Skip to content

Instantly share code, notes, and snippets.

@z0ph
Created June 3, 2022 13:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save z0ph/a6831873a07f4cb965504ce38d945203 to your computer and use it in GitHub Desktop.
Save z0ph/a6831873a07f4cb965504ce38d945203 to your computer and use it in GitHub Desktop.
Bash script to run an AWS CLI command across all your AWS Accounts (AWS SSO wide)
#!/bin/bash
# From Victor (zoph) Grenu from zoph.io - https://zoph.io
# Twitter: @zoph
TARGET_ROLE_NAME="AdministratorAccess"
## Get list of AWS accounts using SSO
AWS_ACCESS_TOKEN=$(cat $(ls -1d ~/.aws/sso/cache/* | grep -v botocore) | jq -r "{accessToken} | .[]")
ACCOUNTS_IDS=($(aws sso list-accounts --access-token $AWS_ACCESS_TOKEN | jq -r '.accountList[] | .accountId'))
echo "Number of target AWS Account(s) in AWS SSO: ${#ACCOUNTS_IDS[@]}"
for ACCOUNT_ID in "${ACCOUNTS_IDS[@]}"; do
echo "Checking role list"
ROLES_LIST=$(aws sso list-account-roles --account-id $ACCOUNT_ID --access-token $AWS_ACCESS_TOKEN --output text --query 'roleList[*].roleName')
echo "ROLE_LIST: $ROLES_LIST on $ACCOUNT_ID"
## Get credentials
if [[ "$ROLES_LIST" == *"$TARGET_ROLE_NAME"* ]]; then
echo "--> Getting $TARGET_ROLE_NAME role credential on $ACCOUNT_ID"
CREDENTIALS=$(aws sso get-role-credentials --role-name="$TARGET_ROLE_NAME" --account-id="$ACCOUNT_ID" --access-token=$AWS_ACCESS_TOKEN)
else
echo "There is no $TARGET_ROLE_NAME role, next"
fi
# Configure AWS CLI with custom profile
aws configure set aws_access_key_id $(echo "$CREDENTIALS" | jq -r '.roleCredentials.accessKeyId') --profile sso_assumer
aws configure set aws_secret_access_key $(echo "$CREDENTIALS" | jq -r '.roleCredentials.secretAccessKey') --profile sso_assumer
aws configure set aws_session_token $(echo "$CREDENTIALS" | jq -r '.roleCredentials.sessionToken') --profile sso_assumer
# Your command here will be runned on each AWS account:
aws sts get-caller-identity --profile sso_assumer
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment