How to login with AWS CLI using credentials profiles

Janne Annala picture Janne Annala · May 29, 2017 · Viewed 17.5k times · Source

I want to setup multiple AWS profiles so that I can easily change settings and credentials when jumping between projects.

I've read the AWS documentation but it's quite vague about how to select what profile you want to use when logging in.

When I'm trying to login it's just giving me this error which seems to indicate that it's not picking up any credentials.

An error occurred (UnrecognizedClientException) when calling the GetAuthorizationToken operation: The security token included in the request is invalid.

Answer

Janne Annala picture Janne Annala · May 29, 2017

To setup multiple profiles for AWS login you need to the following:

  1. Setup the credentials file with your access keys
  2. Setup default settings for profiles (optional)
  3. Set the AWS_PROFILE environment variable
  4. Remove previous AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY

1: ~/.aws/credentials

[default]
aws_access_key_id =
aws_secret_access_key =

[cat]
aws_access_key_id = XXXX
aws_secret_access_key = XXXXXXXXXXXX

[dog]
aws_access_key_id = XXXX
aws_secret_access_key = XXXXXXXXXXXX

2: ~/.aws/config

[default]
region = eu-central-1

[profile cat]
region = us-west-2

[profile dog]
region = ap-northeast-1

3. Select profile

The selected profile is determined by the $AWS_PROFILE environment variable. In bash this could be done in ~\.bash_profile by adding a line export AWS_PROFILE="cat". To switch profiles in the current terminal, type AWS_PROFILE=dog.

4. Remove global settings

You also need to make sure that the environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are not set because the aws-cli will give priority to those variables over profiles.

Running

You can then login to the AWS service of your choice. To see what profile is currently in use echo $AWS_PROFILE. Example command for ECR login would be $(aws ecr get-login)

Debugging

If you're still having problems you can add the --debug flag to see what credentials it's using for the command.