IAM - Assume role in other account

Framework to assume a role in a different account.

#!/bin/bash

# Reads in a list of account numbers, assumes a set role
# (with the required policy to perform whatever...) and does whatever.

FILENAME='accountlist.txt'
export AWS_DEFAULT_REGION='eu-west-2'

while read -r ACCOUNT;
  do
    echo "Using ${ACCOUNT} to get who I am:-"
    aws sts get-caller-identity
    
    echo "Changing role."
    
    # get credentials to use in remote account
    aws sts assume-role  \
      --role-arn arn:aws:iam::"${ACCOUNT}":role/Test_role-to-assume \
      --role-session test_assume > cred-$$.txt

    ACCESSKEY=$(jq -r '.Credentials.AccessKeyId' < cred-$$.txt)
    SECRETACCESSKEY=$(jq -r '.Credentials.SecretAccessKey' < cred-$$.txt)
    SESSIONTOKEN=$(jq -r '.Credentials.SessionToken' < cred-$$.txt)

    echo "${ACCESSKEY}"
    echo "${SECRETACCESSKEY}"
    echo "${SESSIONTOKEN}"

    export AWS_ACCESS_KEY_ID="${ACCESSKEY}"
    export AWS_SECRET_ACCESS_KEY="${SECRETACCESSKEY}"
    export AWS_SESSION_TOKEN="${SESSIONTOKEN}"

    echo "Who am I now?"
    aws sts get-caller-identity
  done < "${FILENAME}"


# Clean up old temp file
rm cred-$$.txt