AWS Security Token Service

Assume role in other accounts in organisation

#!/bin/bash
 
thisaccount='123456787654'
role='OrganizationAdminRole'
session_name='AssumeSession'
 
# Get all the accounts in the organisation
for account in  $(aws organizations list-accounts --no-paginate | jq -r '.Accounts[] | .Id ')
do
    if [ ${account} = ${thisaccount} ]; then
       break
    else
        printf "Getting temp creds for account sts assume-roles.\n" "${account}"
 
        printf "aws sts assume-role --role-arn arn:aws:iam::"${account}":role/"${role}" \
                --role-session-name "${session_name}" \n"
 
        temp_role=$(aws sts assume-role \
        --role-arn arn:aws:iam::"${account}":role/"${role}" \
        --role-session-name "${session_name}")
        -
        printf "temp_role result:- \n\n"
        printf "${temp_role} \n"
 
        export AWS_ACCESS_KEY_ID=$(echo $temp_role | jq -r .Credentials.AccessKeyId)
        export AWS_SECRET_ACCESS_KEY=$(echo $temp_role | jq -r .Credentials.SecretAccessKey)
        export AWS_SESSION_TOKEN=$(echo $temp_role | jq -r .Credentials.SessionToken)
 
        # Do some interesting stuff in the assumes role account here
        printf "sts get id \n"
        aws sts get-caller-identity
        printf "end of sts get \n"
 
        # unset to go back to main account credentials
        unset AWS_ACCESS_KEY_ID
        unset AWS_SECRET_ACCESS_KEY
        unset AWS_SESSION_TOKEN
 
    fi
done
 
aws/sts.txt · Last modified: 26/02/2024 10:03 by andrew