I'm setting up my AWS CLI. To access to AWS services like EC2, I have to switch roles.

I used the command aws sts assume-role, and it spit out JSON with Credentials and AssumedRoleUser, complete with a session token. That's great!

Now what? I've googled around, but I cannot figure what to do with generated JSON. How do I tell AWS CLI, "Use this JSON to authenticate with this role"?

Here is the (redacted) JSON I have:

    "Credentials": {
        "AccessKeyId": "XXXXXXXXXXW5YABBKUXQ",
        "SecretAccessKey": "XXXXXXXXXXXXXXXXXXXXB2EFEUmCtuwbJPcMBF02",
        "SessionToken": "XXXXXXXXXXsi6md6PTNHYjHUljav",
        "Expiration": "2021-12-03T04:59:02+00:00"
    "AssumedRoleUser": {
        "AssumedRoleId": "XXXXXXXXXX:dev",
        "Arn": "arn:aws-us-gov:sts::999999999991:assumed-role/PROJADMIN/dev"

2 Answers 2


I've done this in a bash script and read three of the four elements in the awscli output to set in environment variables for a later awscli command.

It uses jq to extract the individual values from the JSON reply, something like this:

# get session credentials via sts assume-role
    aws sts assume-role \
      --role-arn "${role_arn}" \
      --duration-seconds ${session_secs} \
      --role-session-name what-im-doing-$$

# now extract the items into environment variables for my main command
export AWS_SESSION_TOKEN=$(jq -rM '.Credentials.SessionToken' <<<"${ar_json}")
export AWS_ACCESS_KEY_ID=$(jq -rM '.Credentials.AccessKeyId' <<<"${ar_json}")
export AWS_SECRET_ACCESS_KEY=$(jq -rM '.Credentials.SecretAccessKey' <<<"${ar_json}")

# my main command that needs the role permissions
aws s3 sync "${bucket_url}" "${local_dir}"

There's some error checking I've omitted to keep the example simple. The -r option tells jq to not put quotes around its output, and the -M option tells jq to not colorize its output.

Putting these credentials into environment variables carries a risk of exposing them to someone on the same host who is using ps with options to view process environments. The session credentials may expire quickly enough to not worry about it.

A more secure way to pass the credentials to your awscli commands would be through writing them to configuration files, as another answer suggested.


The answer was to ignore everything in the JSON except the "SessionToken". To use the session token, either add this to the credentials file profile with the same AWS keys, or export it as an env var


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.