AWS Environment Script

The following script can be used to source your AWS environment variables and make it easy to switch between AWS profiles. This is especially useful when you have to switch between AWS accounts frequently. The script requires that you use profiles which are set up using aws configure --profile.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/bin/bash

display_usage() {
echo "Usage : . aws.sh <profile>"
echo ""
echo "Note: An aws profile may be created using:"
echo " aws configure --profile"
}

echo ""

# check script is sourced
if [[ $0 != "-bash" ]]; then
echo "Script must be sourced!"
echo ""
display_usage
exit 1
fi

# check parameters
if [[ "$@" == "" ]]
then
echo "Insufficient parameters!"
echo ""
display_usage
return 1
fi

# check if user requested help
if [[ ( "$@" == "--help") || "$@" == "-h" ]]
then
display_usage
return 0
fi

profile=$1

# check if profile exists
aws configure list --profile ${profile} >/dev/null 2>&1
if [[ $? != 0 ]]; then
echo "Profile ${profile} not found!"
return 1
fi

echo "Configuring environment for ${profile}"

export AWS_DEFAULT_REGION=$(aws configure get ${profile}.region)
export AWS_ACCESS_KEY_ID=$(aws configure get ${profile}.aws_access_key_id)
export AWS_SECRET_ACCESS_KEY=$(aws configure get ${profile}.aws_secret_access_key)

env | grep AWS
echo "Done!"