Go Template 與 Values
Vibe Prompt
「幫我寫 deployment.yaml 的 Helm 模板:支援 replicas、image tag、resources limits、環境變數、nodeSelector。」
templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "my-chart.fullname" . }}
labels:
{{- include "my-chart.labels" . | nindent 4 }}
spec:
replicas: {{ .Values.replicaCount }}
selector:
matchLabels:
{{- include "my-chart.selectorLabels" . | nindent 6 }}
template:
metadata:
labels:
{{- include "my-chart.selectorLabels" . | nindent 8 }}
spec:
containers:
- name: {{ .Chart.Name }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
ports:
- containerPort: 3000
resources:
{{- toYaml .Values.resources | nindent 12 }}
env:
{{- toYaml .Values.env | nindent 12 }}
常用函式
| 函式 | 用途 |
|------|------|
| {{ .Values.key }} | 讀取 values.yaml |
| {{ include "name" . }} | 引入 helpers.tpl |
| {{ nindent n "text" }} | 縮排 n 格 |
| {{ toYaml .Values.x }} | 轉為 YAML 字串 |
| {{ default "dev" .Values.env }} | 預設值 |
| {{- range .Values.items }} | 迴圈 |
| {{- if .Values.ingress.enabled }} | 條件 |
條件式 Ingress
{{- if .Values.ingress.enabled }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: {{ include "my-chart.fullname" . }}
spec:
ingressClassName: nginx
rules:
- host: {{ .Values.ingress.host }}
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: {{ include "my-chart.fullname" . }}
port:
number: {{ .Values.service.port }}
{{- end }}
關鍵要點
- ✅ 請根據本章主題補充具體的學習重點
- ✅ 建議加入比較表格、程式碼範例或流程圖
- ✅ 確保內容扎實且有價值
Go Template 除錯技巧:遇到問題怎麼辦?
寫 Go Template 最痛苦的經驗就是:Template 渲染失敗時,Helm 只給你一句模糊的錯誤訊息。
實用除錯工具
| 技巧 | 指令 | 用途 |
|:----|:----|:----|
| 乾執行 | helm install --dry-run --debug | 看到渲染後的完整 YAML |
| 模板語法檢查 | helm lint | 檢查 Chart 語法是否正確 |
| 渲染特定檔案 | helm template | 輸出 YAML 到 stdout |
| 函式測試 | {{ "hello" | upper | quote }} | 在範本中直接測試函式效果 |
最常犯的三個錯誤
-
忘記 indent:YAML 對縮排敏感,
{{ .Values.config }}直接插入會破壞縮排- ✅ 正確:
{{ .Values.config | indent 8 }}
- ✅ 正確:
-
nil pointer 錯誤:values.yaml 沒有定義某個欄位就使用
- ✅ 防禦:
{{ .Values.database.host | default "localhost" }}
- ✅ 防禦:
-
型態錯誤:
replicaCount: "3"(字串)vsreplicaCount: 3(數字)- ✅ 在 values.yaml 中使用正確的 YAML 型態
下一章預告:相依性與子圖表
學完 Template 語法後,你已經可以寫出動態的 Helm Chart 了。下一章將教你如何管理多個 Chart 之間的依賴關係——當你的應用需要依賴 Redis、MySQL 等外部服務時,如何用 Helm 的 dependencies 和子 Chart 優雅地管理。