Skip to content

Instantly share code, notes, and snippets.

@tmclnk
Created November 4, 2025 20:23
Show Gist options
  • Select an option

  • Save tmclnk/fb1a4ba313055a1530667c9b5e263eef to your computer and use it in GitHub Desktop.

Select an option

Save tmclnk/fb1a4ba313055a1530667c9b5e263eef to your computer and use it in GitHub Desktop.
AWS Config File Generator
#!/bin/bash
# Generate AWS config file entries for all SSO profiles
# SSO session name: dc
set -e
if [ -z "$SSO_SESSION" ]; then
echo "SSO_SESSION variable is required" >&2
exit 1
fi
# Login to SSO session
echo "Logging in to AWS SSO session '$SSO_SESSION'..." >&2
aws sso login --sso-session "$SSO_SESSION"
echo "" >&2
echo "Fetching AWS SSO accounts and roles..." >&2
echo "" >&2
# Get the access token from the cached credentials
SSO_CACHE_DIR="$HOME/.aws/sso/cache"
ACCESS_TOKEN=$(jq -r '.accessToken' $(ls -t "$SSO_CACHE_DIR"/*.json | head -1))
if [ -z "$ACCESS_TOKEN" ] || [ "$ACCESS_TOKEN" = "null" ]; then
echo "Error: Could not find access token. Please ensure you're logged in." >&2
exit 1
fi
# Get SSO start URL and region from the config
SSO_START_URL=$(aws configure get sso_session.${SSO_SESSION}.sso_start_url)
SSO_REGION=$(aws configure get sso_session.${SSO_SESSION}.sso_region)
if [ -z "$SSO_START_URL" ] || [ -z "$SSO_REGION" ]; then
echo "Error: Could not find SSO configuration for session '$SSO_SESSION'" >&2
exit 1
fi
echo "Generating AWS config profiles..." >&2
echo "" >&2
# Get all accounts
accounts=$(aws sso list-accounts --access-token "$ACCESS_TOKEN" --query 'accountList[*].[accountId,accountName]' --output text)
# For each account, get available roles and generate config
while IFS=$'\t' read -r account_id account_name; do
roles=$(aws sso list-account-roles --account-id "$account_id" --access-token "$ACCESS_TOKEN" --query 'roleList[*].roleName' --output text)
for role in $roles; do
profile_name="${account_id}-${role}"
echo "[profile ${profile_name}]"
echo "sso_session = ${SSO_SESSION}"
echo "sso_account_id = ${account_id}"
echo "sso_role_name = ${role}"
echo "region = us-east-1"
echo "output = json"
echo ""
done
done <<<"$accounts"
echo "Done! Copy the output above and paste it into ~/.aws/config" >&2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment