Search code examples
kuberneteskustomize

Kustomize patching multiple path with same value


I am trying to see if there are other ways to run patches with multiple paths with the same value.

This is an example of my Kustomization where I am replacing it with the same value. Is there a way to have a variable that I can use to refer to replace it instead of typing the same value multiple times?

patches: 
  - target:
      group: apps
      version: v1
      kind: Deployment
      name: common-base
    patch: |-
      - op: replace
        path: /metadata/name
        value: "svc1"
      - op: replace
        path: /metadata/labels/app
        value: "svc1"

Solution

  • You can use ConfigMaps and Secrets to hold configuration or sensitive data that are used by other Kubernetes objects, such as Pods. The source of ConfigMaps or Secrets are usually external to a cluster, such as a .properties file or an SSH keyfile. Kustomize has secretGenerator and configMapGenerator, which generate Secret and ConfigMap from files or literals.

    To run patches with multiple paths with the same value,you need to store the value in a ConfigMap or Secret and reference it in your resources.

    Define a ConfigMap in your kustomization.yaml:

    configMapGenerator:
      - name: app-config
        literals:
          - appName=svc1   #(your path / value )
    

    Reference the ConfigMap in your patch:

    patches:
      - target:
          group: apps
          version: v1
          kind: Deployment
          name: common-base
        patch: |-
          - op: replace
            path: /metadata/name
            valueFrom:
              configMapKeyRef:
                name: app-config
                key: appName
          - op: replace
            path: /metadata/labels/app
            valueFrom:
              configMapKeyRef:
                name: app-config
                key: appName
    

    So by following the above process by referencing the ConfigMap in your patch you will be able to achieve patching multiple paths with the same value in the Kustomize and you can also use a strategic merge patch and JSON patch which might also help you to resolve your issue.

    For more information check this Github Link which might be helpful for you.