Variables in Kustomize are handy helpers from time to time, with these variables I can link some settings together which should share the same value all the time. Without variable I probably need to use some template engine like Jinja2 to do the same trick.
Some examples here.
In my case, there’s a bug in kustomize
as of now(3.6.1) where configMap
object names don’t get properly suffixed in a patch file. The issue is here. I can however use variable to overcome this bug. Imagine in a scenario I have a configMap
in a base template and it will be referenced in a patch file:
# common/kustomization.yaml apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - deploy.yaml configMapGenerator: - name: common literals: - TEST=YES # common/deploy.yaml # this is not a fully functional deployment, just to demo kustomization --- apiVersion: apps/v1 kind: Deployment metadata: name: test spec: templates: spec: volumes: [] # test/kustomization.yaml apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization namespace: test bases: - ../common nameSuffix: -raynix patchesStrategicMerge: - patch.yaml # test/patch.yaml --- apiVersion: apps/v1 kind: Deployment metadata: name: test spec: templates: spec: volumes: - name: common configMap: name: common # this should be linked to the configMap in common/kustomization.yaml but it won't be updated with a hash and suffix.
Using variable can get around this bug. Please see the following example.
First a new configuration for kustomize is needed, to let it refer to a variable in this specific place:
# common/config.yaml varReference: - kind: Deployment path: spec/templates/spec/volumes/configMap/name
Then a new variable can be defined as:
# common/kustomization.yaml apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization # load the new configuration! configurations: - config.yaml configMapGenerator: - name: common literals: - TEST=YES vars: - name: COMMON objref: apiVersion: v1 kind: ConfigMap name: common fieldref: # this can be omitted as metadata.name is the default fieldPath fieldPath: metadata.name # test/kustomization.yaml unchanged # test/patch.yaml --- apiVersion: apps/v1 kind: Deployment metadata: name: test spec: templates: spec: volumes: - name: common configMap: name: $(COMMON) # now $(COMMON) will be updated with whatever the real configmap name is
Now to test it for real:
# kustomize build test apiVersion: v1 data: TEST: "YES" kind: ConfigMap metadata: name: common-raynix-75tk5fb6fc namespace: test --- apiVersion: apps/v1 kind: Deployment metadata: name: test-raynix namespace: test spec: templates: spec: volumes: - configMap: name: common-raynix-75tk5fb6fc # <<- here we go! name: common
Problem solved 🙂
EDIT: Added missing configuration file.
One response to “Use Variables in Kustomize”
[…] was looking at the Kustomize variable trick I did a year ago and I think I’ve learned some new tricks worth noting […]