Tag function provided in ec2. It is convenient to use it like an environment variable. Look at a specific tag and change the configuration file read by the application at runtime. Toka Toka. ec2 has API to get your own metadata. Let's try it with boto3.
First of all, as a preliminary preparation, make access_key_id and secret_access_key visible from the application side. It's okay to write solid in the source code, but it's not secure, so export it to the shell.
$ export AWS_KEY='some-key'
$ export AWS_SECRET='some-secret'
$ export AWS_REGION='ap-northeast-1'
Try to get this from python.
console
>>> import os
>>> os.environ.get('AWS_KEY')
'some-key'
>>> os.environ.get('AWS_SECRET')
'some-secret'
>>> os.environ.get('AWS_REGION')
'ap-northeast-1'
If you can confirm that you can get it, try to get the tag actually assigned to you.
console
>>> import os
>>> import urllib2
>>> from boto3.session import Session
>>>
#My instance from the metadata API-Fetch the id.
>>> instance_id = urllib2.urlopen('http://169.254.169.254/latest/meta-data/instance-id').read()
>>>
#Create a session for aws api.
>>> aws = Session(aws_access_key_id=os.environ.get('AWS_KEY'),
... aws_secret_access_key=os.environ.get('AWS_SECRET'),
... region_name=os.environ.get('AWS_REGION'))
>>>
#Create an ec2 object.
>>> ec2 = aws.resource('ec2')
# instance-Create an instance object by specifying id. So to speak, this is myself.
>>> instance = ec2.Instance(id=instance_id)
>>>
#Get the tag completely. It's a little difficult to use, so I'm shaping it.
>>> tags = dict([(tag['Key'], tag['Value']) for tag in instance.tags])
#It is listed here. Should be.
>>> tags
{'Name': 'API_PROD', ...}
Personally, I always add an Env tag, and I try to decide the configuration file to read by looking at it. If you do this, you can change the settings around db and the bucket of s3 at runtime even with the same ami, which is convenient and convenient :-)
Recommended Posts