Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
gce_vault_auth.sh
#!/bin/bash
# Secrets should be written to a directory that is actually a memdisk volume,
# created by whatever is used to bootstrap new GCE instances in your environment
# (e.g. Salt or Terraform).
SECRETS_DIR="/etc/secrets"
CA_CERT="${SECRETS_DIR}/ca.pem"
VAULT_TOKEN="${SECRETS_DIR}/vault-token"
VAULT_SERVER_HOSTNAME="vault.service.consul"
VAULT_SERVER_PORT=8200
VAULT_SERVER_URL="https://${VAULT_SERVER_HOSTNAME}:${VAULT_SERVER_PORT}/v1/auth/gcp/login"
# You'll probably want your Vault roles mapped to something associated with GCE instance
# bootstrapping, such as Salt roles or GCE instance groups.
VAULT_ROLE="example_role"
generate_token() {
local tmpfile=$(mktemp ${SECRETS_DIR}/$(hostname).XXXXXX)
local token_tmp
local gce_token
# Request a signed JWT from the GCE metadata server.
# Note 1: Even though it says "http", the request and the subsequent metadata
# response never leaves the physical host running the virtual machine instance.
# Metadata information is also encrypted on the way to the virtual machine.
# See https://cloud.google.com/compute/docs/storing-retrieving-metadata#is_metadata_information_secure
# Note 2: The server portion of the address in the "audience" section doesn't matter.
# It just needs to be populated with an arbitrary string to satisfy the metadata server.
gce_token="$(curl -s -G -H "Metadata-Flavor: Google" http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience="http://THIS-PART-OF-URL-CAN-BE-AN-ARBITRARY-STRING/vault/${VAULT_ROLE}&format=full")"
# Use signed JWT to request an auth token from Vault server. Write it to a temp file.
curl -s -d "{ \"role\": \"${VAULT_ROLE}\", \"jwt\": \"$gce_token\" }" --cacert ${CA_CERT} -L ${VAULT_SERVER_URL} -o $tmpfile
# Extract token from JSON response and save to a new file containing only the token.
token_tmp=$(cat $tmpfile | jq -r .auth.client_token)
# Check if token is in UUID format and set strict file permissions.
if [[ $token_tmp =~ ^\{?[A-F0-9a-f]{8}-[A-F0-9a-f]{4}-[A-F0-9a-f]{4}-[A-F0-9a-f]{4}-[A-F0-9a-f]{12}\}?$ ]]; then
echo $token_tmp > $VAULT_TOKEN
chmod 400 $VAULT_TOKEN
chown root:root $VAULT_TOKEN
else
echo "[ERR] Token is empty or incorrect, please check curl output:"
cat $tmpfile
rm $tmpfile
exit 2
fi
rm $tmpfile
}
generate_token
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment