Switching AWS Profiles

I tend to have a lot of projects on the go at once, whether they are Bulletproof related, personal side projects or helping out the odd startup. This means that I tend to need to switch between AWS accounts a lot.  Like many others I user AWS profiles to manage credentials for different AWS accounts. These credentials are stored in $HOME/.aws/credentials and are used by the various AWS SDKs, the aws-cli and frameworks like serverless.

Currently, I have seven different profiles. This means I spend a lot of time manually typing things like:

export AWS_PROFILE=inodes

I like to use lots of terminal tabs, so doing this every time I open a new tab gets old pretty quickly. After a long week of hacking marathons, I decided I needed some tab completion goodness and came up with the following.

# AWS Profile switcher

aws-profile() {
  export AWS_PROFILE=$1
}

_aws_profile_completer() {
  _commands=$(cat ~/.aws/credentials  | grep '^\[' | sed 's/.$//;s/^.//')

  local cur prev
  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  COMPREPLY=( $(compgen -W "${_commands}" -- ${cur}) )

  return 0
}

complete -F _aws_profile_completer aws-profile

This allows me to type (tab complete) aws-profile and then complete the name of the AWS profile.

aws-profiles demo

The next thing I want to explore is direnv, which was recommended by Greg Cockburn. This should enable auto profile switching based on the directory I’m in and speed things up even more.