Search code examples
kuberneteskubernetes-helm

helm chart always not going into the if condition


yaml file and in that below values are defined including one specific value called "environment"

image:
 repository: my_repo_url
 tag: my_tag
 pullPolicy: IfNotPresent

releaseName: cron_script
schedule: "0 10 * * *"
namespace: deploy_cron
rav_admin_password: asdf
environment: testing
testing_forwarder_ip: 10.2.71.21
prod_us_forwarder_ip: 10.2.71.15

Now in my helm chart based on this environment value i need to assign a value to new variable and for that I have written code like below, but always it is not entering into the if else block itself

{{- $fwip := .Values.prod_us_forwarder_ip }}
  {{- if contains .Values.environment  "testing" }}
    {{- $fwip := .Values.testing_forwarder_ip }}
{{- end }}
---
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: "{{ .Values.releaseName }}"
  namespace: "{{ .Values.namespace }}"
  labels:
  ....................................
  ....................................
  ....................................
  spec:
      restartPolicy: Never
      containers:
      - name: "{{ .Values.releaseName }}"
        image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
        imagePullPolicy: IfNotPresent
        args:
          - python3
          - test.py
          - --data
          - 100
          - {{ $fwip }}

In the above code always i get $fwip value as 10.2.71.21 what ever environment value is either testing or production for both i am getting same value

And if i don't declare the variable $fwip before the if else statement then it says $fwip variable is not defined error, So i am not sure why exactly if else statement is not getting used at all, How to debug further ?


Solution

  • This is a syntax problem of variables and local variables.

    The fwip in if should use = instead of :=

    {{- $fwip := .Values.prod_us_forwarder_ip }}
    {{- if contains .Values.environment  "testing" }}
      {{- $fwip = .Values.testing_forwarder_ip }}
    {{- end }}
    

    I translated it into go code to make it easier for you to understand.

    (In the go language, := means definition and assignment, = means assignment)

    // := 
    env := "testing"
    test := "10.2.71.21"
    prod := "10.2.71.15"
    
    fwip := prod
    if strings.Contains(env,"testing"){
        fwip := test
        fmt.Println(fwip) // 10.2.71.21
    }
    fmt.Println(fwip) // 10.2.71.15
    
    // =
    env := "testing"
    test := "10.2.71.21"
    prod := "10.2.71.15"
    
    fwip := prod
    if strings.Contains(env,"testing"){
        fwip = test
        fmt.Println(fwip) // 10.2.71.21
    }
    fmt.Println(fwip) // 10.2.71.21