# 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. at_filename=$(ls ~/.aws/sso/cache/*.json | grep -v botocore | head -n 1) at=$(cat $at_filename | jq -r '.accessToken') start_url=$(cat $at_filename | jq -r '.startUrl') region=$(cat $at_filename | jq -r '.region') # Iterate account list account_list=$(echo $available_accounts | jq -r '.accountList | .[] | .accountId') echo $account_list | while read account_id ; do echo "account: $account_id" 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 "$at" --account-id $account_id) role_names=$(echo $account_roles | jq -r '.roleList | .[] | .roleName') echo $role_names | while read role_name ; do echo " role: $role_name" config_profile_name="$account_name-$role_name" hit=$(cat ~/.aws/config | grep $config_profile_name) if [ -z "$hit" ] ; then echo " profile: $config_profile_name not found, adding to config..." cat << EOF >> ~/.aws/config_append [profile $config_profile_name] sso_start_url = $start_url 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" fi done done cat ~/.aws/config_append >> ~/.aws/config rm ~/.aws/config_append echo "Done!"