3

When using the AWS CLI it references the credentials and config files located in the ~/.aws directory. And you use the --profile flag to indicate which account you want. Such as:

aws ec2 describe-instances --profile=company-lab
aws ec2 describe-instances --profile=company-nonprod 

etc.

But I am new to scripting in python 3 and boto 3 and want to do the same thing there. How can I switch between AWS accounts using python?

rpanai
  • 12,515
  • 2
  • 42
  • 64
bluethundr
  • 1,005
  • 17
  • 68
  • 141
  • 1
    Consider putting your credentials in enviroment variables, and then switching environments depending on your needs. This will keep sensitive data out of your code. – bwest Mar 03 '19 at 16:13
  • 3
    Possible duplicate of [How to choose an AWS profile when using boto3 to connect to CloudFront](https://stackoverflow.com/questions/33378422/how-to-choose-an-aws-profile-when-using-boto3-to-connect-to-cloudfront) – Dunedan Mar 03 '19 at 17:08

1 Answers1

4

Just use the `profile_nameˋ parameter when creating the session object.

session = boto3.Session(profile_name='dev')
# Any clients created from this session will use credentials
# from the [dev] section of ~/.aws/credentials.
dev_s3_client = session.client('s3')

https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html

Sébastien Stormacq
  • 14,301
  • 5
  • 41
  • 64