Created
June 3, 2022 13:46
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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