Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save seanorama/7eaa039ee1405324d28fefde35362a80 to your computer and use it in GitHub Desktop.
Save seanorama/7eaa039ee1405324d28fefde35362a80 to your computer and use it in GitHub Desktop.
Automatically configure AWS SSO configuration file for all available accounts and roles
#!/usr/bin/env bash -e
# How to use this script:
# 1. Follow these instructions to configure a single AWS account to do initial login with SSO
# https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html
# 2. Export AWS_PROFILE=... and then run "aws sso login" to get an SSO token
# 3. Once signed in with AWS SSO, run this script to automatically list out all the other accounts and roles and add them to your config file
# If you want to filter roles / accounts in the process, or validate config before committing it, you can customise the script to do this.
config_file="${HOME}/.aws/config.d/aws_sso.config"
echo > "${config_file}.temp"
eval $(jq -r 'to_entries[]|"\(.key)=\(.value)"' $(ls -1t ~/.aws/sso/cache/*.json | grep -v botocore | head -n 1))
# Iterate account list
available_accounts=$(aws sso list-accounts --access-token "${accessToken}" --region "${region}")
n_accounts=$(echo "${available_accounts}" | jq '.accountList | length')
echo "Accounts found: ${n_accounts}"
account_list=$(echo "${available_accounts}" | jq -r '.accountList | .[] | .accountId')
while IFS= read -r account_id ; do
account_data=$( echo "${available_accounts}" | jq -r ".accountList | .[] | select( .accountId == \"$account_id\" )" )
account_name=$(echo "${account_data}" | jq -r '.accountName // .accountId' | xargs)
account_roles=$(aws sso list-account-roles --access-token "${accessToken}" --account-id "${account_id}" --region "${region}")
role_names=$(echo "${account_roles}" | jq -r '.roleList | .[] | .roleName')
while read -r role_name ; do
config_profile_name="${account_name}-${role_name}"
hit=$(grep "${config_profile_name}" ~/.aws/config || echo "")
if [ -z "${hit}" ] ; then
cat << EOF >> "${config_file}.temp"
[profile $config_profile_name]
sso_startUrl = $startUrl
sso_region = $region
sso_account_id = $account_id
sso_role_name = $role_name
sts_regional_endpoints = regional
region = $region
EOF
else
echo " profile: ${config_profile_name} found, doing nothing..."
fi
done < <(printf '%s\n' "${role_names}")
done < <(printf '%s\n' "${account_list}")
mv "${config_file}.temp" "${config_file}"
echo "Your AWS SSO configs have been written to ${config_file}."
echo 'Now execute `gimme-aws-config` to have the configs merged to ~/.aws/config'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment