I have a python program to obtain aws s3 bucket information from boto3.client:
s3_client = boto3.client('s3')
response = s3_client.list_buckets() # get bucket list
bucket_location = s3_client.get_bucket_location # get bucket region
log_location = s3_client.get_bucket_logging # get bucket access log location
inventory_location = s3_client.list_bucket_inventory_configurations # get bucket inventory location
I want to get same information under another account. Here's to code to assume_role:
sts_client = boto3.client('sts')
sts_credentials = sts_client.assume_role(
RoleArn="<another_role>",
RoleSessionName="<session_name>"
)
credentials = sts_credentials['Credentials']
s3_resource = boto3.resource(
's3',
aws_access_key_id=credentials['AccessKeyId'],
aws_secret_access_key=credentials['SecretAccessKey'],
aws_session_token=credentials['SessionToken']
)
The s3_resource is created successfully. 2 options come into my mind to continue but not sure which one is feasible:
Would anyone share the solution? Thanks!
Use a new client:
import boto3
credentials = boto3.client('sts').assume_role(
RoleArn="arn:aws:iam::0000000000000000:role/custom-role",
RoleSessionName="AssumeRoleSession1"
)['Credentials']
session = boto3.Session(
aws_access_key_id=credentials['AccessKeyId'],
aws_secret_access_key=credentials['SecretAccessKey'],
aws_session_token=credentials['SessionToken']
)
s3_client = session.client('s3')
response = s3_client.list_buckets() # get bucket list