Storing docker registry path in Kubernetes yaml's

3/19/2018

In my company we use GitLab as a source control and also use GitLab's Docker registry. Each repository contains a Dockerfile for building an image and Kubernetes yaml's for defining the Pod/Service/Deployment/etc of that project.

The problem is that in the yaml's the image references the GitLab registry by its url

enter image description here (Example from the Redis repository)

I don't like it for two reasons

  1. It would make switching to another registry provider really hard since you'll have to go over your entire code base and change all the Kubernetes yaml files.
  2. If a developer wants to test his app via minikube, he has to make sure that the image is stored and up to date in the registry. In our company, pushing to the registry is something that is done as part of the CI pipeline.

Is there a way to avoid storing the registry url in the repository? Logging in to the docker registry beforehand doesn't solve it, you still have to provide the full image name with the url.

-- areller
docker
kubernetes

1 Answer

3/19/2018

You can use an environment variable with shell scripts.

Here is the working example.

1) Create an environment variable

export IMAGE_URL=node:7-alpine

2) Create a 1 line shell script. This script purpose is replacing your env value in .yaml file with your actual environment variable.

echo sed 's/\$IMAGE_URL'"/$IMAGE_URL/g" > image_url.sh

3) Create sample yaml for example mypod.yaml.tmpl

cat > mypod.yaml.tmpl << EOL  

apiVersion: v1
kind: Pod
metadata:
  name: mypod
spec:
  containers:
  - name: mypod
    image: $IMAGE_URL
    # Just spin & wait forever
    command: [ "/bin/ash", "-c", "--" ]
    args: [ "while true; do sleep 30; done;" ]     
EOL

4) Run kubectl apply

cat mypod.yaml.tmpl | sh image_url.sh | kubectl apply -f -
-- Ercan Aydogan
Source: StackOverflow