Using awscli with multiple AWS accounts

25 June 2022

Described below is a convenient way to configure and switch awscli between multiple AWS accounts.

Within ~/.aws/ we have several files that define profiles and credentials:

➜  ~ tree ~/.aws
├── config            # Global definitions and variables for each profile
├── credentials       # Credentials for each profile
├── dev-main          # Set-up specifics for "dev-main" profile
├── dev-readonly      # Set-up specifics for "dev-readonly" profile
...

The config file defines profiles and default variables:

➜  ~ cat ~/.aws/config
[default]
region=us-east-1

[dev-main]
region=us-east-1

[dev-readonly]
region=ap-northeast-1

The credentials file defines credentials for the profiles:

[default]
aws_access_key_id = XYZXYZXYZXYZXYZXYZXY
aws_secret_access_key = wxyzwxyzwxyzwxyzwxyzwx+zwxyzwxyzwxyzwxyz

[dev-main]
aws_access_key_id = XYZXYZXYZXYZXYZXYZXY
aws_secret_access_key = wxyzwxyzwxyzwxyzwxyzwx+zwxyzwxyzwxyzwxyz

[dev-readonly]
aws_access_key_id = XYZXYZXYZXYZXYZXYZXY
aws_secret_access_key = wxyzwxyzwxyzwxyzwxyzwx+zwxyzwxyzwxyzwxyz

A matching profile name filename within ~/aws/ can add specifics if needed, and can be sourced to easily switch between profiles.

➜  ~ cat ~/.aws/dev-main
export AWS_PROFILE=dev-main
export AWS_DEFAULT_REGION=us-east-1

➜  ~ cat ~/.aws/dev-readonly
export AWS_PROFILE=dev-readonly
export AWS_DEFAULT_REGION=us-east-2

Now it’s a matter of sourcing the appropriate profile filename from ~/.aws/ to activate different accounts:

➜  ~ source ~/.aws/dev-main
➜  ~ aws s3 ls
2021-03-31 09:11:54 some-bucket-1
2021-08-16 12:31:05 some-bucket-2
2022-03-09 11:12:11 some-bucket-3
...
➜  ~ source ~/.aws/dev-readonly
➜  ~ aws s3 ls
2021-04-12 08:12:54 some-other-bucket-1
2021-08-16 12:33:05 some-other-bucket-2
2022-01-08 09:03:11 some-other-bucket-3
...

comments powered by Disqus