To get temporary credentials from within an EC2 instance for a given IAM role iam_role
:
import urllib2
import json
# Instance metadata docs:
# http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#instance-metadata-security-credentials
http_data = urllib2.urlopen('http://169.254.169.254/latest/meta-data/iam/security-credentials/'+iam_role)
security_credentials = json.loads(http_data.read())
To use the previous credentials to open a session e.g. for CloudWatch (here using botocore
but it should be the same with boto3
):
import botocore.session
cloudwatch = botocore.session.get_session().create_client(
'cloudwatch',
aws_access_key_id=security_credentials['AccessKeyId'],
aws_secret_access_key=security_credentials['SecretAccessKey'],
aws_session_token=security_credentials['Token'],
region_name='us-east-1'
)
cloudwatch.put_metric_alarm(...)
To get the instance ID from within a running EC2 instance:
import urllib2
# Retrieve it via the Instance Metadata API
instance_id = urllib2.urlopen('http://169.254.169.254/latest/meta-data/instance-id').read()
import boto3
aws_session = boto3.Session(
aws_access_key_id='FOO',
aws_secret_access_key='BAR',
region_name='us-east-1'
)
the_instance = list(ec2.instances.filter(Filters=[{'Name':'tag:Name', 'Values':[socket.gethostname()]}]))[0]
the_list = list(cloudwatch.alarms.filter(AlarmNamePrefix='tool'))
cloudwatch = aws_session.resource('cloudwatch')
current_metric = cloudwatch.Metric(namespace=current_alarm_params['Namespace'], name=current_alarm_params['MetricName'])
current_metric.put_alarm(...)