Advanced Helm Template Functions
Learn to use advanced Helm template functions such as if/else conditionals, range loops, logical operators, and whitespace trimming to build cleaner and more maintainable custom Kubernetes charts. This lesson helps you understand how to write reusable Helm templates by controlling YAML output, managing indentation, and manipulating values effectively.
Popular functions and constructs
The brackets: {{ vs {{-
If we take a closer look at our template or any other that is available on the Internet, we’ll see that sometimes opening brackets are followed by the - character, like we have in deployment.yaml—in the part responsible for injecting environment variables to a container, as shown below:
The purpose of it is to remove a whitespace character, including a newline character, before a template function. If we hadn’t added it here and kept a regular {{, the resulting YAML file would have looked like this:
env:
- name: {{ .key}}
value: {{ .value}}
The reason for this is that when generating YAML files, Helm is removing (or replacing with values) everything that is between the brackets ({{ }}). To tell Helm that we also want to remove whitespaces before a template function, we need to add the - character after the brackets ({{). And if we want to remove whitespaces after a template function, we can replace a regular bracket with -}}.
The if/elsestatements
Conditions are the essence of programming. We’ve got them in any programming language to control the flow of a running application. Therefore, it’s not a surprise that the Helm template language also has them. Here is a basic structure of an if statement in Helm:
To visualize it as an example, let’s go back to our deployment.yaml file, and to the environment variables section, add a condition ...