Replacing a Container in the List Using a JSON 6902 Patch
To update both the name and image of the container, use a JSON 6902 patch in yourkustomization.yaml file. This patch targets the deployment by its kind and name and replaces the container at index 0 with a new configuration.
kustomization.yaml:
/spec/template/spec/containers/0 specifies that the first element of the containers list (index 0) will be replaced. Once applied, Kustomize updates the container, switching from “nginx” to “haproxy” for both the name and image.
Remember that list indices in YAML start at zero. Always check the index to
target the correct container.
Replacing a Container Using a Strategic Merge Patch
If you prefer modifying just a part of the container configuration (e.g., only the image), you can use a strategic merge patch. First, reference your patch file in thekustomization.yaml:
kustomization.yaml:
label-patch.yaml file, specify the container by its name and provide the updated image:
label-patch.yaml:
Adding a Container to the List Using a JSON 6902 Patch
If you want to add a second container to your deployment, you can achieve this using a JSON 6902 patch. In the example below, a new container with the name and image “haproxy” is appended to the containers list. The dash (-) at the end of the path indicates that the container should be added at the end of the list. kustomization.yaml:Adding a Container Using a Strategic Merge Patch
Alternatively, you can add a container using a strategic merge patch. Suppose the original configuration contains a container named “web” using the “nginx” image and you wish to add another container. First, reference the patch file inkustomization.yaml:
kustomization.yaml:
label-patch.yaml file:
label-patch.yaml:
Deleting a Container from the List Using a JSON 6902 Patch
Imagine a scenario where your Deployment originally includes two containers: one named “web” with the “nginx” image and another named “database” with the “mongo” image. Original Deployment:Ensure that you use the correct index when attempting to remove a container.
An incorrect index could lead to unexpected modifications in your deployment
configuration.
Deleting a Container Using a Strategic Merge Patch
You can also delete a container using a strategic merge patch with the delete directive. Given the initial configuration that includes both “web” and “database” containers, create a patch that instructs Kustomize to remove the “database” container: kustomization.yaml:This lesson detailed multiple methods for manipulating list items in Kubernetes Deployments using both JSON 6902 patches and strategic merge patches. For more information on Kubernetes patch strategies, refer to the Kubernetes Documentation.