This article explores using loops and ranges in templating to dynamically generate configuration files.
In this article, we explore how to use loops and ranges to dynamically generate configuration files using templating. Loops, such as the “for” loop in many programming languages, execute a block of code repetitively by iterating over a collection of data. For example, consider the following simple loop which prints numbers from 1 to 10:
Copy
Ask AI
for i in 1 to 10: print iend
Each iteration updates the value of i sequentially, and the print statement is executed 10 times to display numbers 1 through 10.
The objective is to create a ConfigMap template that automatically populates the regions section with these values. A basic ConfigMap template might initially look like this:
To generalize this template, start with a structure where the regions list is left empty. Notice the metadata includes a dynamic release name using templating syntax:
Next, iterate over the list of regions from the values file by employing the range operator. The process involves looping through each region, where the current scope (represented by a dot) contains the region value. Initially, you might set up the loop as follows, which inserts a dash for each item:
Copy
Ask AI
apiVersion: v1kind: ConfigMapmetadata: name: {{ .Release.Name }}-regioninfodata: regions: {{- range .Values.regions }} - {{- end }}
At this stage, the actual region values are not included yet. The loop only creates a list item placeholder.
To include the actual region value, simply refer to the current value within the loop:
Copy
Ask AI
apiVersion: v1kind: ConfigMapmetadata: name: {{ .Release.Name }}-regioninfodata: regions: {{- range .Values.regions }} - {{ . }} {{- end }}
When rendered with the sample values, the output will be:
If your requirement specifies that each region name must be enclosed in quotes, you can pipe the value through a quoting function. The updated loop looks like this:
This final version ensures that every region is encapsulated in quotes.
By mastering loops and ranges in templating, you can dynamically and efficiently generate Kubernetes ConfigMaps and other configuration files. Advanced templating techniques build on these basics to provide more flexible and powerful configuration options.