Search code examples
amazon-web-servicesamazon-ecrassume-role

bash script for AWS assume-role


I am trying to assume an AWS role within a CI/CD pipeline, hence I have to write a script to change the role via a script. Below is the script to do that, and I used source <script>.sh to replace the existing AWS access & secret keys, and add the session key.

I checked that the 3 env variables are there by echoing them in the terminal.

#!/bin/bash

output="/tmp/assume-role-output.json"

aws sts assume-role --role-arn "arn:aws:iam::<account-id>:role/<rolename>" --role-session-name AWSCLI-Session > $output
AccessKeyId=$(cat $output | jq '.Credentials''.AccessKeyId')
SecretAccessKey=$(cat $output | jq '.Credentials''.SecretAccessKey')
SessionToken=$(cat $output | jq '.Credentials''.SessionToken')

export AWS_ACCESS_KEY_ID=$AccessKeyId
export AWS_SECRET_ACCESS_KEY=$SecretAccessKey
export AWS_SESSION_TOKEN=$SessionToken

However, when I tried running a simple aws command to list ECR images aws ecr list-images --registry-id <id> --repository-name <name>, it gave the following error message.

An error occurred (UnrecognizedClientException) when calling the ListImages operation: 
The security token included in the request is invalid.

I tried manually setting the AWS keys and token in the terminal, and surprisingly the ecr list command works.

export AWS_ACCESS_KEY_ID="XXX"
export AWS_SECRET_ACCESS_KEY="XXX"
export AWS_SESSION_TOKEN="XXX"

Does anyone know what is wrong with my script?


Solution

  • If you use jq the way you do, your export values will contain quotation marks, e.g.

    "ASIASZHPM3IXQXXOXFOY"
    

    rather then:

    ASIASZHPM3IXQXXOXFOY
    

    To avoid this, you have to add -r flag to jq:

    AccessKeyId=$(cat $output | jq -r '.Credentials''.AccessKeyId')
    SecretAccessKey=$(cat $output | jq -r '.Credentials''.SecretAccessKey')
    SessionToken=$(cat $output | jq -r '.Credentials''.SessionToken')