This guide explores simplifying Helm chart templates using “with” blocks to reduce repetition and improve readability when referencing values in values.yaml.
In this guide, we explore how to simplify and optimize your Helm chart templates using “with” blocks. Using a ConfigMap example, we demonstrate how setting the scope can reduce repetition when referencing values defined in your values.yaml file.
In this version, each reference begins at the root (with .), and you must explicitly traverse the hierarchy, which can lead to repetitive expressions such as .Values.app.ui.bg.
By using “with” blocks, you can simplify your templates by setting a local scope. This reduces repetition and makes your templates cleaner and easier to maintain.
Within the “with” block, the current scope becomes .Values.app, allowing access to nested properties directly (e.g., .ui.bg instead of .Values.app.ui.bg).
For better organization and readability, you can further nest “with” blocks to separate UI and database settings. For example:
Copy
Ask AI
apiVersion: v1kind: ConfigMapmetadata: name: {{ .Release.Name }}-appinfodata:{{- with .Values.app }} {{- with .ui }} background: {{ .bg }} foreground: {{ .fg }} {{- end }} {{- with .db }} database: {{ .name }} connection: {{ .conn }} {{- end }} release: {{ $.Release.Name }}{{- end }}
In this structure, the inner “with” blocks set the scope to .Values.app.ui and .Values.app.db respectively. Note that you can use $.Release.Name to access the release name from the root context, as the current scope has been altered.
Using nested “with” blocks not only cleans up your templates but also clarifies the relationship between different configuration sections.
This guide demonstrated how “with” blocks in Helm charts can reduce repetition and improve template readability. By setting appropriate scopes, you can manage complex configurations more efficiently. We hope this example inspires you to explore further optimizations in your Helm charts.For additional insights and documentation on Helm charts, consider visiting the Helm Documentation and Kubernetes Documentation.