· 9 years ago · Jan 18, 2017, 10:20 AM
1"""
2This code snippet shows how to dynamically generate
3permissions for API calls to AWS with the boto3
4SDK when using instance profile roles in an ec2
5instance.
6"""
7
8import boto3
9import botocore.session
10
11# Create the client first
12ec2 = boto3.client('ec2')
13
14# Then create a session and generate the credentials
15# dynamically. This magically works
16session = botocore.session.get_session()
17access_key = session.get_credentials().access_key
18secret_key = session.get_credentials().secret_key
19
20# The client is now allowed to perform API calls
21# included in the policy attached to the role. For
22# example, ec2:DescribeInstances and ec2:StartInstances:
23ec2.describe_instances()
24ec2.start_instances(InstanceIds=[<instance_ids>'])