amazon-web-servicesamazon-s3resourcesbucketsts

Obtain s3 bucket information from s3_resource


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:

  1. Use boto3.client equallent api in boto3.resource.
  2. Create boto3.client from boto3.resource then extract information in the same way.

Would anyone share the solution? Thanks!


Solution

  • 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