how to pass environment variable in kubectl deployment?

I used envsubst (https://www.gnu.org/software/gettext/manual/html_node/envsubst-Invocation.html) for this. Create a deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: $NAME
  labels:
    app: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80

Then:

export NAME=my-test-nginx
envsubst < deployment.yaml | kubectl apply -f -

Not sure what OS are you using to run this. On macOS, envsubst installed like:

brew install gettext
brew link --force gettext 

This isn't a right way to use the deployment, you can't provide half details in yaml and half in kubectl commands. If you want to pass environment variables in your deployment you should add those detail in the deployment spec.template.spec:

You should add following block to your deployment.yaml

spec:
  containers:
  - env:
    - name: var1
      value: val1

This will export your environment variables inside the container.

The other way to export the environment variable is use kubectl run (not advisable) as it is going to be depreciated very soon. You can use following command:

 kubectl run nginx --image=nginx --restart=Always --replicas=1 --env=var1=val1

The above command will create a deployment nginx with replica 1 and environment variable var1=val1