Patch specific resource in kustomize

2/19/2021

I have a base resource that gets imported in an overlay, which in the overlays also makes other resources from the same base but with a different suffix. In the overlay, the base resource needs to be patched without affecting the other newly created resources. However, all three of them are changed. How can I just modify the one I am intending to modify?

Below is an example of this. The base resource is a Deployment with 1 replica. In the overlay, the base is added as a resource but I try to patch it and set the replicas to 0. Unfortunately, all replicas of all deployments get set to 0.

Base

EX_HOME=$(mktemp -d)
BASE=$EX_HOME/base
mkdir $BASE

cat <<EOF >$BASE/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: example
  labels:
    app: example
spec:
  replicas: 1
  selector:
    matchLabels:
      app: example
  template:
    metadata:
      labels:
        app: example
    spec:
      containers:
        - name: example
          image: alpine:latest
          command: ["sh","-c", "sleep 1h"]
EOF

cat <<EOF>$BASE/kustomization.yaml
resources:
- deployment.yaml
EOF

Overlay

OVERLAYS=$EX_HOME/overlays
mkdir -p $OVERLAYS/srv0
mkdir -p $OVERLAYS/srv1

cat <<EOF>$OVERLAYS/kustomization.yaml
resources:
  - svr0
  - svr1
  - ../base

patches:
  - patch: |-
      - op: replace
        path: /spec/replicas
        value: 0
    target:
      kind: Deployment
      group: apps
      version: v1
      name: example
EOF

cat <<EOF>$OVERLAYS/svr0/kustomization.yaml
resources:
  - ../../base
nameSuffix: -svr0
EOF

cat <<EOF>$OVERLAYS/svr0/kustomize.yaml
resources:
  - ../../base
nameSuffix: -svr1
EOF
-- H. S&#225;nchez
kubernetes
kustomize

1 Answer

2/25/2021

The following should work. I took the liberty to re-organize a bit the directory structure to make it clearer. Since you only update the replica count I also switched to the replicas transformer instead of a patch:

base/kustomization.yaml:

resources:
  - deployment.yaml

overlays/svr0/kustomization.yaml:

resources:
  - ../../base

nameSuffix: -svr0

overlays/svr1/kustomization.yaml:

resources:
  - ../../base

nameSuffix: -svr1

`overlays/all/kustomization.yaml`:
```yaml
resources:
  - ../../base
  - ../svr0
  - ../svr1

replicas:
  - name: example-svr0
    count: 0
  - name: example-svr1
    count: 0

On a side note: There is two ways to go about it. Here I add the replicas transformer at the top. You could also add it once in overlays/svr0/kustomization.yaml and once in verlays/svr1/kustomization.yaml instead. If you do so the transformer will become:

replicas:
  - name: example
    count: 0
-- ITChap
Source: StackOverflow