Helm overview and basic use

overview

Reference: https://www.cnblogs.com/lyc94620/p/10945430.html

Introduction

Helm is a package management tool for k8s, similar to apt, yum and other package management tools commonly used in Linux systems. Using helm can simplify k8s application deployment.

Each package is called a Chart, and a Chart is a directory (generally, the directory will be packaged and compressed to form a single file in name-version.tgz format, which is convenient for transmission and storage).

For application publishers, Helm can be used to package applications, manage application dependencies, manage application versions, and publish applications to software warehouses.

For users, after using Helm, they do not need to understand the Yaml syntax of Kubernetes and write application deployment files. They can download and install the required applications on kubernetes through Helm.

In addition, Helm also provides powerful functions for software deployment, deletion, upgrade, and rollback of applications on kubernetes.


Components and related terms

Helm

Helm is a client tool under the command line. It is mainly used for the creation, packaging and release of the Kubernetes application Chart, as well as the creation and management of local and remote Chart warehouses.

Tiller

Tiller is the server of Helm, deployed in the Kubernetes cluster. Tiller is used to receive Helm's request, and generate the Kubernetes deployment file (Helm called Release) according to the Chart, and then submit it to Kubernetes to create the application. Tiller also provides a series of functions such as Release upgrade, deletion, and rollback.

Chart

Packages for Helm, in TAR format. It contains the images, dependencies and resource definitions (YAML) required to run an application, and may also contain service definitions in the Kubernetes cluster. Similar to APT's DEB package or YUM's RPM package.

Repoistory

Helm's software repository, Repository is essentially a web server, which saves a series of Chart packages for users to download, and provides a list file of the Repository's Chart packages for query. Helm can manage multiple different Repositories at the same time. When Helm is first installed, it is pre-configured to use the official Kubernetes chart repository repo. This repo contains many well designed and maintained charts. The charts repo is named stable by default.

Release

helm installAn instance of Chart deployed in a Kubernetes cluster using the command is called a Release. On the same cluster, a Chart can be installed many times. Each installation creates a new release. For example, a MySQL Chart, if you want to run two databases on the server, you can install the Chart twice. Each installation will generate its own Release with its own Release name.

Note: It should be noted that the Release mentioned in Helm is different from the version in the general concept. The Release here can be understood as an application instance deployed by Helm using the Chart package.


working principle

insert image description here

Chart Install process:

  1. Helm parses the Chart structure information from the specified directory or tgz file
  2. Helm passes the specified Chart structure and Values ​​information to Tiller through gRPC
  3. Tiller generates a Release based on Chart and Values
  4. Tiller sends the Release to Kubernetes for generating the Release

Chart Update process:

  1. Helm parses the Chart structure information from the specified directory or tgz file
  2. Helm passes the name of the Release to be updated, the Chart structure, and the Values ​​information to Tiller
  3. Tiller generates a Release and updates the History of the Release with the specified name
  4. Tiller sends the Release to Kubernetes for updating the Release

Chart Rollback process:

  1. Helm passes Tiller the name of the Release to be rolled back
  2. Tiller looks up History based on the name of the Release
  3. Tiller gets the last Release from History
  4. Tiller sends the previous Release to Kubernetes to replace the current Release

template syntax

1. Expression

  • Template expression: { { template expression }}

  • Template expression: { {- template expression-}}, which means to remove the spaces before and after the output result of the expression. To remove the preceding space, you can write { {- template expression }}, and remove the following space { { template expression-}}


2. Variables

By default, a dot ( . ) represents the global scope and is used to refer to the global object.

example:

# 这里引用了全局作用域下的Values对象中的key属性。 
{
    
    {
    
     .Values.key }}

There are two important global objects in the helm global scope: Values ​​and Release

**Values ​​** represents the parameters defined by values.yaml, and any parameter can be referenced through .Values .

example:

{
    
    {
    
     .Values.replicaCount }}

# 引用嵌套对象例子,跟引用json嵌套对象类似
{
    
    {
    
     .Values.image.repository }}

**Release** represents an application release. The following are the attribute fields contained in the Release object:

  • Release.Name : The name of the release, generally defined through Chart.yaml, or specified when installing the application through the helm command.
  • Release.Time: release installation time
  • Release.Namespace : k8s namespace
  • Release.Revision: The release version number is an incremental value, which will be incremented every time it is updated
  • Release.IsUpgrade: true means that the current release is an update
  • Release.IsInstall: true means that the current release is an installation

example:

{
    
    {
    
     .Release.Name }}

In addition to the variables that come with the system, you can also customize template variables.

# The variable name starts with $, and the assignment operator is : = (colon + equal sign)

{
    
    {
    
    - $relname := .Release.Name -}}

Quoting custom variables:

# 不需要 . 引用
{
    
    {
    
     $relname }}

3. Function & pipeline operator

(1) Syntax for calling a function: { { functionName arg1 arg2… }}

example:

# 调用quote函数:将结果用“”引号包括起来。
{
    
    {
    
     quote .Values.favorite.food }}

(2) Pipelines operator |

Similar to linux shell commands, multiple commands are stringed together through the pipeline | to process the content output by the template.

example:

# 将.Values.favorite.food传递给quote函数处理,然后在输出结果。
{
    
    {
    
     .Values.favorite.food | quote }}

# 先将.Values.favorite.food的值传递给upper函数将字符转换成大写,然后专递给quote加上引号包括起来。
{
    
    {
    
     .Values.favorite.food | upper | quote }}

# 如果.Values.favorite.food为空,则使用default定义的默认值
{
    
    {
    
     .Values.favorite.food | default "默认值" }}

# 将.Values.favorite.food输出5次
{
    
    {
    
     .Values.favorite.food | repeat 5 }}

# 对输出结果缩进2个空格
{
    
    {
    
     .Values.favorite.food | nindent 2 }}

(3) The commonly used relational operators >, >=, <, !=, and or not are implemented in the form of functions in the helm template.

Relational operation function definition:

eq  相当于 =
ne  相当于 !=
lt  相当于 <=
gt  相当于 >=
and 相当于 &&
or  相当于 ||
not 相当于 !

example:

# 相当于 if (.Values.fooString && (.Values.fooString == "foo"))
{
    
    {
    
     if and .Values.fooString (eq .Values.fooString "foo") }}
{
    
    {
    
     ... }}
{
    
    {
    
     end }}

4. Flow control statement: IF/ELSE, with, range

(1)IF/ELSE

grammar:

{
    
    {
    
     if 条件表达式 }}
Do something
{
    
    {
    
     else if 条件表达式 }}
Do something else
{
    
    {
    
     else }}
Default case
{
    
    {
    
     end }}

example:

apiVersion: v1
kind: ConfigMap
metadata:
  name: {
    
    {
    
     .Release.Name }}-configmap
data:
  myvalue: "Hello World"
  drink: {
    
    {
    
     .Values.favorite.drink | default "tea" | quote }}
  food: {
    
    {
    
     .Values.favorite.food | upper | quote }}
  {
    
    {
    
    if eq .Values.favorite.drink "coffee"}}
    mug: true
  {
    
    {
    
    end}}

(2)with

with is mainly used to modify the scope, the default. represents the global scope, and the with statement can modify the meaning of.

grammar:

{
    
    {
    
     with 引用的对象 }}
这里可以使用 . (点), 直接引用with指定的对象
{
    
    {
    
     end }}

example:

# .Values.favorite是一个object类型
{
    
    {
    
    - with .Values.favorite }}
drink: {
    
    {
    
     .drink | default "tea" | quote }}  #相当于.Values.favorite.drink
food: {
    
    {
    
     .food | upper | quote }}
{
    
    {
    
    - end }}

ps: It cannot be used in the scope of with. To reference the global object, if you must refer to the global object in with, you can first copy the global object to a variable outside the with, and then use this variable inside the with to refer to the global object.

example:

{
    
    {
    
    - $release:= .Release.Name -}}  #先将值保存起来

{
    
    {
    
    - with .Values.favorite }}
drink: {
    
    {
    
     .drink | default "tea" | quote }}  #相当于.Values.favorite.drink
food: {
    
    {
    
     .food | upper | quote }}
release: {
    
    {
    
     $release }} #间接引用全局对象的值
{
    
    {
    
    - end }}

(3)range

range is mainly used for looping through array types.

Grammar 1:

# 遍历map类型,用于遍历键值对象
# 变量key代表对象的属性名,val代表属性值
{
    
    {
    
    - range key,val := 键值对象 }}
{
    
    {
    
     $key }}: {
    
    {
    
     $val | quote }}
{
    
    {
    
    - end}}

Grammar 2:

{
    
    {
    
    - range 数组 }}
{
    
    {
    
     . | title | quote }} 	# . (点),引用数组元素值。
{
    
    {
    
    - end }}

example:

# values.yaml定义
 
# map类型
favorite:
  drink: coffee
  food: pizza
 
# 数组类型
pizzaToppings:
  - mushrooms
  - cheese
  - peppers
  - onions
 
# map类型遍历例子:
{
    
    {
    
    - range $key, $val := .Values.favorite }}
{
    
    {
    
     $key }}: {
    
    {
    
     $val | quote }}
{
    
    {
    
    - end}}
 
# 数组类型遍历例子:
{
    
    {
    
    - range .Values.pizzaToppings}}
{
    
    {
    
     . | quote }}
{
    
    {
    
    - end}}

5. Sub-template definition

Sub-templates can be defined in files beginning with _ (underscore) for subsequent reuse.

helm create creates the _helpers.tpl public library definition file by default, you can directly define sub-templates in it, or create a new one, as long as the name starts with an underscore.

Subtemplate syntax:

# 定义模版
{
    
    {
    
     define "模版名字" }} 
模版内容
{
    
    {
    
     end }}

# 引用模版
{
    
    {
    
     include "模版名字" 作用域}}

example:

# 模版定义
{
    
    {
    
    - define "mychart.app" -}}
app_name: {
    
    {
    
     .Chart.Name }}
app_version: "{
    
    { .Chart.Version }}+{
    
    { .Release.Time.Seconds }}"
{
    
    {
    
    - end -}}
 
apiVersion: v1
kind: ConfigMap
metadata:
  name: {
    
    {
    
     .Release.Name }}-configmap
  labels:
    {
    
    {
    
     include "mychart.app" . | nindent 4 }} #引用mychart.app模版内容,并对输出结果缩进4个空格
data:
  myvalue: "Hello World"

6. Debugging

After writing the template of the chart package, we can add --debug --dry-runtwo parameters to the helm command to let helm output the template result, but do not hand over the template output result to k8s for processing .

example:

# helm install命令类似,加上--debug --dry-run两个参数即可
$ helm upgrade --debug --dry-run -i set replicas=2 --set host=www.xxxx.com myapp ./myapp

Common commands

Reference: https://www.hellodemos.com/hello-helm-command/helm-command-demos.html

Multi-use optional parameters -hor --help, see command details

chart instance management

View, create and delete chart instances

# 查看chart实例列表
$ helm list
# 查看全部的chart实例(包括删除的)	
helm list -a
# 列出已经删除的Release
helm ls --deleted 

# 查看指定的chart实例信息
$ helm status RELEASE_NAME [flags]


# 创建chart实例部署到k8s
$ helm install chart包 [flags]
# 常用可选参数:
    --name str				# 指定helm实例名称
    --namespace str			# 指定安装的namespace。不指定则默认命名空间
    --version str			# 指定charts版本
    -f values.yaml			# 从文件读取自定义属性集合
    --set "key=value"		# 通过命令方式注入自定义参数,用于覆盖values.yaml定义的值
    						  # 对象类型数据可以用 . (点)分割属性名。示例: --set apiApp.requests.cpu=1
    						  # 可以使用多个 --set 指定多个参数
# 示例
helm install --name test --namespace test ./helm-chart


# 删除chart实例(注意:若不加purge参数,则并没有彻底删除)
$ helm delete RELEASE_NAME [flags]
# 选项:
	--purge		# 彻底删除实例,并释放端口
# 示例:
helm delete --purge RELEASE_NAME 

Update and rollback of chart instance

# 更新chart实例。默认情况下,如果chart实例名不存在,则upgrade会失败
$ helm upgrade [选项] 实例名称 [chart包目录] [flags]
# 选项:
	-i						# 实例名存在则更新,不存在时则安装(合并了install和uprade命令功能)
	--set "key=value"		# 通过命令方式注入自定义参数
# 示例:根据chart包更新chart实例
helm upgrade myapp ./myapp
helm upgrade -i myapp ./myapp
# 示例:使用–set参数更新chart实例
helm upgrade --set replicas=2 --set host=www.xxxx.com myapp


# 查看chart实例的版本信息
$ helm history HELM_NAME [flags]

# 回滚chart实例的指定版本
$ helm rollback HELM_NAME [REVISION] [flags]

charts package management

Search, display and download of charts package

# 在Artifact Hub或自己的hub实例中搜索Helm charts
$ helm search hub [KEYWORD] [flags]

# 搜索系统上配置的所有仓库,并查找匹配
$ helm search repo [keyword] [flags]
# 说明:
	[KEYWORD]	# 参数接受关键字字符串或者带引号的查询字符串

# 显示指定chart包(目录、文件或URL)中的Charts.yaml文件内容
$ helm show chart [CHART] [flags]
# 显示指定chart(目录、文件或URL)中的README文内容
$ helm show readme [CHART] [flags]
# 显示指定chart(目录、文件或URL)包中的values.yaml文件内容
$ helm show values [CHART] [flags]
# 显示指定chart(目录、文件或URL)中的所有的内容(values.yaml, Charts.yaml, README)
$ helm show all [CHART] [flags]

# 从包仓库中检索包并下载到本地
$ helm pull [chart URL | repo/chartname] [...] [flags]

# 下载charts到本地
$ helm fetch redis

Custom charts package

# 创建charts包
$ helm create NAME [flags]
# 选项:
	-p, --starter string 	# 名称或绝对路径。
							  # 如果给定目录路径不存在,Helm会自动创建。
							  # 如果给定目录存在且非空,冲突文件会被覆盖,其他文件会被保留。

# 检查chart语法正确性
$ helm lint myapp

# 打包成一个chart版本包文件。
$ helm package [CHART_PATH] [...] [flags]

# 查看生成的yaml文件
$ helm template myapp-1.tgz

helm warehouse management: helm repo

Listing, adding, deleting, updating and indexing of repositories

grammar:

$ helm repo COMMAND [flags]
从父命令继承的可选参数:
		--debug                       启用详细输出
      	--kube-apiserver string       Kubernetes-API服务器的地址和端口
      	--kube-as-group stringArray   Kubernetes操作的组,可以重复此标志以指定多个组。
      	--kube-as-user string         Kubernetes操作的用户名
      	--kube-ca-file string         Kubernetes-API服务器连接的认证文件
      	--kube-context string         kubeconfig context的名称
      	--kube-token string           用于身份验证的字符串令牌
      	--kubeconfig string           kubeconfig文件的路径
  -n, 	--namespace string            该请求的作用域的命名空间名称
      	--registry-config string      注册表配置文件的路径 (default "~/.config/helm/registry.json")
      	--repository-cache string     包含缓存库索引的文件的路径 (default "~/.cache/helm/repository")
      	--repository-config string    包含仓库名称和url的文件的路径 (default "~/.config/helm/repositories.yaml")

Common commands

# 查看chart仓库列表
$ helm repo list [flags]
# 选项:
	-o, --output format :打印指定格式的输出。支持的格式:table, json, yaml (default table)

# 从chart仓库中更新本地可用chart的信息
$ helm repo update [flags]

# 读取当前目录,并根据找到的chart为chart仓库生成索引文件(index.yaml)。
$ helm repo index
# 选项
	--merge string   # 合并生成的索引到已经存在的索引文件
	--url string     # chart仓库的绝对URL
		
# 添加chart仓库
$ helm repo add [NAME] [URL] [flags]
$ helm repo add myharbor https://harbor.qing.cn/chartrepo/charts --username admin --password password
		
# 删除一个或多个仓库
$ helm repo remove [REPO1 [REPO2 ...]] [flags]

other commands

helm dependency : manage chart dependencies

# 列举所有的chart中声明的依赖
helm dependency list
# 列举指定chart的依赖
helm dependency list CHART [flags]
# 查看helm版本
$ helm version

# 打印所有Helm使用的客户端环境信息
$ helm env [flags]

basic use

Here is an example of making a simple website application chart package to introduce the basic usage of helm.

ps: Skip the process of making a docker image here. For image making, please refer to: Docker Basic Tutorial


1. Create a chart package

Create a new chart package through the helm create command

example:

# 在当前目录创建一个myapp chart包
$ helm create myapp

After the creation is complete, the obtained directory structure is as follows:

myapp                      - chart 包目录名
├── charts                 - 依赖的子包目录,里面可以包含多个依赖的chart包
├── Chart.yaml             - chart定义,可以定义chart的名字,版本号信息
├── templates              - k8s配置模版目录,编写的k8s配置都在这个目录
│	│						 除了NOTES.txt和下划线开头命名的文件,其他文件可以随意命名
│   ├── deployment.yaml
│   ├── _helpers.tpl       - 下划线开头的文件,helm视为公共库定义文件,主要用于定义通用的子模版、函数等
│	│						 helm不会将这些公共库文件的渲染结果提交给k8s处理
│   ├── ingress.yaml
│   ├── NOTES.txt          - chart包的帮助信息文件,执行helm install命令安装成功后会输出这个文件的内容
│   └── service.yaml
└── values.yaml            - chart包的参数配置文件,模版可以引用这里参数

To deploy a website application in k8s, you need to write three configuration files: deployment, service, and ingress , which have been created by the helm create command just now.


2. Write k8s application deployment configuration file

In order to demonstrate the usage of the chart package template, first clear the contents of the deployment, service, and ingress configuration files, and rewrite the k8s deployment file.

The deployment.yaml configuration file is defined as follows:

apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: myapp           #deployment应用名
  labels:
    app: myapp          #deployment应用标签定义
spec:
  replicas: 1           #pod副本数
  selector:
    matchLabels:
      app: myapp          #pod选择器标签
  template:
    metadata:
      labels:
        app: myapp          #pod标签定义
    spec:
      containers:
        - name: myapp           #容器名
          image: xxxxxx:1.7.9    #镜像地址
          ports:
            - name: http
              containerPort: 80
              protocol: TCP

service.yaml is defined as follows:

apiVersion: v1
kind: Service
metadata:
  name: myapp-svc 	#服务名
spec:
  selector: 	#pod选择器定义
    app: myapp
  ports:
  - protocol: TCP 
    port: 80
    targetPort: 80

ingress.yaml is defined as follows:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: myapp-ingress 	#ingress应用名
spec:
  rules:
    - host: www.xxxxx.com  #域名
      http:
        paths: 
          - path: /  
            backend: 
              serviceName: myapp-svc 	#服务名
              servicePort: 80

3. Extract the parameters in the k8s application deployment configuration file as chart package parameters.

The defined k8s configuration files cannot be called templates, they are all fixed configurations. (The template mentioned here is similar to the template technology that everyone usually uses when doing front-end development. It is a concept)

By extracting the parameters in the configuration and injecting template variables, the template expression converts the configuration file into a template file , and helm dynamically renders the template file into the final configuration file according to the parameters at runtime .


Next, convert the three configuration files **deployment, service, and ingress** into template files.

The deployment.yaml configuration template is as follows:

apiVersion: apps/v1beta2
kind: Deployment
metadata:
  name: {
    
    {
    
     .Release.Name }}  #deployment应用名
  labels:
    app: {
    
    {
    
     .Release.Name }}     #deployment应用标签定义
spec:
  replicas: {
    
    {
    
     .Values.replicas}}    #pod副本数
  selector:
    matchLabels:
      app: {
    
    {
    
     .Release.Name }}       #pod选择器标签
  template:
    metadata:
      labels:
        app: {
    
    {
    
     .Release.Name }}     #pod标签定义
    spec:
      containers:
        - name: {
    
    {
    
     .Release.Name }}           #容器名
          image: {
    
    {
    
     .Values.image }}:{
    
    {
    
     .Values.imageTag }}    #镜像地址
          ports:
            - name: http
              containerPort: 80
              protocol: TCP

service.yaml is defined as follows:

apiVersion: v1
kind: Service
metadata:
  name: {
    
    {
    
     .Release.Name }}-svc 	#服务名
spec:
  selector: 	#pod选择器定义
    app: {
    
    {
    
     .Release.Name }}
  ports:
  - protocol: TCP 
    port: 80
    targetPort: 80

ingress.yaml is defined as follows:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: {
    
    {
    
     .Release.Name }}-ingress 	#ingress应用名
spec:
  rules:
    - host: {
    
    {
    
     .Values.host }}  	#域名
      http:
        paths: 
          - path: /  
            backend: 
              serviceName: {
    
    {
    
     .Release.Name }}-svc 	#服务名
              servicePort: 80

Values.yaml chart package parameter definition:

#域名
host: www.XXX.com
 
#镜像参数
image: XXXXXXXXXXXXXXXXXX
imageTag: 1.7.9
 
#pod 副本数
replicas:1

4. Install/update the application through the helm command

Install the app:

$ helm install ./myapp

Inject parameters via command

$ helm install --set replicas=2 --set host=www.xxxx.com ./myapp

Update app:

# 命令格式: helm upgrade release名字  chart包目录
$ helm upgrade myapp ./myapp

# 也可以指定–set参数
$ helm upgrade --set replicas=2 --set host=www.xxxx.com myapp ./myapp

# 默认情况下,如果release名字不存在,upgrade会失败
# 可以加上-i 参数当release不存在的时候则安装,存在则更新,将install和uprade命令合并
$ helm upgrade -i --set replicas=2 --set host=www.xxxx.com myapp ./myapp

Guess you like

Origin blog.csdn.net/footless_bird/article/details/125844110