In this lesson, you will learn how to use Go template if-else blocks to dynamically include or exclude Kubernetes resources in your Helm charts based on user-provided input.
When managing complex applications, you often encounter scenarios where certain resources should only exist under specific conditions. For example, you might want to deploy an Ingress resource only if the user intends to expose the service to the internet, or include a NetworkPolicy only for production environments. Instead of maintaining separate charts, you can use conditional logic directly within your manifest templates.
The Anatomy of Conditional Logic
In Helm, conditional logic is powered by Go templates. You wrap your resource definitions (or snippets of them) using the {{ if ... }} and {{ end }} actions. By referencing values defined in your values.yaml file, you can control the template rendering process.
Consider this example of an Ingress resource manifest that only renders if ingress.enabled is set to true:
{{- if .Values.ingress.enabled }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: {{ include "my-app.fullname" . }}
spec:
rules:
- host: {{ .Values.ingress.host }}
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: {{ include "my-app.fullname" . }}
port:
number: 80
{{- end }}
Implementing Else Blocks
Sometimes you need an alternative action. By adding an {{ else }} block, you can define fallback behavior. For instance, you could provide a default dummy service if an external dependency is not configured:
{{- if .Values.externalDatabase.enabled }}
# Logic to connect to external DB
{{- else }}
# Logic to deploy a local sidecar database
{{- end }}
By using the hyphen (-) within the template tags (e.g., {{- if ... }}), you can trim the whitespace around the blocks, ensuring that your rendered YAML remains clean and free of unnecessary empty lines. This approach keeps your charts DRY (Don't Repeat Yourself) while providing the flexibility to toggle entire architecture patterns with a single variable change during installation.
Key Takeaway: Use Helm’s if-else blocks to wrap entire resource templates, allowing you to toggle feature sets dynamically and maintain a single, highly flexible chart for multiple environments.