Search code examples
dockergoogle-cloud-platformgoogle-compute-enginegoogle-container-registry

Authenticate Google Compute Engine (GCE) to Pull Image from Google Container Registry (GCR)


I'm building deployment pipeline using Google Cloud Build and store the Docker image in GCR. I planned to restart the GCE instance group on the latest Cloud Build step so the GCE can run the latest docker image by add docker pull gcr.io/my-project/my-image in the GCE instance template startup script. The problem is I can't authorize the docker to pull image from GCR. I've read the 4 GCR authentication method but all of them required us to login manually from the browser. Also at this stage I can't upload the service account key since I need to provision and maintain the infrastructure fully from code (Terraform), no Google Cloud console. So how do we authenticate docker as a machine?


Solution

  • If the instance doesn't have gcloud installed, you can use the Metadata service to acquire an access token and use that to login to GCR using Docker.

    I've not used this to login to GCR using Docker but it should work. I use this format to access Google Cloud services from an instance startup script:

    echo "Getting token from metadata"
    ENDPOINT="metadata.google.internal/computeMetadata/v1"
    ACCOUNT="default" # Replace with Service Account Email (!)
    TOKEN=$(\
      curl \
      --silent \
      --header  "Metadata-Flavor: Google" \
      http://${ENDPOINT}/instance/service-accounts/${ACCOUNT}/token)
    
    echo "Extract access token"
    ACCESS=$(\
      echo ${TOKEN} \
      | grep --extended-regexp --only-matching "(ya29.[0-9a-zA-Z._-]*)")
    
    echo "Login to Docker"
    HOST="https://gcr.io" # Or ...
    printf ${ACCESS} \
    | docker login ${HOST} \
      -u oauth2accesstoken \
      --password-stdin