How to “switch role” in aws-cli?

I'm contracting for a company that has multiple aws accounts. They gave me access to the Login account and I "Switch Role" in the web console to the Project account I work on. In the web gui it works.

How do I do the same with aws-cli?? I only have access keys for the Login account and I don’t have permissions to create a user and access keys in the Project account. Is it even possible?


Solution 1:

Of course it's possible!

Let's assume you've got your Login account credentials in ~/.aws/credentials, probably something like this:

~ $ cat ~/.aws/credentials
[customer-login]
aws_access_key_id = AKIABCDEFGHJKLMNOPQR
aws_secret_access_key = ZxCvBnMaSdFgHjKlQwErTyUiOp

All you need to do is to add another profile to ~/.aws/credentials that will use the above profile to switch account to your project account role. You will also need the Project account Role ARN - you can find that in the web console in IAM -> Roles after you switch to the Project account. Let's say the Project account number is 123456789012...

[customer-project]
role_arn = arn:aws:iam::123456789012:role/your-project-role-name   # << Change this
source_profile = customer-login

With that in place you can test if it works:

~ $ aws --profile customer-project sts get-caller-identity
{
    "Account": "123456789012",
    "UserId": "AROA1B2C3D4E5F6G7H8I:botocore-session-1538120713",
    "Arn": "arn:aws:sts::123456789012:assumed-role/your-project-role-name/botocore-session-1538120713"
}

As you can see you're now in the Project account as confirmed by the Account id 123456789012.

If you want to always use this profile with aws-cli you can do so:

~ $ export AWS_DEFAULT_PROFILE=customer-project
~ $ aws sts get-caller-identity
... will be the same output as above, even without specifying --profile ...

For more info check out this post: https://aws.nz/best-practice/cross-account-access-with-aws-cli/

Check also:

  • Assuming an IAM Role in the AWS CLI.
  • AWS CLI Configuration Variables.