Testing assume-role using AWS CLI

2 min read | by Jordi Prats

Once you have configured that one role can assume another role from another account you might want to actually test that you are able to do it. With aws sts you will be able to assume a role

To do so we will need to use aws sts assume-role, setting the role to assume with the option --role-arn and the session name with --role-session-name, for example:

# aws sts assume-role --role-arn "arn:aws:iam::222222222222:role/test/demorole" --role-session-name "test-$(date +%Y%m%d%H%M)"
    "AssumedRoleUser": {
        "AssumedRoleId": "CAT3ARRUBV4FOA7K2ZMX4:test-202103251935", 
        "Arn": "arn:aws:sts::222222222222:assumed-role/demorole/test-202103251935"
    "Credentials": {
        "SecretAccessKey": "...", 
        "SessionToken": "...", 
        "Expiration": "2021-03-25T19:36:48Z", 
        "AccessKeyId": "..."

If the operation does not succeed we will get an AccessDenied as follows:

An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:sts::111111111111:assumed-role/whateverrole/i-6ce63a0563bac58b0 is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::222222222222:role/test/demorole

In some cases, it might be useful to forcefully assume the role, we can do it by setting the appropriate AWS variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN) with the contents of the aws sts assume-role response as follows:


assume_role () {
  NAME=session-$(date +%s)
  SESSION=$(aws sts assume-role --role-arn "$1" --role-session-name $NAME)
  export AWS_ACCESS_KEY_ID=$(echo "$SESSION" | jq .Credentials.AccessKeyId)
  export AWS_SECRET_ACCESS_KEY=$(echo "$SESSION" | jq .Credentials.SecretAccessKey)
  export AWS_SESSION_TOKEN=$(echo "$SESSION" | jq .Credentials.SessionToken)

assume_role arn:aws:iam::222222222222:role/test/demorole

Posted on 01/04/2021