python code to access s3 bucket from different account - Assuming an IAM Role
import boto3
# 1. Configuration for the destination account's role
DESTINATION_ACCOUNT_ID = '123456789012' # Replace with the destination account ID
DESTINATION_ROLE_NAME = 'CrossAccountUploadRole' # Replace with the role name
ROLE_ARN = f"arn:aws:iam::{DESTINATION_ACCOUNT_ID}:role/{DESTINATION_ROLE_NAME}"
BUCKET_NAME = 'their-destination-bucket' # Replace with the destination bucket name
FILE_NAME = 'local_file.txt'
OBJECT_KEY = 'uploads/file.txt' # The key (path) in the S3 bucket
# 2. Assume the role
sts_client = boto3.client('sts')
assumed_role_object = sts_client.assume_role(
RoleArn=ROLE_ARN,
RoleSessionName="CrossAccountS3UploadSession"
)
credentials = assumed_role_object['Credentials']
# 3. Create a new S3 client using the temporary 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')
# 4. Upload the file
print(f"Uploading {FILE_NAME} to {BUCKET_NAME} in another account...")
s3_client.upload_file(
Filename=FILE_NAME,
Bucket=BUCKET_NAME,
Key=OBJECT_KEY,
# This grants the bucket owner full control of the object
ExtraArgs={'ACL': 'bucket-owner-full-control'}
)
print("Upload successful.")
Comments
Post a Comment