Blog About
I use the AWS CLI client a lot for work, where i constantly have to switch between different accounts.
I wrote this handy little Bash script that makes it easy to switch between profiles on the fly. No more setting environment variables or using the --profile
flag like a noob.
Script has been tested to work with Bash 5 on Ubuntu 20.04 and macOS Catalina (Version 10.15.7)
Edit 30.10.2022 - Use Awsume instead of this script.
#!/bin/bash
# check args
if [[ $# -ne 1 ]]; then
echo "usage: aws-profile <profile name>"
echo "profiles can be defined in ~/.aws/credentials"
exit 0
else
# save original profile before exporting
original_profile=$(echo $AWS_DEFAULT_PROFILE)
export AWS_DEFAULT_PROFILE=${1}
fi
# Check if profile exists, revert if not
aws configure list
if [[ $? != 0 ]]; then
echo "aborting.."
export AWS_DEFAULT_PROFILE=${original_profile}
echo -e "\nDone"
else
echo -e "\nOK"
echo "switched to profile: ${1}"
fi
AWS CLI reads both the access and secret keys from environment variables AWS_ACCESS_KEY
and AWS_SECRET_ACCESS_KEY
respectfully.
Another way to supply the credentials is to create profiles in ~.aws/credentials
and point the AWS_DEFAULT_PROFILE
environment variable to one of them.
Here is a quick rundown on how the script works:
AWS_DEFAULT_PROFILE
variable to whatever value we got as the argumentaws configure list
and make sure exit code is 0, (success) then exit.You need to have AWS CLI installed, this is left as an excercise to the reader. Make sure ~.aws/credentials
file exists, and if not then run
aws configure
or create it manually.
Example credentials file:
[default]
region = eu-north-1
AWS_ACCESS_KEY = foo
AWS_SECRET_ACCESS_KEY = bar
[client1]
region = eu-west-1
AWS_ACCESS_KEY = xyz
AWS_SECRET_ACCESS_KEY = asdfgh
All you need to do is configure your profiles there, and start using the script.
Bonus tip
Put the script in /usr/local/bin
and create a bash alias:
alias awsprofile="bash /usr/local/bin/aws_profile_switcher.sh"