Skip to content

Instantly share code, notes, and snippets.

@ns-mkusper
Forked from mccutchen/export-aws-credentials
Last active October 17, 2018 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ns-mkusper/c54efbd5b69ddb7513d8c446125557b1 to your computer and use it in GitHub Desktop.
Save ns-mkusper/c54efbd5b69ddb7513d8c446125557b1 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# 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.
# 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
j 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