Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set dynamic values with Kubernetes yaml file

For example, a deployment yaml file:

apiVersion: extensions/v1beta1 kind: Deployment metadata:   name: guestbook spec:   replicas: 2   template:     metadata:       labels:         app: guestbook       spec:         container:           - name: guestbook             image: {{Here want to read value from config file outside}} 

There is a ConfigMap feature with Kubernetes, but that's also write the key/value to the yaml file. Is there a way to set the key to environment variables?

like image 495
online Avatar asked Jan 17 '18 07:01

online


People also ask

Where do I put Kubernetes YAML files?

As mentioned above, using the YAML field allows you to declaratively manage your Kubernetes applications. These YAML files can be stored in a common directory and may all be applied using kubectl apply -f <directory>. This is fairly simple.

How do I edit pod YAML file?

You can edit pod yaml on the fly using kubectl edit pods <pod-name> . You have to keep in mind that there are fields which will not be allowed to be edited while pod is scheduled, this is mentioned in your error message. I think you should first remove the pod and apply the new yaml file.

What is the purpose of PodSpec YAML file?

A PodSpec defines the containers, environment variables for the container and other properties such as the scheduler name, security context etc.


Video Answer


2 Answers

You can also use envsubst when deploying.

e.g.

cat $app/deployment.yaml | envsubst | kubectl apply ... 

It will replace all variables in the file with their values. We are successfully using this approach on our CI when deploying to multiple environments, also to inject the CI_TAG etc into the deployments.

like image 90
Marek Urbanowicz Avatar answered Sep 20 '22 15:09

Marek Urbanowicz


You can't do it automatically, you need to use an external script to "compile" your template, or use helm as suggested by @Jakub.

You may want to use a custom bash script, maybe integrated with your CI pipeline.

Given a template yml file called deploy.yml.template very similar to the one you provided, you can use something like this:

#!/bin/bash  # sample value for your variables MYVARVALUE="nginx:latest"  # read the yml template from a file and substitute the string  # {{MYVARNAME}} with the value of the MYVARVALUE variable template=`cat "deploy.yml.template" | sed "s/{{MYVARNAME}}/$MYVARVALUE/g"`  # apply the yml with the substituted value echo "$template" | kubectl apply -f - 
like image 37
whites11 Avatar answered Sep 16 '22 15:09

whites11