How do you assume a role into another account with boto3?
AdvancedConceptboto3 & AWS automation
Answer
sts = boto3.client("sts")
creds = sts.assume_role(RoleArn="arn:aws:iam::222222222222:role/audit-readonly",
RoleSessionName="cloudaudit", DurationSeconds=3600)["Credentials"]
session = boto3.Session(aws_access_key_id=creds["AccessKeyId"],
aws_secret_access_key=creds["SecretAccessKey"],
aws_session_token=creds["SessionToken"])
For long-running jobs, use a profile with role_arn and source_profile (or credential_source = Ec2InstanceMetadata) so botocore refreshes credentials automatically, instead of hand-built static sessions that expire mid-run with ExpiredToken.
More on boto3 & AWS automation
What is the difference between a boto3 Session, client and resource?BeginnerHow does boto3 find credentials?BeginnerHow does boto3 decide the region, and what is the gotcha with `AWS_REGION`?AdvancedWhy do you need paginators, and how do you use them?BeginnerWhat is JMESPath `search()` on paginators?AdvancedHow do you handle errors from boto3?Beginner