Skip to content

Instantly share code, notes, and snippets.

@aconz2
Created August 24, 2017 16:14
Show Gist options
  • Save aconz2/9975a90542d6b0a6baf1c9fbbf72a605 to your computer and use it in GitHub Desktop.
Save aconz2/9975a90542d6b0a6baf1c9fbbf72a605 to your computer and use it in GitHub Desktop.
How to assume a role in boto3
def boto3_with_role(role_arn, session_prefix, external_id, **kwargs):
"""
Create a partially applied session to assume a role with an external id.
A unique session_name will be generated by {session_prefix}_{time}
`session` can be passed, otherwise the default sesion will be used
see: http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-api.html
"""
res = sts.assume_role(
RoleArn = role_arn,
RoleSessionName = '{}_{}'.format(session_prefix, int(time.time())),
ExternalId = external_id,
**kwargs
)
creds = res['Credentials']
return partial(boto3.session.Session,
aws_access_key_id = creds['AccessKeyId'],
aws_secret_access_key = creds['SecretAccessKey'],
aws_session_token = creds['SessionToken']
)
# use like this
Session = boto3_with_role('arn:aws:iam::1234567890:role/RoleName', 'MyPrefix', '12345')
my_session = Session()
ec2 = my_session.resource('ec2')
# or connect to a different region (which is the whole point to partially apply Session so we can use with multiple regions)
s3 = Session(region_name='us-east-2').resource('s3')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment