# Conditionals in Helm

In 
Published 2022-12-03

This tutorial explains how we can use conditionals in Helm Charts.

Let's create another namespace in our Kubernetes cluster:

kubectl create namespace my-namespace-25

From the Create a Chart in Helm tutorial, we modify the values.yaml, deployment.yaml and service.yaml files to be like below:

values.yaml
replicaCount: 4

service:
  type: NodePort
  nodePort: 30003

app:
  label: "app1"
  environment: "prod"
deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-first-deploy
spec:
  replicas: {{.Values.replicaCount}}
  selector:
    matchLabels:
      app: {{.Values.app.label}}
      {{ if eq .Values.app.environment "prod"}}
      env: {{.Values.app.environment}} {{- else }}
      env: "dev" {{- end }}
  minReadySeconds: 10
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1
      maxSurge: 1
  template:
    metadata:
      labels:
        app: {{.Values.app.label}}
        {{ if eq .Values.app.environment "prod"}}
        env: {{.Values.app.environment}} {{- else }}
        env: "dev" {{- end }}
    spec:
      containers:
      - name: app1-pod
        image: nginx:1.14.2
        ports:
        - containerPort: 8080
service.yaml
kind: Service 
apiVersion: v1 
metadata:
  name: http-server-service 
spec:
  type: {{.Values.service.type}}
  selector:
    app: {{.Values.app.label}}
    {{ if eq .Values.app.environment "prod"}}
    env: {{.Values.app.environment}} {{- else }}
    env: "dev" {{- end }}
  ports:
    - nodePort: {{.Values.service.nodePort}}
      port: 8080 
      targetPort: 80

Now we can deploy the chart in my-namespace-25 namespace :

helm instal my-cond-chart --namespace=my-namespace-25 ./

We can also check the pods in my-namespace-25 namespace:

kubectl get pods --show-labels --namespace=my-namespace-25

NAME                               READY   STATUS    RESTARTS   AGE    LABELS
my-first-deploy-86dc448c4b-5phzt   1/1     Running   0          3m3s   app=app1,env=prod,pod-template-hash=86dc448c4b
my-first-deploy-86dc448c4b-6d62m   1/1     Running   0          3m3s   app=app1,env=prod,pod-template-hash=86dc448c4b
my-first-deploy-86dc448c4b-ltd7v   1/1     Running   0          3m3s   app=app1,env=prod,pod-template-hash=86dc448c4b
my-first-deploy-86dc448c4b-qqpwv   1/1     Running   0          3m3s   app=app1,env=prod,pod-template-hash=86dc448c4b

This is the conditional used in defining the template:

{{ if eq .Values.app.environment "prod"}}
env: {{.Values.app.environment}} {{- else }}
env: "dev" {{- end }}

If app.environment from values.yaml file is "prod", the label will be env: "prod", if not the label will be env: "dev".