Course contentsShow
← Cloud and Infrastructure
Lesson 1540 of 2,98931. Helm Package ManagerFree lesson

Conditionals and Flow Control

Implement if/else statements, with blocks, and range loops to create dynamic templates based on values.

Conditionals and Flow Control

You'll learn how to use if/else logic and loops in Helm templates to generate different YAML based on user-provided values.

Core Concept

In Helm templates, you often need to include or exclude resources, change configurations, or repeat sections based on what's in your values.yaml file. Conditionals let you say "only render this if something is true," while flow control structures like loops let you repeat template blocks multiple times—making your charts flexible and reusable.

Think of it like a restaurant menu: if a customer is vegetarian (vegetarian: true), you show different dishes. If they order multiple sides, you loop through each one.

How It Works

If/Else Statements

Use {{ if ... }} to conditionally include template sections:

{{ if .Values.enableMetrics }}
- name: metrics-port
  containerPort: 9090
{{ end }}

You can add {{ else }} for alternative content:

{{ if .Values.production }}
replicas: 5
{{ else }}
replicas: 1
{{ end }}

With Blocks

The {{ with ... }} statement sets a new scope, useful when checking if a value exists:

{{ with .Values.nodeSelector }}
nodeSelector:
{{ toYaml . | indent 2 }}
{{ end }}

Range Loops

Use {{ range ... }} to iterate over lists or maps:

{{ range .Values.extraEnvVars }}
- name: {{ .name }}
  value: {{ .value }}
{{ end }}

Key Takeaway: Helm's conditionals and flow control (if/else, with, range) transform static YAML into dynamic templates that adapt to user values, making charts reusable across different environments and configurations.