Skip to content

Instantly share code, notes, and snippets.

@mkostrikin
Forked from ddgenome/aws-creds.bash
Created April 27, 2017 10:30
Show Gist options
  • Save mkostrikin/10db2bddb6d209b1a60e39e9d2d069c8 to your computer and use it in GitHub Desktop.
Save mkostrikin/10db2bddb6d209b1a60e39e9d2d069c8 to your computer and use it in GitHub Desktop.
Fetch AWS STS keys and set environment variables
#!/bin/bash
# Fetch 24-hour AWS STS session token and set appropriate environment variables.
# See http://docs.aws.amazon.com/cli/latest/reference/sts/get-session-token.html .
# You must have jq installed and in your PATH https://stedolan.github.io/jq/ .
# Add this function to your .bashrc or save it to a file and source that file from .bashrc .
# Usage: aws-creds MFA_TOKEN [OTHER_AWS_STS_GET-SESSION-TOKEN_OPTIONS]
function aws-creds () {
if [[ ! $1 ]]; then
echo "aws-creds: missing required argument: MFA_TOKEN_CODE" 1>&2
return 99
fi
export -n AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
# replace USER and 12_DIGIT_ACCOUNT_NUMBER with appropriate values
local iam_user="USER"
local aws_account="12_DIGIT_ACCOUNT_NUMBER"
local rv creds_json
creds_json=$(set -o pipefail; aws --output json sts get-session-token --duration-seconds 86400 --serial-number "arn:aws:iam::$aws_account:mfa/$iam_user" --token-code "$@")
rv="$?"
if [[ $rv -ne 0 || ! $creds_json ]]; then
echo "aws-creds: failed to get credentials: $creds_json" 1>&2
return "$rv"
fi
local jq="jq --exit-status --raw-output"
AWS_ACCESS_KEY_ID=$(echo "$creds_json" | $jq .Credentials.AccessKeyId)
rv="$?"
if [[ $rv -ne 0 || ! $AWS_ACCESS_KEY_ID ]]; then
echo "aws-creds: failed to parse output for AWS_ACCESS_KEY_ID: $creds_json" 1>&2
return "$rv"
fi
AWS_SECRET_ACCESS_KEY=$(echo "$creds_json" | $jq .Credentials.SecretAccessKey)
rv="$?"
if [[ $rv -ne 0 || ! $AWS_SECRET_ACCESS_KEY ]]; then
echo "aws-creds: failed to parse output for AWS_SECRET_ACCESS_KEY: $creds_json" 1>&2
return "$rv"
fi
AWS_SESSION_TOKEN=$(echo "$creds_json" | $jq .Credentials.SessionToken)
rv="$?"
if [[ $rv -ne 0 || ! $AWS_SESSION_TOKEN ]]; then
echo "aws-creds: failed to parse output for AWS_SESSION_TOKEN: $creds_json" 1>&2
return "$rv"
fi
export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
echo -e "AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID\nAWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY\nAWS_SESSION_TOKEN=$AWS_SESSION_TOKEN\nexport AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment