Created
October 13, 2017 17:33
-
-
Save Jurawa/daa3183593bd3735ef406141e91d3410 to your computer and use it in GitHub Desktop.
Export AWS env vars from AWS credentials and set profile in one step.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# export-aws-creds.sh | |
# https://github.com/jurawa | |
# When sourced, this script will export the AWS_ACCESS_KEY_ID and | |
# AWS_SECRET_ACCESS_KEY env vars from a specific profile in | |
# ~/.aws/credentials. | |
# It will also set AWS_PROFILE and AWS_DEFAULT_PROFILE, ensuring | |
# the current shell is configured to use the correct AWS credentials | |
# regardless of what script or tools you are using to connect to AWS... | |
# boto, aws cli, ansible etc. | |
# Modified from: | |
# https://gist.github.com/mccutchen/d7902e2c8cd414cdd2b0 | |
# Usage: | |
# | |
# First ensure your AWS profiles are correctly set up: | |
# http://docs.aws.amazon.com/cli/latest/userguide/cli-multiple-profiles.html | |
# | |
# Then source this script with the profile name. | |
# | |
# $ . ./export-aws-creds.sh [PROFILE NAME] | |
# | |
# If PROFILE is not given, the "default" profile will be exported. | |
# | |
# I also add a function to my .zshrc to ease usage: | |
# | |
# function awsprofile () { | |
# . ~/Dev/export-aws-creds.sh $1 | |
# } | |
# | |
# Then run it: | |
# | |
# $ awsprofile sandbox | |
[[ -z "$1" ]] && profile="default" || profile="$1" | |
credentials=$(grep -A 2 "$profile" ~/.aws/credentials | grep -v "$profile") | |
if [[ "$credentials" == "" ]]; then | |
echo "Error: profile '$profile' not found in ~/.aws/credentials" | |
return | |
fi | |
echo "" | |
echo "Exporting profile: $profile" | |
for key in AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY; do | |
val=$(echo "$credentials" | grep -i $key | awk -F '=' '{print $2}') | |
if [[ "$val" == "" ]]; then | |
echo " Error: missing $key" | |
return | |
fi | |
export $key=$val | |
done | |
export AWS_DEFAULT_PROFILE=$profile | |
export AWS_PROFILE=$profile | |
echo "===================================================================" | |
echo "AWS_ACCESS_KEY_ID: ****************${AWS_ACCESS_KEY_ID: -4}" | |
echo "AWS_SECRET_ACCESS_KEY: ****************${AWS_SECRET_ACCESS_KEY: -4}" | |
echo "AWS_DEFAULT_PROFILE: $AWS_DEFAULT_PROFILE" | |
echo "AWS_PROFILE: $AWS_PROFILE" | |
echo "===================================================================" | |
echo 'aws configure list' | |
aws configure list | |
echo "===================================================================" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment