Kubernetes: How to Delete a Resource with Kustomize

Kustomize is a tool for customizing Kubernetes resources based on yaml manifests. It’s easy to add more resources, or modify manifests for different environments. But I struggled to find a solution for how to delete a resource with kustomize, but here is what I found.

The source code solution for this can be found here:

https://github.com/benkn/kustomize-patch-example

Problem Setup

My file structure looks like this:

hello-world/
|-- base/
|---- deployment.yaml
|---- ingress.yaml
|---- networkpolicy.yaml
|---- service.yaml
|---- kustomization.yaml

In this, I have all of my manifests together in the base directory, as well as the kustomization.yaml to import all of the manifests. Each manifest contains the yaml definition of the Kubernetes resource. Here is the contents of the kustomization.yaml:

resources:
- hello-world-deployment.yaml
- hello-world-networkpolicy.yaml
- hello-world-ingress.yaml
- hello-world-svc.yaml

When I run kustomize build base then I get all the manifests from the base joined together.

Overlay to Remove Networking

The problem is I need a specific overlay to remove all networking resources. To achieve this, I need kustomize to not include the network resources in the output manifests. So, I created an overlay directory specifically for my no-network need. In it, I added this file to utilize the $patch: delete operation in this file rm-networking.yaml:

# This patch removes the NetworkPolicy with the given name
$patch: delete
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: hello-world
---
# This patch removes the Ingress with the given name
$patch: delete
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: hello-world

To use this patch file, the kustomization.yaml in the overlay/no-network directory contains:

bases:
- ../../base

# Apply patches with these files
patchesStrategicMerge:
- rm-networking.yaml

# Ensure the namespace on all resources is the same
namespace: hello-world

The outcome? Running kustomize build overlays/no-network results in the Ingress and NetworkPolicy excluded from the manifest! 🎉

How? Kustomize pulls in the manifests from ../../base and performs a merge to apply patch operations.

Final Folder Structure

hello-world/
|-- base/
|---- deployment.yaml
|---- ingress.yaml
|---- networkpolicy.yaml
|---- service.yaml
|---- kustomization.yaml
|-- overlays/
|---- no-network/
|------- kustomization.yaml
|------- rm-networking.yaml