Helm-Kubernetes

一. 安装

wget https://get.helm.sh/helm-v3.2.4-linux-amd64.tar.gz
tar -zxf helm-v3.2.4-linux-amd64.tar.gz
cp linux-amd64/helm /usr/local/bin/
helm version

二. 使用

1. chart

# 创建一个chart
helm create mychart


[root@k8s ~]# tree  mychart/
mychart/
├── charts					# 存放子chart的目录,目录中可存放这个chart依赖的的所有子chart
├── Chart.yaml				# chart的yaml文件, 用来描述这个chart的基本信息
├── templates				# 存放的模板文件, 部署的的yaml文件都放在这个目录在中
│   ├── deployment.yaml
│   ├── _helpers.tpl		# 防止模板助手文件, 可以在整个chart中重复使用,是放一些templates目录下这些yaml都有可能会用的一些模板
│   ├── hpa.yaml
│   ├── ingress.yaml
│   ├── NOTES.txt			# 存放提示提示信息的文件, 介绍chart的帮助信息,helm install部署后展示给用户,如何使用chart等, 部署chart后给用户的提示信息
│   ├── serviceaccount.yaml
│   ├── service.yaml
│   └── tests				# 用于测试的文件, 测试完部署完chart后,如web, 做一个链接, 看看是否部署正常
│       └── test-connection.yaml
└── values.yaml				# 用于渲染的模板文件,变量文件,定义变量的值,定义template目录下的yaml文件可能引用的变量

2. Chart.yaml

  • 用来描述这个chart的基本信息
apiVersion: v2
name: mychart
description: A Helm chart for Kubernetes

# A chart can be either an 'application' or a 'library' chart.
#
# Application charts are a collection of templates that can be packaged into versioned archives
# to be deployed.
#
# Library charts provide useful utilities or functions for the chart developer. They're included as
# a dependency of application charts to inject those utilities and functions into the rendering
# pipeline. Library charts do not define any templates and therefore cannot be deployed.
type: application

# This is the chart version. This version number should be incremented each time you make changes
# to the chart and its templates, including the app version.
# Versions are expected to follow Semantic Versioning (https://semver.org/)
version: 0.1.0

# This is the version number of the application being deployed. This version number should be
# incremented each time you make changes to the application. Versions are not expected to
# follow Semantic Versioning. They should reflect the version the application is using.
appVersion: 1.16.0

3. values.yaml

  • 主要是定义一些变量信息
# Default values for mychart.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.

replicaCount: 1

image:
  repository: nginx
  pullPolicy: IfNotPresent
  # Overrides the image tag whose default is the chart appVersion.
  tag: ""

imagePullSecrets: []
nameOverride: ""
fullnameOverride: ""

serviceAccount:
  # Specifies whether a service account should be created
  create: true
  # Annotations to add to the service account
  annotations: {}
  # The name of the service account to use.
  # If not set and create is true, a name is generated using the fullname template
  name: ""

podAnnotations: {}

podSecurityContext: {}
  # fsGroup: 2000

securityContext: {}
  # capabilities:
  #   drop:
  #   - ALL
  # readOnlyRootFilesystem: true
  # runAsNonRoot: true
  # runAsUser: 1000

service:
  type: ClusterIP
  port: 80

ingress:
  enabled: false
  annotations: {}
    # kubernetes.io/ingress.class: nginx
    # kubernetes.io/tls-acme: "true"
  hosts:
    - host: chart-example.local
      paths: []
  tls: []
  #  - secretName: chart-example-tls
  #    hosts:
  #      - chart-example.local

resources: {}
  # We usually recommend not to specify default resources and to leave this as a conscious
  # choice for the user. This also increases chances charts run on environments with little
  # resources, such as Minikube. If you do want to specify resources, uncomment the following
  # lines, adjust them as necessary, and remove the curly braces after 'resources:'.
  # limits:
  #   cpu: 100m
  #   memory: 128Mi
  # requests:
  #   cpu: 100m
  #   memory: 128Mi

autoscaling:
  enabled: false
  minReplicas: 1
  maxReplicas: 100
  targetCPUUtilizationPercentage: 80
  # targetMemoryUtilizationPercentage: 80

nodeSelector: {}

tolerations: []

affinity: {}

三. 部署应用

1. 预览yaml

# myrelease为指定的release的名称, 且必须指定,--dry-run 可以看yaml
helm install myrelease mychart/ --dry-run
# 试运行
helm install myrelease mychart/ --dry-run --debug

# 直接部署,不是的时候,需要给整个渲染后的yaml定义一个release name
helm install ${release_name} mychart/

# 部署完后, 查看release
helm list

# 不熟完后, 也可以查看部署的实例的yaml信息,
helm get manifest ${release_name}

# 删除实例
helm uninstall ${release_name}

三. helm内置对象

  • Release
  • Values
  • Chart
  • Capabilities
  • Template

1. Release内置对象

  • 描述了版本发布自身的一些信息, 他包含以下对象
.Release.Name				# release名称
.Release.Namespace			# release的名称空间
.Release.IsUpgrade			# 如果当前操作是升级或回滚的话,为true
.Release.IsInstall			# 如果当前操作是安装的话,该值为true
.Release.Revision			# 获取此次修订的版本号,初次安装时为1,每次升级或回滚都会递增
.Release.Service			# 获取渲染当前模板的服务名称,一般都是Helm

(1). 案例

helm create mychart
cd mychart && rm templates/* -fr

vim templates/cm.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  value1: "{{ .Release.IsUpgrade }}"
  value2: "{{ .Release.IsInstall }}"
  value3: "{{ .Release.Revision }}"
  value4: "{{ .Release.Service }}"
helm install moon mychart --debug --dry-run

# 得到如下yaml信息
[root@k8s ~]# helm install moon mychart/ --dry-run
# Source: mychart/templates/cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: moon-cm
  namespace: default
data:
  value1: "false"
  value2: "true"
  value3: "1"
  value4: "Helm"

2. Values内置对象

  • 描述的是 value.yaml 文件的内容,默认是空,使用Values内置对象可以获取该文件中定义的任何变量值
# 先清空value.yaml中内容, 然后添加如下
name: moon
foo:
  name: bar

# 查看value信息
[root@k8s ~]# helm show values mychart/
name: pengdehuai
foo:
  name: bar


# 获取上面两个值  
.Values.name
.Values.foo.name
# 继续沿用上面创建的chart
[root@k8s ~]# cat mychart/templates/cm.yaml 
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  value1: "{{ .Release.IsUpgrade }}"
  value2: "{{ .Release.IsInstall }}"
  value3: "{{ .Release.Revision }}"
  value4: "{{ .Release.Service }}"
  value5: "{{ .Values.name }}"
  value6: "{{ .Values.foo.name }}"

[root@k8s ~]# helm install moon mychart/ --dry-run
# Source: mychart/templates/cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: moon-cm
  namespace: default
data:
  value1: "false"
  value2: "true"
  value3: "1"
  value4: "Helm"
  value5: "pengdehuai"
  value6: "bar"

3. Chart内置对象

  • 用于获取 Chart.yaml 文件中的内容
.Chart.Name					# 获取Chart的名称
.Chart.Version				# 获取Chart的版本
# Chart.yaml内容为
apiVersion: v2
name: mychart
description: A Helm chart for Kubernetes
type: application
version: 0.1.0
appVersion: 1.16.0

# 查看chart
[root@k8s ~]# helm show chart mychart/
apiVersion: v2
appVersion: 1.16.0
description: A Helm chart for Kubernetes
name: mychart
type: application
version: 0.1.0


[root@k8s ~]# helm install moon mychart/ --dry-run
# Source: mychart/templates/cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: moon-cm
  namespace: default
data:
  value1: "mychart"
  value2: "0.1.0"

4. Capabilities内置对象

  • 提供关于kubernertes集群相关信息, 该对象有如下方法
.Capabilities.APIVersions				# 描述k8s的api版本信息
.Capabilities.APIVersions.Has $version	# 用于检查版本或资源在k8s中是否可用, 如apps/v1/Deployment
.Capabilities.KubeVersion和..Capabilities.KubeVersion.Version	# 用于获取k8s的版本号
.Capabilities.KubeVersion.Major			# 获取k8s的主版本号
.Capabilities.KubeVersion.Minor			# 获取k8s的小版本号
[root@k8s ~/mychart]# cat templates/cm.yaml 
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  value1: "{{ .Chart.Name }}"
  value2: "{{ .Chart.Version }}"
  value3: "{{ .Capabilities.APIVersions }}"
  value4: '{{ .Capabilities.APIVersions.Has "apps/v1/Deployment" }}'
  value5: "{{ .Capabilities.KubeVersion }}"
  value5: "{{ .Capabilities.KubeVersion.Major }}"
  value5: "{{ .Capabilities.KubeVersion.Minor }}"

#
# Source: mychart/templates/cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: moon-cm
  namespace: default
data:
  value1: "mychart"
  value2: "0.1.0"
  value3: "[autoscaling/v1/HorizontalPodAutoscaler certificates.k8s.io/v1beta1/CertificateSigningRequest apiextensions.k8s.io/v1beta1/CustomResourceDefinition storage.k8s.io/v1 batch/v1 storage.k8s.io/v1beta1 crd.projectcalico.org/v1 v1/Endpoints v1/Pod authorization.k8s.io/v1/SelfSubjectAccessReview storage.k8s.io/v1/CSINode v1 crd.projectcalico.org/v1/FelixConfiguration v1/ConfigMap v1/Scale policy/v1beta1/PodDisruptionBudget apps/v1 authorization.k8s.io/v1beta1 v1/Node apps/v1/StatefulSet node.k8s.io/v1beta1/RuntimeClass crd.projectcalico.org/v1/GlobalNetworkPolicy apiregistration.k8s.io/v1 v1/ServiceAccount apps/v1/ReplicaSet storage.k8s.io/v1beta1/CSINode v1/Event v1/PodProxyOptions certificates.k8s.io/v1/CertificateSigningRequest coordination.k8s.io/v1beta1/Lease crd.projectcalico.org/v1/BGPPeer v1/ComponentStatus apiregistration.k8s.io/v1beta1/APIService networking.k8s.io/v1beta1/Ingress v1/PodTemplate autoscaling/v2beta1 autoscaling/v1 v1/LimitRange authorization.k8s.io/v1/LocalSubjectAccessReview rbac.authorization.k8s.io/v1beta1/RoleBinding crd.projectcalico.org/v1/IPPool crd.projectcalico.org/v1/GlobalNetworkSet events.k8s.io/v1 storage.k8s.io/v1/StorageClass v1/Namespace policy/v1beta1 v1/NodeProxyOptions batch/v1/Job authorization.k8s.io/v1 node.k8s.io/v1beta1 v1/PodAttachOptions v1/ReplicationController v1/ServiceProxyOptions authentication.k8s.io/v1beta1 v1/PersistentVolume autoscaling/v2beta1/HorizontalPodAutoscaler admissionregistration.k8s.io/v1beta1/ValidatingWebhookConfiguration events.k8s.io/v1beta1 batch/v1beta1 networking.k8s.io/v1/IngressClass rbac.authorization.k8s.io/v1/RoleBinding rbac.authorization.k8s.io/v1/Role coordination.k8s.io/v1/Lease crd.projectcalico.org/v1/NetworkPolicy autoscaling/v2beta2 apiextensions.k8s.io/v1/CustomResourceDefinition storage.k8s.io/v1beta1/StorageClass coordination.k8s.io/v1 v1/PodExecOptions certificates.k8s.io/v1 admissionregistration.k8s.io/v1 v1/PodPortForwardOptions extensions/v1beta1/Ingress rbac.authorization.k8s.io/v1beta1/ClusterRoleBinding rbac.authorization.k8s.io/v1beta1 authorization.k8s.io/v1/SubjectAccessReview rbac.authorization.k8s.io/v1/ClusterRoleBinding rbac.authorization.k8s.io/v1beta1/Role scheduling.k8s.io/v1beta1/PriorityClass v1/PersistentVolumeClaim apps/v1/DaemonSet batch/v1beta1/CronJob storage.k8s.io/v1/VolumeAttachment crd.projectcalico.org/v1/BlockAffinity certificates.k8s.io/v1beta1 crd.projectcalico.org/v1/KubeControllersConfiguration crd.projectcalico.org/v1/BGPConfiguration admissionregistration.k8s.io/v1beta1 events.k8s.io/v1/Event crd.projectcalico.org/v1/IPAMConfig apiextensions.k8s.io/v1beta1 discovery.k8s.io/v1beta1 crd.projectcalico.org/v1/ClusterInformation apiextensions.k8s.io/v1 networking.k8s.io/v1/NetworkPolicy rbac.authorization.k8s.io/v1/ClusterRole crd.projectcalico.org/v1/HostEndpoint apps/v1/Deployment autoscaling/v2beta2/HorizontalPodAutoscaler authorization.k8s.io/v1beta1/SubjectAccessReview v1/Secret authentication.k8s.io/v1/TokenReview authentication.k8s.io/v1beta1/TokenReview networking.k8s.io/v1beta1/IngressClass admissionregistration.k8s.io/v1/MutatingWebhookConfiguration v1/Binding scheduling.k8s.io/v1 v1/ResourceQuota authorization.k8s.io/v1beta1/SelfSubjectRulesReview admissionregistration.k8s.io/v1/ValidatingWebhookConfiguration crd.projectcalico.org/v1/IPAMHandle crd.projectcalico.org/v1/NetworkSet authentication.k8s.io/v1 v1/Eviction v1/Service events.k8s.io/v1beta1/Event authorization.k8s.io/v1/SelfSubjectRulesReview networking.k8s.io/v1/Ingress storage.k8s.io/v1/CSIDriver scheduling.k8s.io/v1/PriorityClass rbac.authorization.k8s.io/v1 scheduling.k8s.io/v1beta1 authorization.k8s.io/v1beta1/LocalSubjectAccessReview discovery.k8s.io/v1beta1/EndpointSlice crd.projectcalico.org/v1/IPAMBlock extensions/v1beta1 networking.k8s.io/v1 apiregistration.k8s.io/v1/APIService apps/v1/ControllerRevision policy/v1beta1/PodSecurityPolicy rbac.authorization.k8s.io/v1beta1/ClusterRole storage.k8s.io/v1beta1/CSIDriver apiregistration.k8s.io/v1beta1 coordination.k8s.io/v1beta1 apps/v1/Scale authorization.k8s.io/v1beta1/SelfSubjectAccessReview storage.k8s.io/v1beta1/VolumeAttachment admissionregistration.k8s.io/v1beta1/MutatingWebhookConfiguration networking.k8s.io/v1beta1]"
  value4: 'true'
  value5: "v1.19.3"
  value5: "1"
  value5: "19"

5. Template内置对象

  • 用于获取当前模板的信息,包含如下两个对象
.Template.Name				# 用于获取当前模板的名称和路径, 如mychart/templates/mytemplate.yaml
.Template.BasePath			# 用于获取当前模板的路径, 如mychart/template
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  value1: "{{ .Template.Name }}"
  value2: "{{ .Template.BasePath }}"



# Source: mychart/templates/cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: moon-cm
  namespace: default
data:
  value1: "mychart/templates/cm.yaml"
  value2: "mychart/templates"

四. 常用命令

helm version
helm create ${chart_name} ${chart_path}			# 通过chart安装一个release包
helm list 							# 列出实例
helm repo list						# 列出仓库
helm history ${release_name}		# 获取release历史
helm upgrade ${release_name}		# 更新一个release实例
helm rollback						# 从之前一个版本
helm show values ${chart_path}		# 查看一个chart的value信息
helm show chart ${chart_path}		# 查看一个chart的chart信息,也就是Chart.yaml中的内容
helm repo add
helm pull test-repo/tomcat --vserion 0.43 --untar	# 从远处仓库拉取指定版本的chart包到本地并解压

1. 小案例

helm create nginx-chart
rm nginx-chart/templates/* -rf
> nginx-chart/values.yaml

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Values.deployment.name }}
spec:
  replicas: {{ .Values.replicas }}
  selector:
    matchLabels:
      app: {{ .Values.pod_label }}
  template:
    metadata:
      labels:
        app: {{ .Values.pod_label }}
    spec:
      containers:
      - image: {{ .Values.image }}:{{ .Values.imageTag }}
        name: {{ .Values.container_name }}
        ports:
        - containerPort: {{ .Values.containerport }}

service.yaml

apiVersion: v1
kind: Service
metadata:
  name: {{ .Values.service_name }}
  namespace: {{ .Values.namespace }}
spec:
  type: NodePort
  ports:
  - port: {{ .Values.port }}
    targetPort: {{ .Values.targetport }}
    nodePort: {{ .Values.nodeport }}
    protocol: TCP
  selector:
    app: {{ .Values.pod_label }}

values.yaml

deployment:
  name:  nginx-deployment
replicas: 2
pod_label: nginx
image: nginx
imageTag: 1.17
container_name: nginx
service_name: nginx-svc
namespace: default
port: 80
targetport: 80
containerport: 80
nodeport: 30001
# 部署
helm install nginx-release nginx-chart/

# 将values.yaml文件中的tag改为1.18然后升级动作
helm upgrade nginx-release nginx-chart/
# 也可以在命令行直接修改变量从而修改yaml, 而不修改values中的内容
helm upgrade nginx-release nginx-chart/ --set imageTag=1.18

# 回滚到上一个版本
helm rollback nginx-release
# 回滚到指定版本, 可以通过helm list查看版本,也就是REVISION的值
helm rollback nginx-release 2

五. helm内置函数

1. helm内置函数

  • quote 或 squote
    • 给获取的变量值加一个双引号, squote加单引号
  • upper 或 lower
    • 给获取的变量值大写, lower改为小写
  • repeat
    • 给获取的值重复输出指定次数
  • default
    • 默认值
  • lookup
    • 用于在当前的k8s集群中获取一些资源信息, 类似于kubectl get xxx
# 函数使用格式
函数名 arg1 arg2
arg1 | 函数名		# 实际使用中更偏向于这种, 这样结构看起来比较直观
# template中的yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  value1: {{ quote .Values.name }}
  value2: {{ squote .Values.name }}

# 用管道的格式
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  value1: {{ .Values.name | quote }}
  value2: {{ .Values.name | squote }}


# 渲染后得到
# Source: mychart/templates/cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: moon-cm
  namespace: default
data:
  value1: "pengdehuai"
  value2: 'pengdehuai'
  • 大小写
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  value1: {{ .Values.name | upper | quote }}
  value2: {{ .Values.name | lower | squote }}


# Source: mychart/templates/cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: moon-cm
  namespace: default
data:
  value1: "PENGDEHUAI"
  value2: 'pengdehuai'
  • 重复输出指定次数
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  value1: {{ .Values.name | repeat 2 | quote }}
  value2: {{ .Values.name | repeat 3 | squote }}


# Source: mychart/templates/cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: moon-cm
  namespace: default
data:
  value1: "pengdehuaipengdehuai"
  value2: 'pengdehuaipengdehuaipengdehuai'
  • 默认值
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  value1: {{ .Values.d1 | default "peng" | quote }}
  value2: {{ .Values.d2 | default "jing" | squote }}
  • lookup格式
lookup "apiVersion" "kind" "namespace" "name"

# 案例, 必须要部署之后才能看到,用dry-run就是空map
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  value2: {{ lookup "v1" "Pod" "kube-system" "" | quote }}	# kebe-system的pod
  value1: {{ lookup "v1" "Namespace" "" "" | quote }}		# 获取所有namespace
  
  
# 可通过helm查看创建的资源
helm get manifest ${chart_name}

2. 流程控制

  • eq
    • 用于判断两个参数是否相等,如果等于则为true, 否则false
  • ne
    • 不等为true, 否则false
  • lt
    • 小于则为true, 否则false
  • le
    • 小于等于
  • gt
    • 大于
  • ge
    • 大于等于
  • and
    • 两个参数只要有一个不为真则为不为真
  • or
    • 两个参数有一个为真则为真
  • not
    • 参数为正常参数且非空, 则为真
  • default
    • 用于设置一个默认值
  • empty
    • 判断给定值是否为空
  • coalesce
    • 扫描一个给定的列表,并返回第一个非空的值
  • ternary
    • 接受2个参数和一个test值,如果test的布尔值为true, 则返回第一个参数,如果test的布尔值为false, 则返回第一个参数
# 案例
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  value1: {{ eq 2 2 }}
  value2: {{ and .Values.name1 .Values.name2 }}

3. 字符串函数

函数名 说明
print, println, printf 打印
trim, trimAll, trimPrefix trimSuffix 去除字符串两边的空格,trimAll移除指定字符,trimPrefix移除指定字符串的前缀
lower, upper, title, untitle 小写,大写,首字母大写,大写的首字母小写
snakecase, camelcase,kebabcase 将驼峰的字符串, 改为下划线的,如 NiHao改为ni_hao,camelcase下划线转为驼峰法,kebabcase将驼峰法转为中划线
swapcase 用内置算法切换字符串大小写
substr 字符串切割,需要指定他的起始位置, 如substr 3 5
trunc 截断字符串 trunc 5
abbrev 使用...来切割字符串,然后保留指定长度, 省略号的长度为3
randAlphaNum, randAlpha, randNumeric, randAscii 都是用于生成加密的随机字符串randAlphaNum, 生成的整数和大小写字母, randAlpha生成大小写字母, randNumeric生成整数, randAscii生成ASCII字符
contains 测试一个字符串中是否包含在另一个字符串中,返回布尔值
hasPrefix,hasSuffix 测试一个字符串是否是指定字符串的前缀或者后缀,返回布尔值
repeat, nospace, initials 重复输出字符串,nospace去掉字符串中的空格,截取字符串每个单词的首字母,并拼接在一起
wrapWith 在指定列数添加内容, wrapWith 4 "HG" "helloworld", 也就是在字符串的第四索引位置后面加上HG字符串
quote, squote 字符串加单引号, 双引号
replace 简单字符串替换
shuffle 对字符串重新排序,基于内部的算法
indent, nindent 用于指定长度缩进字符串,nindent是另开一行然后进行缩进
plural 判断字符串的长度, 如果字符串长度为1则返回第一个参数, 否则就返回第二个参数
输出字符串的长度

4. 类型转换函数和正则表达式函数

函数名 说明
atoi 字符串转为整型
float64 字符串转为float64类型
int 字符串装维int类型
toString 转换为字符串
int64 字符串转为int64
toDecimal 将unit八进制转为int64
toStrings 将列表, 切片或数组转为字符串列表
toJson 将列表, 切片, 数组, 字典或对象转为JSON
toPrettyJson 将列表, 切片, 数组, 字典或对象转换为格式化JSON
toRawJson 将列表, 切片, 数组, 字典或对象转换成JSON(HTML字符不转义)

5. 字典函数

函数名 说明
dict 用于存储key/value键值对, 其中字典的key必须是字符串, value可以是任何类型
get 函数来获取定义字典myDict的值
set 用于向已有的字典中添加新的键值对, 也可以修改原来键值对的值
unset 用于删除字典中的key
Keys 获得字典中的key的值
hasKey 判断字典中是否包含指定的key, 如果包含就返回true, 否则false
pluck 根据一个key在多个字典中时获得所有的匹配的value, 并返回一个value组成的列表, 如果key值在两个字段中都不存在, 则返回一个空列表
merge 用于合并两个或多个字典, 由源字段向目标字典合并, 如果目标字典中已有相同的key, 则忽略源字典中对应的键值对,以目标字典为主
mergeOverwrite, mustMergeOverwrite 也用于合并字典, 但与merge不同的是, 如果目标字典中存在源字典中相同的key, 那么目标字典中的key会被覆盖
values 用于获取一个自定中所有的value值并返回一个列表, 由于字典是无序的, 所以返回的list的内容也是无序的
pick 用于根据指定的字典和key值获取value, 并将key和value组成一个新的字典
deepCopy, mustDeepCopy 都是用于深度拷贝一个字典并返回一个字典
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  {{- $myDict := dict "name1" "value1" "name2" "value2" "name3" "value3" }}
  data1: {{ $myDict}}
  data2: {{ get $myDict "name1" }}
  data3: {{ set $myDict "name4" "value4" }}
  data4: {{ get $myDict "name4" }}
  data5: {{ unset $myDict "name4" }}

6. 列表函数

函数名 说明
list 用于生成一个列表, 传入的参数将会作为列表中的值, 案例: $myList := list 1 2 3 "one" "two" "three"
first 用于获取列表中的第一项, 示例 first $myList
rest 获取列表中除第一项以外的所有内容
last 获取列表中的最后一项
initial 获取列表中除最后一项以外的所有内容, 与rest相反
append 用于在已有的列表中追加一项, 并返回新的列表
prepend 在列表的最前面加入一个新值
concat 将任意数量的列表合并成一个新的列表
reverse 用于反转一个列表, 并返回一个新的列表
uniq 用于去除一个列表中的重复项, 并返回一个新的列表
without 用于过滤掉列表中的指定值,即不要某个值或多个值
has 用于判断一个值是否包含在列表中
compact 用于删除一个列表中的空值, 并返回一个新的列表
slice 用于对列表进行切片, 格式: slice list [n] [m]
until 用于构建一个指定整数范围内的列表, 案例: until 5
untilStep 与until作用类似, 不过可以定义整数的开始和步长, 实例: untilStep 3 9 2 输出3-9之间的数字, 且步长值为2
seq 与linux中seq命令类似, 用于生成指定范围内的整数, 最多可以传递三个参数

7. 循环和作用域

  • range用于循环
# values.yaml
person:
  info:
    name: test
    sex: boy
    address: shenzhen
    age: 18

#
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  address: |-
  {{- range $key, $value := .Values.person.info }}
  {{ $key }}: {{ $value }}
  {{- end }}

# 渲染后
# Source: mychart/templates/cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: moon-cm
  namespace: default
data:
  address: |-
  address: shenzhen
  age: 18
  name: test
  sex: boy
  • with
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  {{ $releasename := .Release.Name }}
  {{ $sex := .Values.people.info.sex }}
  {{- with .Values.people.info }}
  Name: {{ .name }}
  Age: {{ .age }}
  Sex: {{ $sex }}
  

六. 定义模板

1. 子模板定义和调用

  • 使用 define 在主模板中定义子模板, 需要通过调用才能输出, 如果不调用是不会有输出的
# 用define调用子模板, 
{{- define "mychart.labels" }}
  labels:
    author: test
    date: {{ now | htmlDate }}
{{- end }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  {{- template "mychart.labels" }}
data:
  data1: "hello"
  
# 渲染后, 可以看到多了一些字段,labels下面
# Source: mychart/templates/cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: moon-cm
  labels:
    author: test
    date: 2023-01-08
data:
  data1: "hello"
  • define在_helpers.tpl文件中定义子模板, 使用template进行调用子模板
# 在_helpers.tpl文件中定义子模板内容
{{- define "mychart.labels" }}
  labels:
    author: test
    date: {{ now | htmlDate }}
{{- end }}

# template中的yaml, 注意调用的子模板的时候后面有一个点, 也就是要指定位置
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  {{- template "mychart.labels" }}
data:
  data1: "hello"
  
# 渲染后结果和上面的一样

2. 向子模板中传入对象

  • 向子模板中传入对象, 使用template进行调用子模板

values.yaml

person:
  info:
    name: test
    sex: boy
    address: shenzhen
    age: 18

vim _helpers.tpl

{{- define "mychart.labels" }}
  labels:
    Author: {{ .Values.person.info.name }}
    Address: {{ .Values.person.info.address }}
{{- end }}

vim template/cm.yaml

# 调用子模板, 在引用的时候需要指定对象位置信息, 这个点表示在顶层作用域中寻找子模板中指定的对象, 如果不指定直接报错
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  {{- template "mychart.labels" . }}	# 也可以直接在主模板中写, 将点改为 .Values.person.info, 也就是在这个作用域去找子模板, 那么我们_helpers.tpl文件可以直接改为.name和.address
data:
  data1: "hello"

3. include进行调用子模板

  • 向子模板中传入对象, 使用include进行调用子模板, template和include都有引用子模板, 用法一样, template不能被其他函数修饰, include可以, 如果想要在自定义修饰缩进的字符, template因不能被其他函数修饰而报错, include可以被其他函数修饰, 推荐使用include

values.yaml

person:
  info:
    name: test
    sex: boy
    address: shenzhen
    age: 18

_helpers.tpl

{{- define "mychart.labels" }}
Author: {{ .Values.person.info.name }}
Address: {{ .Values.person.info.address }}
{{- end }}

template/cm.yaml

# 如果用template调用, 那么后面的修饰函数,就无法使用, 所以用include
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  labels:
{{- include "mychart.labels" .  | toString | indent 4 }}
data:
{{- include "mychart.labels" . | toString | indent 2 }}

4. get方法获取文件内容

  • 有时候需要我们导入的是一个普通的文件内容而不是模板文件, helm提供了. Files 对象用于访问文件, 其中包含了一些方法用于处理文件中的内容
echo "test message" >> mychart/config/test.txt

values.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
data:
  token1:
{{ .Files.Get "config/test.txt" | b64enc | indent 4 }}
  token2: {{ .Files.Get "config/test.txt" | quote }}
# 渲染后结果
# Source: mychart/templates/cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: moon-cm
data:
  token1:
    dGVzdCBtZXNzYWdlCg==
  token2: "test message\n"

5. Glob

  • 使用 Glob 方法获取文件名和内容
mkdir template/config{1,2}
echo "nginx conf" > config1/nginx.conf
echo "http conf" > config1/httpd.conf
echo "mysql conf" > config2/mysql.conf
# 连个* 表示匹配所有,
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
data:
{{- range $path, $_ := .Files.Glob "**.conf" }}
  path: {{ $path }}
{{- end }}
{{ (.Files.Glob "config1/*").AsConfig | indent 2 }}
{{ (.Files.Glob "config2/*").AsConfig | indent 2 }}
# Source: mychart/templates/cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: moon-cm
data:
  path: config1/httpd.conf
  path: config1/nginx.conf
  path: config2/mysql.conf
  httpd.conf: |
    http conf
  nginx.conf: |
    nginx conf
  mysql.conf: |
    mysql conf

6. lines方法

  • 使用 lines 方法循环遍历并逐行读取文件中的内容
vim mychart/config/test.txt
the line1
the line2
the line3

cm.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
data:
{{- range $index,$line := .Files.Lines "config/test.txt" }}
  {{- if $line }}
  {{ $index }}: {{ $line | quote }}
  {{- end }}
{{- end }}
# 渲染后
# Source: mychart/templates/cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: moon-cm
data:
  0: "the line1"
  1: "the line2"
  2: "the line3"

七. 流控制语句

  • if/else, with, range 语句

1. if/else

values.yaml

Person:
  name: liboqing
  age: 16
  sex: man
  work: IT
ingress:
  enabled: true

cm.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  name: {{ .Values.Person.name | default "test_name" | quote }}
  sex: {{ .Values.Person.sex | upper | quote }}
  
  # 如果ingres.enabled为true, 否则就不配置
  {{- if .Values.ingress.enabled }}
  ingress: "配置ingress..."
  {{- else }}
  ingress: "不配置ingress..."
  {{- end }}
  
  # 传入了一个变量值为IT, 如果与.Values.Person.work获得的值相等那么WORK: IT, 否则WORK: "otter work"
  {{- if eq .Values.Person.work "IT" }}
  WORK: {{ .Values.Person.work | quote }}
  {{- else }}
  WORK: "otter work"
  {{- end }}
NAME: moon
LAST DEPLOYED: Mon Jan  9 21:44:25 2023
NAMESPACE: default
STATUS: pending-install
REVISION: 1
TEST SUITE: None
HOOKS:
MANIFEST:
---
# Source: mychart/templates/cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: moon-cm
  namespace: default
data:
  name: "liboqing"
  sex: "MAN"
  ingress: "配置ingress..."
  WORK: "IT"

2. with

values.yaml

people:
  info:
    name: test
    age: 17
    sex: boy

cm.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  # 正常方式调用values.yaml中的内容
  Name: {{ .Values.people.info.name }}
  Age: {{ .Values.people.info.age }}
  Sex: {{ .Values.people.info.sex }}
  
  # 通过with语句已用变量, 效果和上面是一样的, 用with语句可以将重复的路径写一此就可以, 当然也可以用with语句到.Values.people.info
  {{- with .Values.people }}
  Name: {{ .info.name }}
  Age: {{ .info.age }}
  Sex: {{ .info.sex }}
  {{- end }}
# 渲染后结果
# Source: mychart/templates/cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: moon-cm
  namespace: default
data:
  # 正常方式调用values.yaml中的内容
  Name: test
  Age: 17
  Sex: boy
  
  # 通过with语句已用变量, 效果和上面是一样的, 用with语句可以将重复的路径写一此就可以
  Name: test
  Age: 17
  Sex: boy

3. range

  • 用于提供循环遍历

values.yaml

address:
  - beijing
  - sichuan
  - shanghai

cm.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  address: |-
    {{- range .Values.address }}
    - {{ . | title }}
    {{- end }}
    {{- range tuple "bj" "sh" "guang" }}
    - {{ . | title }}
    {{- end }}
# 渲染后
# Source: mychart/templates/cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: moon-cm
  namespace: default
data:
  address: |-
    - Beijing
    - Sichuan
    - Shanghai
    - Bj
    - Sh
    - Guang

八. 计算函数

1. 四则运算

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  address: |-
    data1: {{ add 1 2 3 | quote }} # 加
    data2: {{ sub 3 2 | quote }}   # 减
    data3: {{ mul 3 2 | quote }}   # 乘
    data4: {{ div 6 3 | quote }}   # 除
    data5: {{ mod 9 2 | quote }}   # 取余
    data6: {{ add1 3 | quote }}    # 给参数 + 1

2. 其他运算函数

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  address: |-
    data1: {{ max 1 2 3 | quote }}              # 取最大数
    data2: {{ min 1 2 3 | quote }}              # 取最小数
    data3: {{ round 3.1415926 3 | quote }}      # 保留小数点多少位
    data4: {{ len "hello" | quote }}            # 计算字符串长度
    data5: {{ floor 123.5555 | quote }}         # 返回小于等于输入值的最大浮点整数
    data6: {{ ceil 123.5555 | quote }}          # 返回大于等于输入值的最小浮点整数

九. 网络, 文件路径,类型检查函数

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  address: |-
    data1: {{ getHostByName "www.baidu.com" | quote }}	# 解析域名
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  address: |-
    data1: {{ base "/tmp/a/a.txt" }} # 返回最后一级目录
    data2: {{ dir "/tmp/a/a.txt" }}  # 去掉最后一级目录
    data3: {{ ext "a.txt" }}         # 返回文件的扩展名
    data4: {{ isAbs "/tmp/a" }}      # 判断文件路径是否为绝对路径
    data5: {{ isAbs "tmp/a" }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-cm
  namespace: {{ .Release.Namespace }}
data:
  address: |-
    data1: {{ kindOf ( list 1 2 3 ) }} # 返回对象类型
    data2: {{ kindIs "string" "hi" }}  # 用于检测某个对象是否是指定的类型, 返回布尔值
    data3: {{ deepEqual ( list 1 2 3 ) ( list 1 2 3 ) }} # 判断两个对象的值是否完全一致
    data4: {{ deepEqual ( list 1 2 3 ) ( list 2 3 4 ) }}

Helm-Kubernetes_第1张图片

你可能感兴趣的:(k8s,kubernetes,docker)