14

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?

potom
  • 340
  • 1
  • 2
  • 8
  • Docs: [Assuming an IAM Role in the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-role.html) & [AWS CLI Configuration Variables](https://docs.aws.amazon.com/cli/latest/topic/config-vars.html). – kenorb Mar 18 '19 at 21:44

1 Answers1

17

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:

kenorb
  • 5,943
  • 1
  • 44
  • 53
MLu
  • 23,798
  • 5
  • 54
  • 81
  • this requires `customer-project` role having a trust policy allowing `customer-login` to assumerole, yes? – Neil McGuigan Mar 07 '21 at 22:08
  • Thanks, this worked, only I had to add ```source_profile = default``` to your answer, otherwise I got a *Partial credentials found in assume-role, missing: source_profile or credential_source* error – Paul Oprea Dec 03 '21 at 21:06