Advanced Helm Tech

501 阅读1分钟

_helper.tpl的一些示例

{{- define "chart.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }} #.Values.fullnameOverride是否存在,是则打印
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }} #赋值变量name,默认为.Chart.Name,.Chart.Name不存在,则为.Values.nameOverride
{{- if contains $name .Release.Name }} #变量name是否包含.Release.Name
{{- .Release.Name | trunc 63 | trimSuffix "-" }} #是则打印,trunc限制长度、trimSuffix去除尾部
{{- else }}{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }} #否则输出.Release.Name-$name
{{- end }}
{{- end }}
{{- end }}

{{- define "chart.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }} #将+替换为_

helm.sh/chart: {{ include "chart.chart" . }} #引用模板时末尾传入.可以打印模板中的变量

{{- define "chart.serviceAccountName" -}}
{{- if .Values.serviceAccount.create }} #.Values.serviceAccount.create值存在则为真
{{- default (include "chart.fullname" .) .Values.serviceAccount.name }}
{{- else }}
{{- default "default" .Values.serviceAccount.name }} #给.Values.serviceAccount.name设置默认值为default
{{- end }}
{{- end }}

{{- define "chart.appConfig" -}}
{{- $configFile := "config.yaml" -}}
{{ if .Files.Get $configFile }} #判断configFile文件是否存在
{{ .Files.Get $configFile }} #输出文件内容
{{ else }}
{{ fail "You need to copy a config.yaml to the root dir of the chart." }} #报错信息
{{ end }}
{{- end }}

引用模板和变量

  {{- if not .Values.autoscaling.enabled }} #如果enabled为false  replicas: {{ .Values.replicaCount }}  {{- end }}

checksum/config: {{ include "chart.appConfig" . | sha256sum }} #helm upgrade时,如果deploy配置没有发生变化,会根据配置文件的更改,触发更新deploy

{{- $host := quote (printf "%s.%s.%s" (required "backendName is required" .Values.ingress.backendName) .Values.gitlab.env .Values.ingress.baseDomain ) -}} #在template文件里定义变量,required值必须存在,否则报错

{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion -}} #判断k8s集群版本,GitVersion会返回VersionapiVersion: networking.k8s.io/v1{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}}apiVersion: networking.k8s.io/v1beta1{{- else -}}apiVersion: extensions/v1beta1{{- end }}

helm capabilities源码:github.com/helm/helm/b…

ingress多个path循环创建资源

{{- if .Values.ingress.enabled -}}
...
---
{{- range .Values.ingress.extraPaths }}
...
---
{{- end }}{{- end }}

拼接变量、拼接变量字符串

name: {{ $fullName }}-{{ .name }}
name: {{ include "chart.fullname" . }}-mq-worker