Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading