AWS CLI: Configuring authentication and profiles

aws awscli SDK authentication profiles

2 min read | by Jordi Prats

With the .aws/config and .aws/credentials files we can are used for configuring and authenticating for the AWS cli or any tool that uses the AWS SDK with AWS.

Each file has a different purpose:

  • ~/.aws/config: This file stores configuration settings for AWS CLI and SDKs, including profiles, regions, output format, and roles to assume.
  • ~/.aws/credentials: This file holds AWS access key IDs and secret access keys.

To configure an account, first we'll need to add the credentials to the ~/.aws/credentials file, giving it a name and the access key and secret key:

[prod]
aws_access_key_id = YOUR_ADMIN_ACCESS_KEY_ID
aws_secret_access_key = YOUR_ADMIN_SECRET_ACCESS_KEY

If we can use the IAMUser directly, without assuming any role, we can just add the profile to the ~/.aws/config file with any settings we want to use by default, for example:

[default]
output=json
region = us-west-2

[profile prod]
region = us-east-1

If we nee to assume a role, we can use the role_arn setting to assume the role:

[profile prod-demo]
region = us-east-1
role_arn = arn:aws:iam::123456789012:role/demo-role
source_profile = prod

Given the case that we need to assume a specific role that cannot be assumed directly, we can use a chain of profiles to do so. For example, first-role will use the credentials to assume the role. We can then use the previous profile, first-role, to define the second role to assume:

[profile first-role]
region=eu-west-2
role_arn=arn:aws:iam::123456789012:role/first-role
source_profile=prod

[profile second-role]
region=eu-west-2
role_arn=arn:aws:iam::123456789012:role/second-role
source_profile=first-role

Once we have the profiles configured, we can use the --profile flag if available or the AWS_PROFILE environment variable to use the profile we want to use:

AWS_PROFILE=second-role aws s3 ls

Posted on 04/09/2024

Categories