python code to access s3 bucket from different account - Using Separate Boto3 Sessions/Profiles
This method is typically used to copy objects between buckets without saving them locally.
import boto3
import io
# Source Account Credentials (can be loaded from .env file or config)
SOURCE_ACCESS_KEY = '...'
SOURCE_SECRET_KEY = '...'
SOURCE_BUCKET = 'my-source-bucket'
# Destination Account Credentials
DESTINATION_ACCESS_KEY = '...'
DESTINATION_SECRET_KEY = '...'
DESTINATION_BUCKET = 'their-destination-bucket'
OBJECT_KEY = 'path/to/object.txt'
# 1. Create a client for the source account
source_client = boto3.client(
's3',
aws_access_key_id=SOURCE_ACCESS_KEY,
aws_secret_access_key=SOURCE_SECRET_KEY
)
# 2. Get the object data as a stream (file-like object)
source_object = source_client.get_object(Bucket=SOURCE_BUCKET, Key=OBJECT_KEY)
object_body = source_object['Body']
# 3. Create a client for the destination account
destination_client = boto3.client(
's3',
aws_access_key_id=DESTINATION_ACCESS_KEY,
aws_secret_access_key=DESTINATION_SECRET_KEY
)
# 4. Upload the file-like object to the destination bucket
destination_client.upload_fileobj(
object_body,
DESTINATION_BUCKET,
OBJECT_KEY,
ExtraArgs={'ACL': 'bucket-owner-full-control'} # Ensure destination account owns the object
)
print(f"Successfully transferred {OBJECT_KEY} from {SOURCE_BUCKET} to {DESTINATION_BUCKET}.")
Comments
Post a Comment