0

is there a way to use variables to set fields like name, labels, hostname in a Kubernetes yaml deployment for kubectl command ?

Like a .env file with docker-compose allows to use variables to define image, port, volumes... Or the values.yaml for Helm installs.

For example :

deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: $deploy_name
spec:
  selector:
    matchLabels:
      app: $app
      customer: $customer
      env: $env

kube.env

deploy_name=prod-app
app=mysql
customer=customer1
env=prod

kubectl command :

kubectl apply -f deployment.yaml --values kube.env

I only found a way to set env variables for containers but not for the rest of the yaml deployment.

JRU
  • 1
  • 2
  • 3
    Have you checked this [topic](https://stackoverflow.com/questions/65705619/substitute-environment-variable-in-all-files-when-kubectl-apply-ing) ? – Vins Mar 10 '23 at 22:35

1 Answers1

0

According to me their is not way to set dynamic variable mechanism in deployment. but you can achieve this by two way
1 ) (Recommended and Easy to use) Using Helm ( Helm allows you set all the value in one place )
You can always refer the doc : https://helm.sh
2 ) Using Script

   #!/bin/sh

   # load the env variable
   if [ ! -f kube.env ]
   then
    export $(cat kube.env | xargs)
   fi


   # create the deployment and set exported variable 
   kubectl apply -f - << EOF
   apiVersion: apps/v1
   kind: Deployment
   metadata:
   name: ${deploy_name}
   .
   .
   .
   EOF