Understanding Patch Components
To create a patch, you need to provide three essential parameters:-
Operation Type: Determines the action performed on a resource. The most commonly used operations are:
- add: Inserts a new element. For instance, when adding a container to a list in a deployment.
- remove: Deletes an element, such as removing a container or a label.
- replace: Swaps an existing value with a new one. For example, changing the replica count from 5 to 10.
-
Target: Specifies the criteria to identify the exact Kubernetes object(s) to patch. You can filter objects based on properties like:
- kind
- version
- name
- namespace
- label selector
- annotation selector
- Value: Represents the new value to be applied or used for replacement. Note that for removal operations, no value is provided since the intention is to delete the target property.
When updating configurations, ensure that your patch accurately targets the intended resource to prevent unintended changes.
Example 1: Changing the Deployment Name
Consider the followingdeployment.yaml file with an initial configuration:
metadata.name from api-deployment to web-deployment, you can use an inline JSON 6902 patch in your kustomization.yaml file:
Example 2: Updating the Replica Count
Let’s review another scenario. Suppose the original deployment has one replica, and you want to increase it to five. The initial configuration remains:kustomization.yaml, update the replica count as follows:
deployment.yaml is updated to:
Patch Methods in Kustomize
Kustomize supports two primary methods for defining patches:1. JSON 6902 Patch
This method specifies the target and lists the patch operations. An example using JSON 6902 patch is:2. Strategic Merge Patch
This approach resembles standard Kubernetes configuration files. You provide only the parts of the configuration you intend to modify, and Kustomize merges these changes with the existing configuration. For example:Both methods effectively update Kubernetes resources. The choice between JSON 6902 and strategic merge patches is based on personal preference, with many opting for the readability of strategic merge patches.