kubernetesgoogle-kubernetes-enginekustomize

How to use dynamic/variable image tag in a Kubernetes deployment?


In our project, which also uses Kustomize, our base deployment.yaml file looks like this:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:IMAGE_TAG # <------------------------------
        ports:
        - containerPort: 80

Then we use sed to replace IMAGE_TAG with the version of the image we want to deploy.

Is there a more sophisticated way to do this, rather than editing the text yaml file using sed?


Solution

  • There is a specific transformer for this called the images transformer. You can keep your deployment as it is, with or without tag:

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: nginx-deployment
      labels:
        app: nginx
    spec:
      replicas: 3
      selector:
        matchLabels:
          app: nginx
      template:
        metadata:
          labels:
            app: nginx
        spec:
          containers:
          - name: nginx
            image: nginx
            ports:
            - containerPort: 80
    

    and then in your kustomization file:

    apiVersion: kustomize.config.k8s.io/v1beta1
    kind: Kustomization
    
    resources:
      - deployment.yaml
    
    images:
      - name: nginx
        newTag: MYNEWTAG
    

    Do keep in mind that this will replace the tag of all the nginx images of all the resources included in your kustomization file. If you need to run multiple versions of nginx you can replace the image name in your deployment by a placeholder and have different entries in the transformer.