Overview
Just a memo for myself.
This shows how to authenticate with a boto3.Session when you hold the credentials obtained from an account switch via AssumeRole.
I’ve also included the case where MFA is enabled.
Implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| mfa_TOTP = raw_input("Enter the MFA code: ")
client=boto3.client( 'sts' )
response = client.assume_role( RoleArn='arn:aws:iam::123456789:role/admin_full', RoleSessionName='mysession', DurationSeconds=3600, SerialNumber='arn:aws:iam::987654321:mfa/myaccount', TokenCode=mfa_TOTP, )
credentials = response['Credentials']
session = boto3.Session(profile_name=session_name, aws_access_key_id = credentials['AccessKeyId'], aws_secret_access_key = credentials['SecretAccessKey'], aws_session_token = credentials['SessionToken'], )
ec2Client = session.client('ec2', region_name='ap-north-east1') resources = ec2.describe_instances()
|
Here, the credentials obtained from AssumeRole via STS are passed to boto3.Session.
That’s all.