AWS sts assume role in one command

Arcones picture Arcones · Aug 4, 2020 · Viewed 7.1k times · Source

To assume an AWS role in the CLI, I do the following command:

aws sts assume-role --role-arn arn:aws:iam::123456789123:role/myAwesomeRole --role-session-name test --region eu-central-1

This gives to me an output that follows the schema:

{
    "Credentials": {
        "AccessKeyId": "someAccessKeyId",
        "SecretAccessKey": "someSecretAccessKey",
        "SessionToken": "someSessionToken",
        "Expiration": "2020-08-04T06:52:13+00:00"
    },
    "AssumedRoleUser": {
        "AssumedRoleId": "idOfTheAssummedRole",
        "Arn": "theARNOfTheRoleIWantToAssume"
    }
}

And then I manually copy and paste the values of AccessKeyId, SecretAccessKey and SessionToken in a bunch of exports like this:

export AWS_ACCESS_KEY_ID="someAccessKeyId"                                                                                      
export AWS_SECRET_ACCESS_KEY="someSecretAccessKey"
export AWS_SESSION_TOKEN="someSessionToken"

To finally assume the role.

How can I do this in one go? I mean, without that manual intervention of copying and pasting the output of the aws sts ... command on the exports.

Answer

Arcones picture Arcones · Aug 4, 2020

Finally, a colleague shared with me this awesome snippet that gets the work done in one go:

eval $(aws sts assume-role --role-arn arn:aws:iam::123456789123:role/myAwesomeRole --role-session-name test | jq -r '.Credentials | "export AWS_ACCESS_KEY_ID=\(.AccessKeyId)\nexport AWS_SECRET_ACCESS_KEY=\(.SecretAccessKey)\nexport AWS_SESSION_TOKEN=\(.SessionToken)\n"')

Apart from the AWS CLI, it only requires jq which is usually installed in any Linux Desktop.