Skip to content

Instantly share code, notes, and snippets.

@dylanenabled
Last active July 4, 2023 04:32
Show Gist options
  • Save dylanenabled/5fd0128afe362343cf2a8e9628c4218e to your computer and use it in GitHub Desktop.
Save dylanenabled/5fd0128afe362343cf2a8e9628c4218e to your computer and use it in GitHub Desktop.
Use google workload identity to run firebase adminsdk script
#!/bin/bash
PROJECT_ID=your-project-id
SERVICE_ACCOUNT=sa@${PROJECT_ID}.iam.gserviceaccount.com
echo "LOGGING IN TO GCLOUD USING the external_account credentials"
gcloud auth login --cred-file=/etc/google-cred-config/google_cred_config.json
gcloud config set project "${PROJECT_ID}"
#Create a temporary key to use during bootstrap (need this because firebase admin sdk can't use external_account workload identity federation)
# https://github.com/firebase/firebase-admin-node/issues/1377
echo "UPLOADING A SERVICEACCOUNT KEY for ${SERVICE_ACCOUNT}, REMOVE THIS ONCE EXPIRED"
openssl req -x509 -nodes -newkey rsa:2048 -days 1 -keyout /tmp/private_key.pem -out /tmp/public_key.pem -subj "/CN=unused"
gcloud iam service-accounts keys upload /tmp/public_key.pem --iam-account=${SERVICE_ACCOUNT} --format json > /tmp/uploaded_key.json
GCLOUD_PRIVATE_KEY_NAME=$(jq -r .name /tmp/uploaded_key.json | awk -F/ '{print $NF}')
echo "CREATED SERVICE ACCOUNT KEY $GCLOUD_PRIVATE_KEY_NAME"
touch /tmp/service_account.json
chmod 0600 /tmp/service_account.json
cat << EOF > /tmp/service_account.json
{
"type": "service_account",
"project_id": "$PROJECT_ID",
"private_key_id": "$GCLOUD_PRIVATE_KEY_NAME",
"private_key": "$(sed ':a;N;$!ba;s/\n/\\n/g' /tmp/private_key.pem)",
"client_email": "${SERVICE_ACCOUNT}",
"client_id": "$(gcloud iam service-accounts describe $SERVICE_ACCOUNT --format 'value(uniqueId)')",
"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": "https://www.googleapis.com/robot/v1/metadata/x509/$(echo ${SERVICE_ACCOUNT} | sed 's/@/%40/g')"
}
EOF
export GOOGLE_APPLICATION_CREDENTIALS=/tmp/service_account.json
npm run-firebase-commands
echo "REMOVING SERVICE ACCOUNT KEY"
gcloud iam service-accounts keys delete ${GCLOUD_PRIVATE_KEY_NAME} --iam-account=${SERVICE_ACCOUNT}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment