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?
One line:
In yaml:
You can also use
envsubst
when deploying.e.g.
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.
I create a script called
kubectl_create
and use it to run the create command. It will substitute any value in the template that is referenced in an environment variable.For example, if the template file has:
Run
kubectl_create nginx-service.yaml
and then the environment variable PUBLIC_IP will be substituted before running the actual kubectl create command.I create a script called kubectl_apply. It loads variables from .env, replace ${CUSTOMVAR} in yml and pass it to kubectl command
Helm is exactly meant for such things and a lot more. It handle complex set of resource deployment as a group etc.
But if we are still looking for some simple alternative then how about using ant?
If you want to modify the file as part of build process or test process then you can go with ant task as well.
Using ant you can load all environment values as property or you can simply load properties file like:
Then you can have a target which converts template files into your desired yaml file.
Of course you can use a
fileset
instead offile
in case you want to change values dynamically for multiple files (nested or whatever)Your template file
xyz.template.yml
should look like:env.
property being loaded from environment variables and other from property fileHope it helped :)
I have been using kubetpl
It has three different template flavors and supports ConfigMap/Secret freezing.