If one uses more than one AWS account it’s absolutely necessary to configure profiles for AWS CLI.
The configuration is made of two files: .aws/credentials and .aws/config. The former contains access keys to AWS accounts – you should never add the file to the version control, the latter contains additional configuration and can be versioned.
Separate credentials for each account
The typical case is the one with separate credentials for each acount (.aws/credentials):
[default] aws_access_key_id=AKIAIOSFODNN7EXAMPLE aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY [user2] aws_access_key_id=AKIAI44QH8DHBEXAMPLE aws_secret_access_key=je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY
And .aws/config:
[default] region=eu-west-2 output=json [profile user2] region=eu-west-1 output=text
In above configuration each account is independent of each other. In config file we can also specify some addtional customisations like a default region or an output format for AWS CLI commands.
The default stanza configures default account which is used if you don’t specify any profile during execution.
Assume Role configuration
The more interesting case is the one in which we use one account to login to AWS and then we assume role in the same – or another – account, eg. when using AWS Organizations.
In the case we configure only one credentials pair in .aws/credentials file for the login account (in this example it’s for default):
[default] aws_access_key_id=AKIAIOSFODNN7EXAMPLE aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Then, in .aws/config we put settings for login account and then we define profiles with assume roles specified:
[default] region = eu-west-1 output = json aws_account_id = 11111222222333333444 [profile dev] role_arn = arn:aws:iam::123456789012:role/OrganizationAccountAccessRole region = eu-central-1 source_profile = default [profile prod] role_arn = arn:aws:iam::987654321098:role/OrganizationAccountAccessRole region = eu-central-1 source_profile = default
It’s worth mentioning that you can use source_profile to define more than one “hierarchy” of accounts.
Using profiles
There are two main ways to use AWS CLI profiles – first one is to explicite specify profile name using argument to AWS CLI call:
aws --profile prod sts get-caller-identity
Above way is most often used in scripts in which you have to call multiple different profiles. For everyday use setting AWS_PROFILE environment variable is much more convenient:
export AWS_PROFILE=prod aws sts get-caller-identity
Summary
AWS CLI profiles can dramatically simplify and speed up working with AWS. The above mentioned configurations are pretty basic and of course we can further impreve them – eg. by adding MFA – but this is a topic for one of next post :)
If you don’t want to miss more ticks related to AWS subscribe to my blog with RSS, or Facebooku.
Leave a Comment