Skip to content

Instantly share code, notes, and snippets.

@gabrielferreira
Created March 24, 2016 21:40
Show Gist options
  • Select an option

  • Save gabrielferreira/fff0cae59ca9efd0e72d to your computer and use it in GitHub Desktop.

Select an option

Save gabrielferreira/fff0cae59ca9efd0e72d to your computer and use it in GitHub Desktop.

Connect Cross Account using AWS CLI

First you need to configure the access to the origin account

$ export AWS_ACCESS_KEY_ID="<AWS_ACCESS_KEY_ID>"
$ export AWS_SECRET_ACCESS_KEY="<AWS_SECRET_ACCESS_KEY>"

execute the command bellow to connect to the account

If you don't have a MFA configured

$ aws sts assume-role --role-arn arn:aws:iam::<ACCOUNT_ID>:role/<ROLE_NAME> --role-session-name "<SESSION_NAME>"

Where ACCOUNT_ID is the destination ACCOUNT_ID ROLE_NAME is the name of the role that you want to assume SESSION_NAME is a nick name that you want to provide ORIGIN_ACCOUNT_ID is the ID of the origin account

If you have a MFA configured you need to pass the MFA_ID and the MFA_CODE

$ aws sts assume-role --role-arn arn:aws:iam::<ACCOUNT_ID>:role/<ROLE_NAME> --role-session-name "<SESSION_NAME>" --serial-number "arn:aws:iam::<ORIGIN_ACCOUNT_ID>:mfa/<MFA_ID>" --token-code "<MFA_CODE>"

The command executed will print something like

{
    "AssumedRoleUser": {
        "AssumedRoleId": "<ASSUME_ROLE_ID>:<SESSION_NAME>",
        "Arn": "arn:aws:sts::<ACCOUNT_ID>:assumed-role/<ROLE_NAME>/<SESSION_NAME>"
    },
    "Credentials": {
        "SecretAccessKey": "<AWS_SECRET_ACCESS_KEY>",
        "SessionToken": "<AWS_SESSION_TOKEN>",
        "Expiration": "2016-03-24T16:53:55Z",
        "AccessKeyId": "<AWS_ACCESS_KEY_ID>"
    }
}

Now you need to copy the informations and export the environment variables again

$ export AWS_ACCESS_KEY_ID="<AWS_ACCESS_KEY_ID>"
$ export AWS_SECRET_ACCESS_KEY="<AWS_SECRET_ACCESS_KEY>"
$ export AWS_SESSION_TOKEN="<AWS_SESSION_TOKEN>"

Done, every command that you execute now calling the CLI will use the destination account

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment