Skip to content

Instantly share code, notes, and snippets.

@briceburg
Last active February 5, 2025 15:47
Show Gist options
  • Save briceburg/f9b485dc0fa75fac0b2b169652e422b3 to your computer and use it in GitHub Desktop.
Save briceburg/f9b485dc0fa75fac0b2b169652e422b3 to your computer and use it in GitHub Desktop.
Configure shell completions for activating AWS_PROFILE and optionally refreshing its sso-session (if it expires in 2 hours or less)
# add the bellow blocks to your shell startup files (~/.bashrc || ~/.zshrc &c.)
# you will now have awsp-<profile_name> tab completions for activating configured profiles.
_aws-set-profile(){
echo "activating aws profile: $1" >&2
export AWS_PROFILE="$1"
local sso_session="$(aws configure get sso_session 2>/dev/null)"
if [[ -n "$sso_session" ]]; then
local expires=$(aws configure export-credentials | jq -r '.Expiration')
if [[ -z "$expires" || $(gdate --date "$expires" +'%s') -lt $(gdate --date "+2 hours" +'%s') ]]; then
echo "refreshing sso session" >&2
aws sso login --sso-session "$sso_session"
fi
fi
}
for p in $(aws configure list-profiles); do
[[ "$p" == "default" ]] && continue
eval "awsp-$p(){ _aws-set-profile \"$p\" }"
done
# example ~/.aws/config - replace acme with your org + default region + account ids and role names
[default]
output=json
region = us-east-1
[sso-session acme]
sso_start_url = https://acme.awsapps.com/start
sso_region = us-east-1
sso_registration_scopes = sso:account:access
[profile acme-prod-admin]
sso_session = acme
sso_account_id = 12345
sso_role_name = AdministratorAccess
[profile acme-dev-admin]
sso_session = acme
sso_account_id = 67890
sso_role_name = AdministratorAccess
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment