Home > Software design >  Authenticate Google Compute Engine (GCE) to Pull Image from Google Container Registry (GCR)
Authenticate Google Compute Engine (GCE) to Pull Image from Google Container Registry (GCR)

Time:09-07

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?

CodePudding user response:

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="http://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 -u oauth2accesstoken \
  --password-stdin ${HOST}

CodePudding user response:

You can grant IAM privileges or scopes to the service account attached to your GCE instance, then run the following command:

gcloud auth print-access-token | docker login -u oauth2accesstoken \
    --password-stdin https://HOSTNAME

That will authenticate against the registry and be able to push and pull images.

  • Related