Skip to content

Instantly share code, notes, and snippets.

@jesseendahl jesseendahl/ Secret
Created Sep 19, 2017

What would you like to do?
# 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).
# You'll probably want your Vault roles mapped to something associated with GCE instance
# bootstrapping, such as Salt roles or GCE instance groups.
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
# 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
echo "[ERR] Token is empty or incorrect, please check curl output:"
cat $tmpfile
rm $tmpfile
exit 2
rm $tmpfile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.