Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kustomize patching a specific container other than by array (/containers/0)

I'm trying to see if there's a way to apply a kustomize patchTransformer to a specific container in a pod other than using its array index. For example, if I have 3 containers in a pod, (0, 1, 2) and I want to patch container "1" I would normally do something like this:

patch: |-
  - op: add
    path: /spec/containers/1/command
    value:  ["sh", "-c", "tail -f /dev/null"]

That is heavily dependent on that container order remaining static. If container "1" is removed for whatever reason, the array is reshuffled and container "2" suddenly becomes container "1", making my patch no longer applicable.

Is there a way to patch by name, or target a label/annotation, or some other mechanism?

path: /spec/containers/${NAME_OF_CONTAINER}/command

Any insight is greatly appreciated.

like image 408
pocketjokers Avatar asked Jan 24 '26 23:01

pocketjokers


1 Answers

You cannot currently address a list item using [key=value] syntax when using kustomize's patchesJson6902 -- you may have seen JSONPath syntax like this floating around the internet and hoped that you could select a list item and patch it using Kustomize.

# Unsupported JSONPath syntax
/spec/containers[name=my-app]/command

As @Rico mentioned in his answer: This is a limitation with JSON6902 - it only accepts paths using JSONPointer syntax, defined by JSON6901.

However, the problem presented in the original question around dealing with changes to the order of list items does have a solution using the accepted JSONPointer syntax (JSON6901) without moving to Strategic Merge Patch (which can depend on CRD authors correctly annotating how list-item merges should be applied).

Simply add another JSON6902 operation to your patches to test that the item remains at the index you specified.

# First, test that the item is still at the list index you expect
- op: test
  path: /spec/containers/0/name
  value: my-app

# Now that you know your item is still at index-0, it's safe to patch its command
- op: replace
  path: /spec/containers/0/command
  value: ["sh", "-c", "tail -f /dev/null"]

The test operation will fail your patch if the value at the specified path does not match what is provided. This way, you can be sure that your other patch operation's dependency on the item's index is still valid!

I use this trick especially when dealing with custom resources, since I:

  • A) Don't have to give kustomize a whole new openAPI spec, and
  • B) Don't have to depend on the CRD authors having added the correct extension annotation (like: "x-kubernetes-patch-merge-key": "name") to make sure my strategic merge patches on list items work the way I need them to.
like image 169
Zev Isert Avatar answered Jan 27 '26 12:01

Zev Isert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!