Will.Evo
Will.Evo

Reputation: 1177

Access GCP Secret during Cloud Build build step

Lets say I have a cloudbuild.yaml file that looks like this:

steps:
  - name: 'gcr.io/cloud-builders/docker'
    id: build
    args: ['build', '-t', 'us.gcr.io/${PROJECT_ID}/image_name', '--build-arg', 'secret=$$SECRET', '.']
    secretEnv: ['SECRET']
 
images:
  - 'us.gcr.io/${PROJECT_ID}/image_name'

availableSecrets:
  secretManager:
  - versionName: projects/project/secrets/my_secret/versions/latest
    env: 'SECRET'

Right now, the --build-arg is assigning to the Docker secret arg the value $SECRET instead of the value actually stored in the secret. How can I access the secret value during this step? All of the examples I can find online say to add a bash entrypoint however only for steps that aren't actually doing the build call.

Upvotes: 2

Views: 2847

Answers (2)

guillaume blaquiere
guillaume blaquiere

Reputation: 75950

It's a usual issue with Cloud Build and Secret Manager integration. You can access to the secret only in a script, not in entry-point and arguments (your case)

Try that

steps:
  - name: 'gcr.io/cloud-builders/docker'
    id: build
    entrypoint: 'bash'
    args: 
      - -c
      - |
          docker build -t us.gcr.io/${PROJECT_ID}/image_name --build-arg secret=$$SECRET .
    secretEnv: ['SECRET']

reference: https://cloud.google.com/build/docs/securing-builds/use-secrets?configuring_builds_to_access_the_secret_from#access-utf8-secrets

Upvotes: 12

Mark Allen
Mark Allen

Reputation: 252

The syntax for assigning secrets to docker args seems to be slightly different to that for normal environment variables. The following snippet is taken from a working project of my own and correctly accesses the secret, and you can see the difference compared to the normal environment variables:

...
    env:
      - PROJECT_ID=$PROJECT_ID
      - NO_DEPLOY=$_NO_DEPLOY
      - NO_E2E=$_NO_E2E
    secretEnv:
      - "EXAMPLE_API_KEY"
    args:
      - --destination=gcr.io/$PROJECT_ID/api
      - --cache=true
      - --build-arg=PROJECT_ID
      - --build-arg=EXAMPLE_API_KEY
      - --build-arg=NO_DEPLOY
      - --build-arg=NO_E2E

availableSecrets:
  secretManager:
    - versionName: projects/$PROJECT_ID/secrets/example-api-key/versions/latest
      env: "EXAMPLE_API_KEY"
...

Upvotes: 4

Related Questions