In this lesson, you will learn how to use the Helm range function to dynamically generate multiple Kubernetes resource definitions from a single configuration block.
When managing complex deployments, you often need to create repetitive resources—such as multiple ConfigMaps, Secrets, or Ingress rules—that differ only by a few parameters. Rather than hardcoding these manually, we use range loops to iterate over lists or maps defined in your values.yaml file.
How range Works
The range keyword allows you to traverse a collection. When iterating over a list, Helm assigns each element to a variable; when iterating over a map, it exposes both the key and the value. This keeps your chart "DRY" (Don't Repeat Yourself) and highly scalable.
Consider this values.yaml snippet:
configFiles:
- name: app-settings
mountPath: /etc/config/app
- name: db-settings
mountPath: /etc/config/db
You can generate multiple ConfigMap volumes in your deployment.yaml using a single loop:
volumes:
{{- range .Values.configFiles }}
- name: {{ .name }}
configMap:
name: {{ .name }}
{{- end }}
Key Considerations
- Scope and Pipelines: Inside a
rangeloop, the "dot" (.) context shifts. It now points to the current item being iterated. If you need to access global values (like{{ .Release.Name }}), you must use$, which represents the root context (e.g.,{{ $.Release.Name }}). - Pipelines: You can use a variable name in your loop to keep your code readable, for example:
{{- range $key, $val := .Values.myMap }}. - Indentation: Because Helm templates generate raw YAML, be mindful of whitespace. Using the
-(hyphen) in{{-and-}}helps strip extra newlines, ensuring your rendered YAML remains valid and clean.
By leveraging range loops, you transform static, error-prone templates into dynamic engines capable of handling dozens of resources with minimal code maintenance.
Key Takeaway: Use the range loop to transform list and map data from your values.yaml into dynamic Kubernetes manifests, allowing you to scale your application configuration without duplicating manual resource definitions.