Kubernetes: using a delete patch with kustomize

It is not uncommon when using kustomize to inherit a large set of resources or components.  Perhaps a few of them need to be updated with patches to accommodate your environment.  But if there are objects that are completely incompatible, it may be necessary to delete them.

This can be done with a kustomize ‘$delete’ patch.  Let’s use a simple kustomization.yaml to define a namespace, deployment, and configmap.

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
  - myns.yaml 
  - mydeployment.yaml

configMapGenerator:
- name: myconfigmap
  namespace: default
  literals:
  - foo=bar
generatorOptions:
  disableNameSuffixHash: true

When run, this assembles the definitions in myns.yaml and mydeployment.yaml as well as a generated configmap as shown below.

# run kustomize, 
$ kubectl kustomize .

apiVersion: v1
kind: Namespace
metadata:
  name: myns
---
apiVersion: v1
data:
  foo: bar
kind: ConfigMap
metadata:
  name: myconfigmap
  namespace: default
---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: mydeployment
  name: mydeployment
  namespace: default
spec:
  foo: bar
  selector:
    matchLabels:
      app: mydeployment
  template:
    metadata:
      labels:
        app: mydeployment
    spec:
      containers:
      - image: gcr.io/google-samples/hello-app:1.0
        name: mydeployment
        ports:
        - containerPort: 8080

If you created a delete patch file named delete-deployment.yaml

$patch: delete
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mydeployment
  namespace: default

And reference that delete patch file in kustomization.yaml

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
  - myns.yaml 
  - mydeployment.yaml

configMapGenerator:
- name: myconfigmap
  namespace: default
  literals:
  - foo=bar
generatorOptions:
  disableNameSuffixHash: true

# delete patch
patches:
  - delete-deployment.yaml

Notice how the output below is changed, and only the namespace and configmap are rendered (deployment is deleted).

$ kubectl kustomize .
apiVersion: v1
kind: Namespace
metadata:
  name: myns
---
apiVersion: v1
data:
  foo: bar
kind: ConfigMap
metadata:
  name: myconfigmap
  namespace: default

An equivalent method is to define the patch inline as shown below.

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
  - myns.yaml
  - mydeployment.yaml

configMapGenerator:
- name: myconfigmap
  namespace: default
  literals:
  - foo=bar
generatorOptions:
  disableNameSuffixHash: true

patches:
  - |-
    $patch: delete
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: mydeployment
      namespace: default

REFERENCES

kubernetes-sig, kustomize inline and $delete patches

kubernetes.io, using kustomize

kustomize components KEP