Helm 在values配置存在时 default函数 依然生效 的原因及解决

文章目录

问题

在一些特殊的场景,对于pod的更新有时会通过helm upgrade 将replicas从1->0->1变化,但是当replicas 模板设置了default函数时,replicas会出现非预期的变化。

如下 helm 模板中

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {
    
    {
    
     include "example.fullname" . }}
  labels:
    {
    
    {
    
    - include "example.labels" . | nindent 4 }}
spec:
  replicas: {
    
    {
    
     default 1 .Values.replicaCount }}
  selector:
    matchLabels:
      {
    
    {
    
    - include "example.selectorLabels" . | nindent 6 }}
  template:

将values.yaml的replicaCount设置为0时,并不会将replicas置为0,而是使用默认值1

helm template -s templates/deployment.yaml .
....
spec:
  replicas: 1

原因

default函数用于设置空值时的默认值,上述错误的原因源于 default 函数对 空值的定义
空值取决于以下类型:

  • 整型: 0
  • 字符串: “”
  • 列表: []
  • 字典: {}
  • 布尔: false
  • 以及所有的nil (或 null)

因此当values.yaml中将replicaCount为0,整型为0时等于空值,即使用default函数设置的值(1)

解决

使用 kindIs 函数

spec:
  {
    
    {
    
    - if kindIs "invalid" .Values.replicaCount}}
  replicas: 1
  {
    
    {
    
    - else }}
  replicas: {
    
    {
    
     .Values.replicaCount }}
  {
    
    {
    
    - end }}
  selector:
    matchLabels:
      {
    
    {
    
    - include "example.selectorLabels" . | nindent 6 }}

效果展示

$ helm template -s templates/deployment_kindis.yaml .
...
spec:
  replicas: 0
  selector:

kindIs "invalid"可以用于判断是否为 nil(values.yaml未设置)

PS: 此处使用replicas作为示例 略有牵强,请见谅

reference

猜你喜欢

转载自blog.csdn.net/moluzhui/article/details/131876818