variable
1. Concept
Functions, pipe symbols, objects and control structures can be controlled. We turn to one of the more basic ideas in many programming languages: variables. In the template, it is rarely used. But we can use variables to simplify the code and make better use of with and range.
We will see the failure in the following code:
{{- with .Values.favorite }} drink: {{ .drink | default "tea" | quote }} food: {{ .food | upper | quote }} release: {{ .Release.Name }} {{- end }}
Release.Name is not within the limits of the with block. One way to solve the scope problem is to assign objects to variables that can be accessed regardless of the current scope.
2. Syntax format
In the Helm template, a variable is a named reference to another object. Follows the format of the $name variable and specifies a special assignment operator:: =. We can use for release The variable name overrides the above.
apiVersion: v1 kind: ConfigMap metadata: name: {{ .Release.Name }}-configmap data: myvalue: "Hello World" {{- $relname := .Release.Name -}} {{- with .Values.favorite }} drink: {{ .drink | default "tea" | quote }} food: {{ .food | upper | quote }} release: {{ $relname }} {{- end }}
Note: before the start of the with block, assign $relname: = Release. Name. Now in the with block, the $relname variable will still execute the version name
# Operation results apiVersion: v1 kind: ConfigMap metadata: name: viable-badger-configmap data: myvalue: "Hello World" drink: "coffee" food: "PIZZA" release: viable-badger
3. Examples
The data structure is single data
- value.yaml
# values.yaml pizzaToppings: - mushrooms - cheese - peppers - onions
- Define template
change amount stay Variable in Variable in range Follow ring in special other have use . can with use to class as if column surface of yes as , with catch Obtain Rope lead and value Especially useful in loops. Can be used with list like objects to capture indexes and values Especially useful in loops. Can be used with list like objects to capture indexes and values
toppings: |- {{- range $index, $topping := .Values.pizzaToppings }} {{ $index }}: {{ $topping }} {{- end }}
- Output results
notes meaning before yes Attention, first Pay attention to the range first , however after yes change amount , however after yes Fu value transport count symbol , however after yes column surface . meeting take whole type Rope lead ( from 0 open beginning ) Fu value to , then variables, then assignment operators, then lists. The integer index (starting from 0) is assigned to , then variables, then assignment operators, then lists. The integer index (starting from 0) is assigned to $index and take value Fu value to And assign the value to And assign the value to $topping
toppings: |- 0: mushrooms 1: cheese 2: peppers 3: onions
Data structures include key and value
- values.yaml
favorite: drink: coffee food: pizza
- Define template
yes to number according to junction structure have For data structures key for data structure and and And value , can with send use , you can use , you can use range Obtain take obtain Get key and and And value . than as , can with through too . For example, you can . For example, through Values.favorite enter that 's ok Follow ring Cycle Cycle
apiVersion: v1 kind: ConfigMap metadata: name: {{ .Release.Name }}-configmap data: myvalue: "Hello World" {{- range $key, $val := .Values.favorite }} {{ $key }}: {{ $val | quote }} {{- end }}
- Output results
The first one second Overlap generation , The first iteration, First iteration, $key meeting yes Yes It'll be drink And And And $val meeting yes Yes It'll be coffee , The first two second Overlap generation , second iteration , second iteration $key meeting yes Yes It will be food And And And $val meeting yes Yes It's gonna be pizza
apiVersion: v1 kind: ConfigMap metadata: name: eager-rabbit-configmap data: myvalue: "Hello World" drink: "coffee" food: "pizza"
4. Supplementary notes
Variables are generally not "global". The scope is the block in which it is declared. Above, we assigned $relname at the top level of the template. The scope of the variable will be the entire template. But in the last example, $key and $val scope will be in {{range...}} {{end}} block.
But one variable is always Global - $- this variable always points to the root context. It is useful when looping in a range, and you need to know the version name of chart.
{{- range .Values.tlsSecrets }} apiVersion: v1 kind: Secret metadata: name: {{ .name }} labels: # Many helm templates would use `.` below, but that will not work, # however `$` will work here app.kubernetes.io/name: {{ template "fullname" $ }} # I cannot reference .Chart.Name, but I can do $.Chart.Name helm.sh/chart: "{{ $.Chart.Name }}-{{ $.Chart.Version }}" app.kubernetes.io/instance: "{{ $.Release.Name }}" # Value from appVersion in Chart.yaml app.kubernetes.io/version: "{{ $.Chart.AppVersion }}" app.kubernetes.io/managed-by: "{{ $.Release.Service }}" type: kubernetes.io/tls data: tls.crt: {{ .certificate }} tls.key: {{ .key }} --- {{- end }}
Naming template
1. Concept
A named template (sometimes called a part or a sub template) is simply a template defined inside a file and uses a name. There are two creation methods and several different usage methods.
Three ways to declare and manage templates
- define declares a new named template in the template
- Template import a named template
- Block declares a special template block that can be filled
be careful:
- The template name is global. If you want to declare two templates with the same name, whichever is last loaded will be used. Because the template in the child chart is compiled together with the top-level template, pay attention to the specific name of chart when naming.
- A common naming convention is to prefix the template with the chart Name: {{define "mychart.labels"}}. Using a specific chart name as a prefix can avoid possible conflicts caused by two different charts using templates with the same name.
2. Local and_ file
A single file contains a single template. But Helm's template language allows you to create named embedded templates that can be accessed by name elsewhere.
- Most of the files in templates / are considered to contain the Kubernetes manifest
- NOTES.txt is an exception
- Name dash () The initial file assumes that it does not contain the contents of the list. These files are not rendered as Kubernetes object definitions, but are available in other chart templates
These files are used to store local and auxiliary objects. In fact, when we first create mychart, we will see a file named_ helpers.tpl file, which is the default location of the template part
3. define and template declare and use templates
The define operation allows us to create a named template in the template file
{{ define "MY.NAME" }} # body of template here {{ end }}
- Define a template to encapsulate the label of Kubernetes: default
{{- define "mychart.labels" }} labels: generator: helm date: {{ now | htmlDate }} {{- end }}
- The template is embedded in the existing template
{{- define "mychart.labels" }} labels: generator: helm date: {{ now | htmlDate }} {{- end }} apiVersion: v1 kind: ConfigMap metadata: name: {{ .Release.Name }}-configmap {{- template "mychart.labels" }} data: myvalue: "Hello World" {{- range $key, $val := .Values.favorite }} {{ $key }}: {{ $val | quote }} {{- end }}
- Render results
When model plate lead Hold read take Should writing piece Time , it meeting Save Store When the template engine reads the file, it stores When the template engine reads the file, it stores mychart labels of lead use straight reach References until Until template "mychart.labels" cover transfer use . however after meeting Press that 's ok Shading dye model plate Called. The template is then rendered in rows Called. The template is then rendered in rows
apiVersion: v1 kind: ConfigMap metadata: name: running-panda-configmap labels: generator: helm date: 2021-05-16 data: myvalue: "Hello World" drink: "coffee" food: "pizza"
Note: define will not have output unless it is called with a template as in this example.
4. _helpers.tpl file
Helm chart places these templates in local files, usually_ helpers.tpl
- Define template
# _helpers.tpl {{/* Generate basic labels */}} {{- define "mychart.labels" }} labels: generator: helm date: {{ now | htmlDate }} {{- end }}
Description: the define method will have a simple document block {/ *... * /}} to describe what to do
- Call template
all Manage this individual set righteousness yes stay Although this definition is in Although this definition is in_ helpers.tpl in , but it still can interview ask But it can still be accessed But it can still access configmap yaml
apiVersion: v1 kind: ConfigMap metadata: name: {{ .Release.Name }}-configmap {{- template "mychart.labels" }} data: myvalue: "Hello World" {{- range $key, $val := .Values.favorite }} {{ $key }}: {{ $val | quote }} {{- end }}
5. include method
- Suppose a simple template is defined as follows:
{{- define "mychart.app" -}} app_name: {{ .Chart.Name }} app_version: "{{ .Chart.Version }}" {{- end -}}
- Requirement: I want to insert this into the labels: part and data: part of the template:
apiVersion: v1 kind: ConfigMap metadata: name: {{ .Release.Name }}-configmap labels: {{ template "mychart.app" . }} data: myvalue: "Hello World" {{- range $key, $val := .Values.favorite }} {{ $key }}: {{ $val | quote }} {{- end }} {{ template "mychart.app" . }}
- Output error message
$ helm install --dry-run measly-whippet ./mychart Error: unable to build kubernetes objects from release manifest: error validating "": error validating data: [ValidationError(ConfigMap): unknown field "app_name" in io.k8s.api.core.v1.ConfigMap, ValidationError(ConfigMap): unknown field "app_version" in io.k8s.api.core.v1.ConfigMap]
To see what is rendered, you can re execute with the -- Disable OpenAPI validation parameter: helm install -- dry run -- Disable OpenAPI validation meanly Whippet/ mychart
apiVersion: v1 kind: ConfigMap metadata: name: measly-whippet-configmap labels: app_name: mychart app_version: "0.1.0" data: myvalue: "Hello World" drink: "coffee" food: "pizza" app_name: mychart app_version: "0.1.0"
Note: apps in two places_ Version is not indented correctly. Why? Because the text in the replaced template is left aligned. Because template is a behavior, not a method, the output of the template call cannot be passed to other methods, and the data is simply inserted by line
- Modify template
Helm carry Offer Yes one individual Provides a A template is provided of can choose term , can with take model plate within Allow guide enter When front Manage Avenue , however after pass Deliver to Manage Avenue in of his he square method , send use Optionally, you can import the template content into the current pipeline and then pass it to other methods in the pipeline Optionally, you can import the template content into the current pipeline, and then pass it to other methods in the pipeline, using indent just Indeed land shrink enter Indent correctly Indent mychart. Correctly app model plate Template Template
apiVersion: v1 kind: ConfigMap metadata: name: {{ .Release.Name }}-configmap labels: {{ include "mychart.app" . | indent 4 }} data: myvalue: "Hello World" {{- range $key, $val := .Values.favorite }} {{ $key }}: {{ $val | quote }} {{- end }} {{ include "mychart.app" . | indent 2 }}
- Output information
apiVersion: v1 kind: ConfigMap metadata: name: edgy-mole-configmap labels: app_name: mychart app_version: "0.1.0" data: myvalue: "Hello World" drink: "coffee" food: "pizza" app_name: mychart app_version: "0.1.0"
6. Supplementary notes
- Using include instead of template in Helm template is considered a better way, just to better deal with the output format of YAML documents.
- Sometimes we need to import content, but not as a template, that is, import file content literally, which can be used Files object to access files (next chapter)