Search code examples
pythongoogle-cloud-platformdockerfileservice-accountsgoogle-cloud-build

Application Default Credentials in Google Cloud Build


Within my code, I am attempting to gather the Application Default Credentials from the associated service account in Cloud Build:

from google.auth import default

credentials, project_id = default()

This works fine in my local space because I have set the environment variable GOOGLE_APPLICATION_CREDENTIALS appropriately. However, when this line is executed (via a test step in my build configuration) within Cloud Build, the following error is raised:

google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. 
Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. 
For more information, please see https://cloud.google.com/docs/authentication/getting-started

This is confusing me because, according to the docs:

By default, Cloud Build uses a special service account to execute builds on your behalf. This service account is called the Cloud Build service account and it is created automatically when you enable the Cloud Build API in a Google Cloud project. Read Here

If the environment variable GOOGLE_APPLICATION_CREDENTIALS isn't set, ADC uses the service account that is attached to the resource that is running your code. Read Here

So why is the default call not able to access the Cloud Build service account credentials?


Solution

  • There is a trick: you have to define the network to use in your Docker build. Use the parameter --network=cloudbuild, like that

    steps:
      - name: gcr.io/cloud-builders/docker
        entrypoint: 'docker'
        args: 
          - build
          - '--no-cache'
          - '--network=cloudbuild'
          - '-t'
          - '$_GCR_HOSTNAME/$PROJECT_ID/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA'
          - .
          - '-f' 
          - 'Dockerfile'
    ...
    

    You can find the documentation here