scott
scott

Reputation: 441

boto3 how to connect different account in different region

I have two different AWS account in two region CN and US, Can I use boto3 connect to different region service? look like following up code.

Boto2 code:

sqs = boto.sqs.connect_to_region(
  region, aws_access_key_id=access_key, aws_secret_access_key=secret_key)

how Boto3 do it like boto2

Upvotes: 6

Views: 19115

Answers (2)

mootmoot
mootmoot

Reputation: 13176

There is many ways to do it. Refer to credential configuration guide for a start.

You can quickly get the info from from boto3.Session

# use aws credential profile
session = boto3.Session(profile_name='dev')

# Or hardcoded your credentail 
session = boto3.Session(
    aws_access_key_id="****",
    aws_secret_access_key="****",
    region_name="us-east-1"
)

Second way is supply hard coded credential in the client call. NOTE: You cannot specify profile_name using client.

client = boto3.client(
    's3',
    aws_access_key_id="****",
    aws_secret_access_key="****",
    region_name="us-east-1"
)

NOTE: If you setup EC2 instance using STS/temporary security credential, then you can retrieve the session token like this.

sts = boto3.client('sts')
my_token = sts.get_session_token()
s3 = boto3.client(
        's3',
        region_name="us-east-1",
        aws_session_token = my_token
    )

Upvotes: 6

franklinsijo
franklinsijo

Reputation: 18300

One possible method would be to use boto Session

from boto3 import Session

# Example: connecting to 'us-east-1' region

session = Session(aws_access_key_id=*****,aws_secret_access_key=****,region_name='us-east-1')
sqs_client = session.client('sqs')
sqs_resource = session.resource('sqs')

Upvotes: 5

Related Questions