skip to Main Content

How to pass environment variables to kubectl create deployment command?

I’m trying to pass environment variable to kubectl create deployment command with below syntax

kubectl create deployment  nginx-deployment --replicas=2  --env="HOSTNAME=dev.example.com" --env="KEY=randomkey1456" --env="PORT_NUMBER=5601" --image=nginx

It’s throwing below error message saying --env as an unknown flag

error: unknown flag: --env

Similar syntax is working with below kubectl run command successfully

kubectl run  nginx-deployment --env="HOSTNAME=dev.example.com" --env="KEY=randomkey1456" --env="PORT_NUMBER=5601" --image=nginx

So what’s the right way to pass an environment variable to kubectl create deployment imperative command?

2

Answers


  1. The kubectl create command does not support this. The best you can do is lean on it for generating a resource, patch it, and apply:

    kubectl create deployment nginx-deployment --replicas=2 --image=nginx --dry-run=client -o json | 
    jq '.spec.template.spec.containers[0].env |= [{name: "HOSTNAME", value: "dev.example.com"}]' | 
    kubectl apply -f -
    

    You may want to use jq’s argument processing features to move the arguments out of the jq expression. For example:

    jq '.spec.template.spec.containers[0].env |=
      [$ARGS.positional[] | split("=") | {name: .[0], value: .[1]}]' 
      --args HOSTNAME=dev.example.com
    
    Login or Signup to reply.
  2. kubectl create deployment nginx-deployment --replicas=2 --image=nginx
    
    kubectl set env deployment/nginx-deployment 
      HOSTNAME=dev.example.com 
      KEY=randomkey1456 
      PORT_NUMBER=5601
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search