How to pull images from a GCP container registry into Kubernetes


In this example we configure K8S to use an access token in order to pull images from a GCP registry.

As described in the link above (steps 1 and 2), the first step is to create a service account with a role which has read access on the registry (ex: Storage Admin), and associate a key to it.

After creating the key, the downloaded JSON file should be stored in a machine which has Docker installed (in order to run steps 3 and 5). In my case I don’t want to install the Google Cloud SDK on my Docker host, therefore I am going to use a container which has the gcloud tool already installed.

# pull the sdk container
docker pull google/cloud-sdk

# log into it 
docker run -v key.json:/key.json -it google/cloud-sdk bash

# authenticate with the service account
gcloud auth activate-service-account <service-account>@<project>.iam.gserviceaccount.com --key-file=key.json

# print the access token
gcloud auth print-access-token

The output of this command is then fed to docker login in the host machine.

echo "token" | docker login -u oauth2accesstoken --password-stdin https://<hostname> #(ex: eu.gcr.io)

This would store the unencrypted token in ~/.docker/config.json.

Next, we would have to add this config as a secret in Kubernetes. But first, we need to convert the content of config.json file to base64

cat .docker/config.json | base64 -w0

Then we create a secret yaml file (ex: registry-secret.yaml) with the following content:

apiVersion: v1
kind: Secret
metadata:
  name: secret-dockerconfigjson
  namespace: visuite
type: kubernetes.io/dockerconfigjson
data:
  .dockerconfigjson: <paste base64 config.json here>

and apply it:

kubectl apply -f registry-secret.yaml

Finally, we need to instruct K8S to use this secret to pull the required image using the docker configuration file.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: pull-image-test
spec:
  replicas: 1
  selector:
    matchLabels:
      app: pull-image-test
  template:
    metadata:
      labels:
        app: pull-image-test
    spec:
      imagePullSecrets:
      - name: secret-dockerconfigjson
      containers:
      - name: pull-image-test
        image: eu.gcr.io/project/image-to-pull:latest
    

Aaand there you go! Applying the deployment should result in a successful image pull.

One thought on “How to pull images from a GCP container registry into Kubernetes

  1. I don’t know where you get your knowledge, but this is a really great problem. I ought to take some time to comprehend or discover more. I appreciate the wonderful information; it was exactly what I needed for my purpose.

Comments are closed.