with — Scoping

The with action narrows the current scope (the dot) to a nested value, shortening deep references.

Syntax{{- with .Values.nodeSelector }} ... {{- end }}

with changes what the dot (.) refers to inside its block. Instead of repeating .Values.image.something, you enter the image scope once.

Syntax

{{ with .Values.image }} ... {{ end }}

Inside the block, . is now .Values.image, so you write .repository and .tag directly.

The scope gotcha

Because the dot is rebound, you cannot reach .Release or .Values normally inside a with. To reach the root context, use $ — for example $.Release.Name.

with as a guard

with also skips its block entirely if the value is empty, so it doubles as an existence check.

Example

Example · yaml
spec:
  {{- with .Values.nodeSelector }}
  nodeSelector:
    {{- toYaml . | nindent 4 }}
  {{- end }}
  containers:
    - name: app
      {{- with .Values.image }}
      image: "{{ .repository }}:{{ .tag }}"
      {{- end }}

When to use it

  • A chart author uses with to scope into .Values.ingress so templates write .host instead of the verbose .Values.ingress.host throughout the block.
  • A developer uses with to safely skip an entire block when a nested value object is empty, avoiding nil-pointer errors from accessing keys of an unset map.
  • A template uses with to scope into a specific container definition from a list, making the template code inside the block clean and readable.

More examples

Scope into nested values

with scopes the dot to .Values.ingress, so all references inside use short keys like .host and .path.

Example · yaml
{{- with .Values.ingress }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    {{- toYaml .annotations | nindent 4 }}
spec:
  rules:
    - host: {{ .host | quote }}
      http:
        paths:
          - path: {{ .path | default "/" }}
{{- end }}

Skip block when value absent

with acts as a guard: if .Values.podAnnotations is empty or nil the entire block is skipped, preventing an empty annotations key.

Example · yaml
{{- with .Values.podAnnotations }}
  annotations:
    {{- toYaml . | nindent 4 }}
{{- end }}

Access outer scope with dollar

Uses $ to access the root context (such as .Release) from inside a with block where the dot is re-scoped to a sub-object.

Example · yaml
{{- with .Values.database }}
  env:
    - name: DB_HOST
      value: {{ .host | quote }}
    - name: RELEASE
      # Use $ to escape the with scope and access .Release
      value: {{ $.Release.Name | quote }}
{{- end }}

Discussion

  • Be the first to comment on this lesson.