Q5
How do you assume an IAM role programmatically inside a Boto3 script?
💬Answer
Call AWS Security Token Service (STS) assume_role to fetch temporary credentials, then initialize a new Boto3 session:
import boto3
sts = boto3.client("sts")
assumed_role = sts.assume_role(
RoleArn="arn:aws:iam::123456789012:role/TargetDevOpsRole",
RoleSessionName="AssumedRoleSession"
)
# Extract credentials
creds = assumed_role["Credentials"]
# Create session with temporary credentials
session = boto3.Session(
aws_access_key_id=creds["AccessKeyId"],
aws_secret_access_key=creds["SecretAccessKey"],
aws_session_token=creds["SessionToken"]
)
# Use resources within the context of the assumed role
s3 = session.resource("s3")
Related Python Questions
View All PythonQuestions →
Created by
Apurv Gujjar
DevOps & Cloud Engineer
Specialized in:DevOpsAWSGCPKubernetesTerraformDocker
View Portfolio