Skip to content

Instantly share code, notes, and snippets.

@mrbuk
Last active March 11, 2023 17:20
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 mrbuk/1d6c38f345910c469b110fc5cadcb9af to your computer and use it in GitHub Desktop.
Save mrbuk/1d6c38f345910c469b110fc5cadcb9af to your computer and use it in GitHub Desktop.
Cloud Build Step calling Cloud Run Service with Identity Token

To use this cloudbuild.yaml the following pre-reqs need to be met:

  1. Create a invoker service account (e.g. service-invoker@my-project.iam.gserviceaccount.com)
  2. Grant the Cloud Run Invoker / Cloud Function Invoker role / permissions to invoker service account
  3. Grant roles/iam.serviceAccountOpenIdTokenCreator to the Cloud Build service account for the invoker service account
  4. Enable the iamcredentials.googleapis.com API
steps:
- name: gcr.io/cloud-builders/curl
entrypoint: "/bin/sh"
args:
- "-c"
- |-
access_token=$(curl -H 'Metadata-Flavor: Google' \
http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token | \
grep -E -o 'ya29[^"]+')
curl -s -f 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/$_SERVICE_ACCOUNT:generateIdToken' \
-H "Content-Type: application/json" -H "Authorization: Bearer $access_token" \
-d '{"audience": "$_ENDPOINT", "includeEmail": true}' | grep -E -o 'ey[^"]+' > /workspace/token
- name: gcr.io/cloud-builders/curl
entrypoint: "/bin/sh"
args:
- "-c"
- |-
curl -v -H "Authorization: Bearer $(cat /workspace/token)" "$_ENDPOINT"
substitutions:
# service account to generate identity token for
#
# ensure that either the Cloud Build SA has
# the role: roles/iam.serviceAccountOpenIdTokenCreator
# or the permission: iam.serviceAccounts.getOpenIdToken
# on that service account
_SERVICE_ACCOUNT: NOT_DEFAULT_CLOUD_BUILD_ACCOUNT@project.iam.gserviceaccount.com
# endpoint of the cloud run service or cloud run
# needs to be specified as the audience in the generated identity token
# to allow access to the service/function
_ENDPOINT: https://CLOUD_FUNCTION_OR_CLOUD_RUN_SERVICE
gcloud builds submit --no-source \
--substitutions=_SERVICE_ACCOUNT=service-invoker@my-project.iam.gserviceaccount.com,_ENDPOINT=https://hello-12397ss-ew.a.run.app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment