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

Template Variables and Scope

Manage variable scope, assignment, and context passing within templates to handle complex logic cleanly.

Template Variables and Scope

What You'll Learn

You'll learn how to assign and manage variables within Helm templates to keep complex logic organized and avoid repeating code or values.

Understanding Template Variables

In Helm templates, you can assign values to variables to simplify repeated expressions, improve readability, and control what data is accessible in different template sections. Just like in programming, variables store information temporarily for reuse.

Think of variables as labeled boxes: you put something in the box once, then reference that box's label instead of carrying the item around repeatedly.

Declaring Variables

Variables in Helm templates use the $ prefix and are assigned with :=:

{{- $releaseName := .Release.Name -}}
{{- $chartVersion := .Chart.Version -}}

Now $releaseName and $chartVersion hold those values throughout the template (within their scope).

Scope Matters

Variables are scoped to the block where they're defined. When you use control structures like range or with, the context (.) changes, potentially losing access to root-level values. Variables let you preserve important values:

{{- $root := . -}}
{{- range .Values.items }}
  name: {{ .name }}
  release: {{ $root.Release.Name }}
{{- end }}

Inside range, . now refers to each item, but $root still points to the original top-level context, letting you access .Release.Name even when the context has shifted.

Why This Matters

Without variables, you'd either repeat long expressions (like .Values.config.database.host) or lose access to important context when looping or changing scope. Variables keep templates clean, maintainable, and logically structured.

Key Takeaway:
Use template variables with $ to store values, preserve context across scope changes, and make complex template logic readable and maintainable.