How to use Kustomize to add same sidecar container to both Deployment and CronJob

106 Views Asked by At

I have both Deployment and CrobJob and I'd like to append the same sidecar container to them. However, the path to the containers list in Deployment and CronJob is different. I had to create 2 patch files and copy/paste the same sidecar container fragment.

file sidecar-for-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: sidecar-patch-for-deployment
spec:
  template:
    spec:
      containers:
        - name: sidecar-xyz
          image: ...
          ...

file sidecar-for-crobjob.yaml

apiVersion: batch/v1
kind: CronJob
metadata:
  name: sidecar-patch-for-cronjob
spec:
  jobTemplate:
    spec:
      template:
        spec:
          containers:
            - name: sidecar-xyz
              image: ...
              ...

Then in the kustomize.yaml

kind: Kustomization
apiVersion: kustomize.config.k8s.io/v1beta1
resources:
  - base

patches:
  - target:
      kind: Deployment
      labelSelector: "require-sidecar=true"
    path: sidecar-for-deployment.yaml

  - target:
      kind: CronJob
      labelSelector: "require-sidecar=true"
    path: sidecar-for-crobjob.yaml

That works, but I have to copy/paste a big chunk of the sidecar container code in 2 places. How can I avoid that duplication?

Another point, when I did like above, the sidecar container is prepended in the container list, how can I have it appended instead?

0

There are 0 best solutions below