AWS sts assume role in one command

Arcones's answer is good but here's a way that doesn't require jq:

eval $(aws sts assume-role \
 --role-arn arn:aws:iam::012345678901:role/TrustedThirdParty \
 --role-session-name=test \
 --query 'join(``, [`export `, `AWS_ACCESS_KEY_ID=`, 
 Credentials.AccessKeyId, ` ; export `, `AWS_SECRET_ACCESS_KEY=`,
 Credentials.SecretAccessKey, `; export `, `AWS_SESSION_TOKEN=`,
 Credentials.SessionToken])' \
 --output text)

No jq, no eval, no multiple exports - using the printf built-in (i.e. no credential leakage through /proc) and command substitution:

export $(printf "AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s AWS_SESSION_TOKEN=%s" \
$(aws sts assume-role \
--role-arn arn:aws:iam::123456789012:role/MyAssumedRole \
--role-session-name MySessionName \
--query "Credentials.[AccessKeyId,SecretAccessKey,SessionToken]" \
--output text))

You can store an IAM Role as a profile in the AWS CLI and it will automatically assume the role for you.

Here is an example from Using an IAM role in the AWS CLI - AWS Command Line Interface:

[profile marketingadmin]
role_arn = arn:aws:iam::123456789012:role/marketingadminrole
source_profile = user1

This is saying:

  • If a user specifies --profile marketingadmin
  • Then use the credentials of profile user1
  • To call AssumeRole on the specified role

This means you can simply call a command like this and it will assume the role and use the returned credentials automatically:

aws s3 ls --profile marketingadmin

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.