Search code examples
bashkuberneteskubectlenvsubst

Substitute environment variable in all files when kubectl apply-ing


Let's say we have a number of Kubernetes configuration files in a folder kubernetes and we want to apply them all:

kubectl apply -f kubernetes -n MyNamespace

Some of these files contain environment variables which need to be substituted first (no templating in Kubernetes). For instance, several of the deployment yamls contain something like:

image: myregistry.com/myrepo:$TAG

For a single yaml file, this can be done e.g. by using envsubst like this:

envsubst < deploy.yml | kubectl apply -f -

What's the best way to do these substitutions for all the yaml files?

(Looping over the files in the folder and calling envsubst as above is one option, but I suspect that it would be preferrable to pass the entire folder to kubectl and not individual files)


Solution

  • This works:

    for f in *.yaml; do envsubst < $f | kubectl apply -f -; done