Skip to content

Instantly share code, notes, and snippets.

@nickv2002
Last active June 27, 2023 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickv2002/d19299c45161ad5c50d6f06db87ccc17 to your computer and use it in GitHub Desktop.
Save nickv2002/d19299c45161ad5c50d6f06db87ccc17 to your computer and use it in GitHub Desktop.
AWS CLI Quick Switch (using fzf)
#!/bin/sh
# sets the AWS_PROFILE env var with a fzf choice
# make sure to prefix the script with a dot so it runs in your native shell, eg `. ./fzf-aws.sh`
# Read the AWS config file
config_file="$HOME/.aws/config"
# called out here to select a different grep, egrep, ripgrep, ag etc
grepBin=$(which grep)
# Use grep to get a list of profiles
profile_choices=$($grepBin -E "^\[profile|^\[default" "$config_file" | cut -d' ' -f2 | tr -d ']' | tr -d '[')
# Use fzf to offer a selection of each profile choice
selected_profile=$(echo "$profile_choices" | fzf)
# Print the selected profile
echo "Selected profile: $selected_profile"
# Check if the variable selected_profile is empty or equal to "default"
if [ -z "$selected_profile" ] || [ "$selected_profile" = "default" ]; then
# Unset AWS_PROFILE if condition is true
unset AWS_PROFILE
else
# Set AWS_PROFILE to the value of selected_profile if condition is false
export AWS_PROFILE="$selected_profile"
fi
@nickv2002
Copy link
Author

nickv2002 commented Jun 26, 2023

Make sure you have fzf in your standard path (it does the hard work of presenting the choices and fuzzy matching them, and it's generally awesome).

You can add the following to your .bashrc file or similar to alias the script and add the profile to your shell prompt. Make sure to change the alias path to point at this script and then source your the file to reload it.

# AWS CLI and quick switch
# https://gist.github.com/nickv2002/d19299c45161ad5c50d6f06db87ccc17
alias awsp=". /path/to/fzf-aws.sh"
function aws_prof {
  local profile="${AWS_PROFILE:=default}"
  echo "aws:${profile}"
}
PS1="\$(aws_prof) $PS1"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment