Skip to content

Instantly share code, notes, and snippets.

@Lowess
Last active April 9, 2025 13:10
Show Gist options
  • Save Lowess/0461d4d5be865a97187971644aafa801 to your computer and use it in GitHub Desktop.
Save Lowess/0461d4d5be865a97187971644aafa801 to your computer and use it in GitHub Desktop.
awsp

πŸ” awsp: Simple AWS SSO Profile Switcher for Your Shell

awsp is a tiny shell function to quickly switch AWS profiles based on AWS SSO account names. It uses your existing SSO session cache and sets the AWS_PROFILE environment variable in your shell.


🧩 What It Does

Given an account name (e.g., media-prod), it:

  1. Locates your active AWS SSO session token.
  2. Lists all available accounts via aws sso list-accounts.
  3. Finds the account ID associated with your input.
  4. Constructs the profile name as SharedAdministratorAccess-ACCOUNT_ID.
  5. Sets the AWS_PROFILE accordingly.

πŸ–₯️ Installation

🐚 For Zsh (with Oh My Zsh)

  1. Save the function into a file:
~/.oh-my-zsh/custom/aws.zsh
  1. Reload your shell:
source ~/.zshrc

βœ… Tip: Oh My Zsh automatically loads any .zsh file in the ~/.oh-my-zsh/custom/ directory on startup.

🐚 For Bash

  1. Add the function to your ~/.bashrc:
nano ~/.bashrc
  1. Paste the function and save the file.

  2. Reload your shell:

source ~/.bashrc

πŸš€ Usage

awsp <account-name>

Example:

awsp media-prod

Output:

βœ… AWS_PROFILE set to 'SharedAdministratorAccess-123456789012'
πŸ”Ž Optional: Check Current AWS_PROFILE

If you run awsp without arguments, it will:

Show usage instructions

Display your current AWS_PROFILE (broken into role and account ID)

Example:

awsp
Usage: awsp <account-name>
πŸ”Ž Currently set AWS_PROFILE: SharedAdministratorAccess-123456789012
   └─ Role:        SharedAdministratorAccess
   └─ Account ID:  123456789012

🧠 Requirements

  • An active AWS SSO session (run aws sso login if needed)
  • jq must be installed (brew install jq on macOS)
  • AWS CLI v2 with SSO configured

πŸ› οΈ Future Ideas

  • Fuzzy matching for account names
  • Override default IAM role name
  • Caching for performance
  • Auto login if session is expired

πŸ“„ License

MIT – use, share, and modify freely !


#!/usr/bin/env zsh
alias awswhoami='aws sts get-caller-identity'
export AWSP_DEFAULT_ROLE="SharedAdministratorAccess"
awsp() {
role_name="${AWSP_DEFAULT_ROLE:-SharedReadOnlyAccess}"
sso_cache_dir="$HOME/.aws/sso/cache"
# Disable nomatch in zsh to prevent globbing errors
if [ -n "$ZSH_VERSION" ]; then
setopt +o nomatch
fi
# Find the latest SSO token file
latest_token_file=$(ls -t "$sso_cache_dir"/*.json 2>/dev/null | head -n 1)
if [ -z "$latest_token_file" ]; then
echo "❌ No SSO token file found. Please login using 'aws sso login'."
return 1
fi
access_token=$(jq -r '.accessToken' "$latest_token_file")
if [ -z "$access_token" ] || [ "$access_token" = "null" ]; then
echo "❌ Access token not found or invalid. Please login using 'aws sso login'."
return 1
fi
if [ -z "$1" ]; then
echo "πŸ‘‰ Usage: awsp <account-name>"
if [ -n "$AWS_PROFILE" ]; then
role_part=$(echo "$AWS_PROFILE" | cut -d'-' -f1)
account_part=$(echo "$AWS_PROFILE" | cut -d'-' -f2)
echo "πŸ”Ž Currently set AWS_PROFILE: $AWS_PROFILE"
echo " └─ Role: $role_part"
echo " └─ Account ID: $account_part"
else
echo "πŸ”Ž No AWS_PROFILE is currently set."
fi
echo ""
echo "πŸ“œ Available accounts from your SSO session:"
aws sso list-accounts --access-token "$access_token" --output json \
| jq -r '.accountList[] | " - \(.accountName) (\(.accountId))"'
return 0
fi
account_name="$1"
account_id=$(aws sso list-accounts \
--access-token "$access_token" \
--output json | jq -r --arg name "$account_name" '.accountList[] | select(.accountName == $name) | .accountId')
if [ -z "$account_id" ]; then
echo "❌ Account '$account_name' not found in your SSO account list."
return 1
fi
profile="${role_name}-${account_id}"
export AWS_PROFILE="$profile"
echo "βœ… AWS_PROFILE set to '$AWS_PROFILE'"
}
### ----------------------------------------
### Completion with caching
### ----------------------------------------
_awsprofile_accounts() {
local cache_file="$HOME/.aws/.awsp-account-cache.json"
local cache_ttl=21600 # 6 hours in seconds
local sso_cache_dir="$HOME/.aws/sso/cache"
local latest_token_file=$(ls -t "$sso_cache_dir"/*.json 2>/dev/null | head -n 1)
local access_token
[[ -z "$latest_token_file" ]] && return
access_token=$(jq -r '.accessToken' "$latest_token_file")
[[ -z "$access_token" || "$access_token" == "null" ]] && return
# Check if cache exists and is fresh
if [[ -f "$cache_file" ]]; then
local now=$(date +%s)
local modified=$(date -r "$cache_file" +%s)
local age=$((now - modified))
if [[ $age -gt $cache_ttl ]]; then
# Cache expired – refresh it
aws sso list-accounts --access-token "$access_token" --output json > "$cache_file" 2>/dev/null
fi
else
# No cache – create it
aws sso list-accounts --access-token "$access_token" --output json > "$cache_file" 2>/dev/null
fi
# Read from cache
[[ -f "$cache_file" ]] || return
compadd -- $(jq -r '.accountList[].accountName' "$cache_file")
}
# Register completion function for `awsp`
compdef _awsprofile_accounts awsp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment