TL;DR Functions in your .bash_profile
can affect the current Terminal session.
The AWS CLI uses the environment variables “AWS_PROFILE” and “AWS_DEFAULT_PROFILE” to know which configured profile to use when running cli commands. If you only have one configured profile, it’s best to leave its name to “default” so that you don’t have to worry about what those environment variables are set to. I have multiple named profiles, though, and need to switch between them on occasion.
I normally switch between profiles by just changing the “AWS_PROFILE” variable to a different named profile. I would normally do this by running an export
in my Terminal session.
$ echo $AWS_PROFILE
example1 # Current variable value
$ aws configure list-profiles
example1
example2
example3
$ export AWS_PROFILE=example2
$ echo $AWS_PROFILE
example2 # Variable updated successfully
While this is easy enough, I wanted a quicker way to do it. It would be perfect to have a command that shows me the current profiles and asks which profile I want to change into. I haven’t done shell scripting in a while but here’s what I came up with.
#!/bin/bash
AWS_PROFILES=( $(aws configure list-profiles) )
INDEX=1
printf "\nConfigured AWS Profiles:\n"
for p in "${AWS_PROFILES[@]}"; do
echo "$INDEX: $p"
INDEX=$((INDEX + 1))
done
printf "\nEnter profile number: "
read -r choice
PROFILE=${AWS_PROFILES[choice-1]}
export AWS_PROFILE=$PROFILE
export AWS_DEFAULT_PROFILE=$PROFILE
printf "\nAWS profile set to \"%s\"\n" "$AWS_PROFILE"
The script works great except that scripts run in a subprocess. That means that “AWS_PROFILE” is unaffected for the current terminal session, as shown here:
$ echo $AWS_PROFILE
example1 # Current variable value
$ ./aws_profile_script
Configured AWS Profiles:
1: example1
2: example2
3: example3
Enter profile number: 2
AWS profile set to "example2"
$ echo $AWS_PROFILE
example1 # Variable was not updated
The solution is to move the script into a function of my ~/.bash_profile
which is able to affect the current terminal session. It looks like this:
#.bash_profile
(...)
# Change AWS Profile
chaws() {
AWS_PROFILES=( $(aws configure list-profiles) )
INDEX=1
printf "\nConfigured AWS Profiles:\n"
for p in "${AWS_PROFILES[@]}"; do
echo "$INDEX: $p"
INDEX=$((INDEX + 1))
done
printf "\nEnter profile number: "
read -r choice
PROFILE=${AWS_PROFILES[choice-1]}
export AWS_PROFILE=$PROFILE
export AWS_DEFAULT_PROFILE=$PROFILE
printf "\nAWS profile set to \"%s\"\n" "$AWS_PROFILE"
}
Not only does this work correctly, but it even gives me a quick shortcut by just typing chaws
.
$ echo $AWS_PROFILE
example1 # Current variable value
$ chaws
Configured AWS Profiles:
1: example1
2: example2
3: example3
Enter profile number: 2
AWS profile set to "example2"
$ echo $AWS_PROFILE
example2 # Variable updated successfully
Yay! Now back to some real work…