Skip to content

Instantly share code, notes, and snippets.

@ollytheninja
Last active October 12, 2022 23:21
Show Gist options
  • Save ollytheninja/e858bb5500086f1c0bcf7709f17bcf07 to your computer and use it in GitHub Desktop.
Save ollytheninja/e858bb5500086f1c0bcf7709f17bcf07 to your computer and use it in GitHub Desktop.
###############################################
# Generate a JWK file to connect Vault to GCP #
# by providing GCP our own private key #
###############################################
# Inspired by:
# https://binx.io/2021/03/08/how-to-create-your-own-google-service-account-key-file/
# And for my later self - GCP does indeed want a public key certificate - not just a bare public key!
# Provide these from the Service Account you created.
PROJECT_ID=""
CLIENT_NAME=""
CLIENT_ID=""
openssl genrsa -out my.key 4096
openssl req -x509 -new \
-key my.key \
-subj /CN=unused \
-out csr.pem
openssl x509 \
-in csr.pem \
-signkey my.key \
-days 31 \
-out certificate.pem
PRIVATE_KEY_ID=$(cat certificate.pem | openssl x509 -outform der | openssl sha1)
PRIVATE_KEY=$(cat my.key)
CLIENT_EMAIL=${CLIENT_NAME}@${PROJECT_ID}.iam.gserviceaccount.com
touch keys.json
chmod 0600 keys.json
jq -n \
--arg PRIVATE_KEY "$PRIVATE_KEY" \
--arg PROJECT_ID $PROJECT_ID \
--arg CLIENT_EMAIL $CLIENT_EMAIL \
--arg CLIENT_ID $CLIENT_ID \
--arg PRIVATE_KEY_ID $PRIVATE_KEY_ID \
'{
"type": "service_account",
"project_id": $PROJECT_ID,
"private_key_id": $PRIVATE_KEY_ID,
"private_key": $PRIVATE_KEY,
"client_email": $CLIENT_EMAIL,
"client_id": $CLIENT_ID,
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": @uri "https://www.googleapis.com/robot/v1/metadata/x509/\($CLIENT_EMAIL)"
}' > keys.json
vault write gcp/config credentials=@keys.json
rm keys.json my.key
echo "Add certificate.pem to your service account keys"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment