To assume a role using the AWS SDK, you need to use the STS (Security Token Service) client.
Example Code (Python):
import boto3
# Create an STS client
sts_client = boto3.client('sts')
# Assume the role
response = sts_client.assume_role(
RoleArn='arn:aws:iam::123456789012:role/example-role',
RoleSessionName='example-session'
)
# Extract temporary credentials
credentials = response['Credentials']
access_key = credentials['AccessKeyId']
secret_key = credentials['SecretAccessKey']
session_token = credentials['SessionToken']
# Use the temporary credentials to create a new session
assumed_role_session = boto3.Session(
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
aws_session_token=session_token
)
# Use the assumed role session to interact with AWS services
s3_client = assumed_role_session.client('s3')
response = s3_client.list_buckets()
print(response['Buckets'])