In this article, we explore how to use conditionals in Helm charts to include or exclude sections of your templates based on values specified in the values file. With these techniques, you can add optional configurations such as custom labels, control whitespace, and conditionally render entire objects like service accounts—all of which add flexibility to your deployments.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Example: Adding Optional Labels
Consider a basic Helm chart with a simple service template. Initially, you might have avalues.yaml file with minimal configuration and a corresponding service.yaml template:
orgLabel value is optional, you want these label lines to appear only when the value is provided. Similar to conditionally executing code in programming languages such as Python:
service.yaml file that conditionally adds the organization label:
The dash (
-) after the opening braces ({{-) ensures that Helm trims any preceding whitespace, preventing extra blank lines in the rendered output.Trimming Whitespace in Templates
When Helm renders your templates, it may leave unintended whitespace between directives. To avoid this, use a dash after the opening braces—and before the closing braces, if needed—as shown below:Using If, Else If, and Else Blocks
Helm templates support conditional logic that includesif, else if, and else constructs. Similar to Python’s conditional logic, you can use helper functions such as eq for equality comparisons. Consider this Python pseudocode:
orgLabel is provided, its value is used. If it specifically equals "hr", the label is set to “human resources”. This approach leverages Helm’s helper functions for clear and concise conditional logic.
Conditional Creation of Objects
A common use case for Helm conditionals is to control the creation of certain Kubernetes objects based on configuration. For example, you might want to create a ServiceAccount only if it is explicitly enabled in yourvalues.yaml file.
In your default values.yaml, you can add a section like this:
This concludes our deep dive into using conditionals in Helm charts. We demonstrated how to add optional labels, trim whitespace in rendered templates, employ if-else logic using helper functions, and conditionally create resources like service accounts. By leveraging these techniques, you can create more dynamic, efficient, and maintainable Helm charts. Happy templating! For more information, explore the official Helm Documentation.