Skip to content

Instantly share code, notes, and snippets.

@mvisonneau
Created July 10, 2018 10:50
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 mvisonneau/5776f061c230e7c0df8933f20f30c7ea to your computer and use it in GitHub Desktop.
Save mvisonneau/5776f061c230e7c0df8933f20f30c7ea to your computer and use it in GitHub Desktop.
vault-aws-ec2-login
#!/usr/bin/env bash
if [[ -z ${VAULT_ADDR} ]]; then
echo "VAULT_ADDR must be set"
exit 1
fi
pkcs7=$( curl -s http://169.254.169.254/latest/dynamic/instance-identity/pkcs7 | tr -d '\n' )
iam_instance_profile=$( curl -s http://169.254.169.254/latest/meta-data/iam/info | jq -r .InstanceProfileArn | cut -d '/' -f2 )
nonce=$( openssl rand -base64 36 )
# In order to request a role onto vault we prefer VAULT_AWS_ROLE or we default to instance profile otherwise
role="${VAULT_AWS_ROLE:-${iam_instance_profile}}"
result=$(
curl -s -X POST "${VAULT_ADDR}/v1/auth/aws/login" \
-d '{"role":"'"$role"'","pkcs7":"'"$pkcs7"'","nonce":"'"$nonce"'"}"'
)
token=$( jq -r .auth.client_token <<< "$result" )
errors=$( jq -r .errors <<< "$result" )
if [[ -n ${errors} ]]; then
echo ${errors}
exit 1
elif [[ -z ${token} ]]; then
echo 'no error nor token returned from Vault'
exit 1
else
echo ${token}
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment