google-cloud-platformkubernetesgoogle-kubernetes-enginegoogle-container-registry

Creating image pull secret for google container registry that doesn't expire?


I'm trying to get Kubernetes to download images from a Google Container Registry from another project. According to the docs you should create an image pull secret using:

$ kubectl create secret docker-registry myregistrykey --docker-server=DOCKER_REGISTRY_SERVER --docker-username=DOCKER_USER --docker-password=DOCKER_PASSWORD --docker-email=DOCKER_EMAIL

But I wonder what DOCKER_USER and DOCKER_PASSWORD I should use for authenticating with Google Container Registry? Looking at the GCR docs it says that the password is the access token that you can get by running:

$ gcloud auth print-access-token

This actually works... for a while. The problem seems to be that this access token expires after (what I believe to be) one hour. I need a password (or something) that doesn't expire when creating my image pull secret. Otherwise the Kubernetes cluster can't download the new images after an hour or so. What's the correct way to do this?


Solution

  • This is really tricky but after a lot of trail and error I think I've got it working.

    1. Go to the Google Developer Console > Api Manager > Credentials and click "Create credentials" and create a "service account key"

    2. Under "service account" select new and name the new key "gcr" (let the key type be json)

    3. Create the key and store the file on disk (from here on we assume that it was stored under ~/secret.json)

    4. Now login to GCR using Docker from command-line:

      $ docker login -e your@email.se -u _json_key -p "$(cat ~/secret.json)" https://eu.gcr.io

    This will generate an entry for "https://eu.gcr.io" in your ~/.docker/config.json file. 6. Copy the JSON structure under "https://eu.gcr.io" into a new file called "~/docker-config.json", remove newlines! For example:

    1. Base64 encode this file:

      $ cat ~/docker-config.json | base64

    2. This will print a long base64 encoded string, copy this string and paste it into an image pull secret definition (called ~/pullsecret.yaml):

    apiVersion: v1
      kind: Secret
      metadata:
        name: mykey
      data:
        .dockercfg: <paste base64 encoded string here>
      type: kubernetes.io/dockercfg
    
    1. Now create the secret:

    $ kubectl create -f ~/pullsecret.yaml 10. Now you can use this pull secret from a pod, for example:

    apiVersion: v1
    kind: Pod
    metadata: 
      name: foo
      namespace: awesomeapps
    spec: 
      containers: 
        - image: "janedoe/awesomeapp:v1"
          name: foo
      imagePullSecrets: 
        - name: mykey
    

    or add it to a service account.