AWS CLI profile switching made easy

Why did i write this script?

I use AWS CLI a lot for work, and i often have the need to work with multiple different environments/accounts simultaneously.

This Bash script enables you to easily 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)

Script content


# check args
if [[ $# -ne 1 ]]; then
    echo "usage: aws-profile <profile name>"
    echo "profiles can be defined in ~/.aws/credentials"
    exit 0
    # save original profile before exporting
    original_profile=$(echo $AWS_DEFAULT_PROFILE)
    export AWS_DEFAULT_PROFILE=${1}

# Check if profile exists, revert if not
aws configure list
if [[ $? != 0 ]]; then
    echo "aborting.."
    export AWS_DEFAULT_PROFILE=${original_profile}
    echo -e "\nDone"
    echo -e "\nOK"
    echo "switched to profile: ${1}"

How it works

AWS CLI reads both the access and secret keys from environment variables AWS_ACCESS_KEY and AWS_SECRET_ACCESS_KEY respectfully.

Another way to accomplish this is to create profiles in and switch between those pre-defined profiles by setting the AWS_DEFAULT_PROFILE environment variable to one of the profiles, which is basically what the script does.

Here is a quick rundown on how the script works:

How to use it

I am going to assume you already have AWS CLI installed.

As mentioned earlier, AWS CLI profile credentials are stored in file.
If this folder/file does not exist, you can either run aws configure or create it manually.

Example credentials file:

region = eu-north-1

region = eu-west-1

All you need to do is configure the profiles there, and the script will take care of everything else.

Bonus tip
Put the script in /usr/local/bin and create a bash alias:

alias awsprofile="bash /usr/local/bin/"