Kubernates pass env variable to “kubectl create”

2019-07-10 03:31发布

问题:

I need to pass dynamic env variable to kubectl create. Something like this

kubectl create -f app.yaml --Target=prod

Based on Target code deploys on different servers.

回答1:

You can achieve this in two ways:

  1. Use Helm. It is a "package manager" for Kubernetes and is built exactly for your use case (dynamic variables to configure behaviour of your resources). If it is only a single variable, "converting" your deployment is as simple as creating a new Helm chart, copy your files into templates/, modify values.yaml and use {{ .Values.target }} in your templates. See the quickstart guide for a more in-depth introduction to Helm.

  2. If you consider Helm to be over the top for a single variable, use kubectl's capability to read from standard input. You'll need an additional templating tool (for example mustache). Rewrite your deployment to fit your templating tool. Create a dynamic data.yml in your deployment process (e.g. a simple bash script that reads from environment variables) and run something like mustache data.yml deployment.mustache | kubectl apply -f -.



回答2:

If you want to avoid installing 3rd party plugin then you can replace the text using sed "s/orginal/change/". It worked. I used this in Jenkins shell.

cat app.yaml | sed "s/l3-apps/l2-apps/" | kubectl create -f -



回答3:

kubectl config set-context allows you to configure cluster, namespace, user credentials and more and save it as a "context" in your ~/.kube/config.

The you can use --context option of kubectl exactly in a way that you used --Target in your example.