How to AWS Sts Assume Role in One Command - Without Jq

The issue - what it takes to assume a role

To assume an AWS role in the CLI, you will have to do something like this:

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

This will give you the following output:

    "Credentials": {
        "AccessKeyId": "someAccessKeyId",
        "SecretAccessKey": "someSecretAccessKey",
        "SessionToken": "someSessionToken",
        "Expiration": "20203-01-02T06:52:13+00:00"
    "AssumedRoleUser": {
        "AssumedRoleId": "idOfTheAssummedRole",
        "Arn": "theARNOfTheRoleIWantToAssume"

But then you will have to 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"

At this stage you can assume the role….

The solution - how to speed this up

You can do this with, or without jq.

Obviously the fewer dependencies the better, so we will do it:

  • Without jq
  • Without multiple exports
  • By using printf built-ins

This also allows the benefit of no credential leakage through /proc..

$(aws sts assume-role \
--role-arn arn:aws:iam::123456789012:role/MyAssumedRole \
--role-session-name MySessionName \
--query "Credentials.[AccessKeyId,SecretAccessKey,SessionToken]" \
--output text))