pass environment variable when use `kubectl apply -f file.yaml`

7/25/2019

Can I pass environment variable when use kubectl apply -f file.yaml like kubectl apply -f file.yaml -env HOST=dev.api.host.com?

Because I have a file yaml, and I need to run in two pipelines, in one case to use host for production and in another case to use host for developlemnt.

I don't want to use two different files, I want to use one file, where I'll replace the host.

Is it possible?

-- Rui Martins
kubernetes

3 Answers

7/25/2019

I'd recommend a different solution:

In Kubernetes you can use ConfigMaps and Secrets to store your configuration.

There are multiple ways how to do it. You could for example split development and production in 2 namespaces, if they should run in one cluster. Then you can put a ConfigMap with your host configuration in each namespace. When you deploy the same deployment to different namespaces, they'll find their appropriate ConfigMap and load it.


If you want to go the way of replacing it, a simple search-and-replace in your file would work.

In your file.yml specify an environment variable like this

    env:
    - name: HOST
      value: %%HOST%%

And in your pipeline replace it with the appropriate value

sed -i -e "s#%%HOST%%#http://whatever#" file.yml;
-- Pampy
Source: StackOverflow

7/25/2019

This is how you should update environment variables in deployment yaml.

export TAG="1.11.1"
export NAME=my-nginx
envsubst < deployment.yaml | kubectl apply -f -
-- P Ekambaram
Source: StackOverflow

7/25/2019

kubectl does not provide any such facility to pass environment variables on the fly. Like @Pampy mentioned, other way would be by using ConfigMaps and Secrets. In case you are going to use same resource specs in two different environments, I would suggest to go with Helm. Helm provides an easy way to package Kubernetes resource yamls in an efficient way. It consists of values.yaml which can be used separately depending on the environment you are planning to use. If still you want to insert values on the fly then, check this kubectl cheat sheet

-- Tyto
Source: StackOverflow