Skip to content

Instantly share code, notes, and snippets.

@tappoz
Last active December 21, 2016 11:12
Show Gist options
  • Save tappoz/34e2c34dd874be8861ce3dcf376af6d0 to your computer and use it in GitHub Desktop.
Save tappoz/34e2c34dd874be8861ce3dcf376af6d0 to your computer and use it in GitHub Desktop.

AWS SDK for python

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()

Get a session from a static key / access key

import boto3
aws_session = boto3.Session(
  aws_access_key_id='FOO',
  aws_secret_access_key='BAR',
  region_name='us-east-1'
)

Find instance's details

the_instance = list(ec2.instances.filter(Filters=[{'Name':'tag:Name', 'Values':[socket.gethostname()]}]))[0]

CloudWatch alarms stuff

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(...)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment