Templating your Kubernetes files

Imagine that everytime you git push to a repository, your Jenkins pipeline creates a Docker image tagged with the commit hash that triggered the build. How can you tell Kubernetes to deploy that image if the YAML files are static?

image: https://my-registry.com/my-image:latest

That’s the main problem we faced the other day and a lot of solutions came to our way. First thing I must say, thanks to the Stack Overflow community and most of all my invaluable mates at adidas!


First solution: Using Helm as a wrapper for Kubernetes files, turning them to templates. We didn’t choose this option because:

  • Helm is a complex tool. This means learning a whole new tool besides learning Kubernetes. Too much stuff for only deploying a custom image.
  • Helm is more than templating. We didn’t want to kill flies with cannons.
  • We’re tired of wrappers. We wanted to use the standards, because using wrappers means relying on the team that supports it. It’s like duplicating the risk of getting obsolete…


sed is an standard shell command. Everyone knows to use it, every Jenkins slave can use it, it’s portable and a huge community supporting it (the whole Linux community, I mean).

So, we created a placeholder for the templates: ${WHATEVER}. Given a YAML file, we put this:

image: https://my-registry.com/my-image:${IMAGE_TAG}

Then, we create a dummy function in our Jenkins library (or in the Jenkinsfile, whatever):

def kubeSubst(placeholder, value, file) {
sh "sed -i.bak s/:\\\${$placeholder}/:$value/g $file.yml"

This will replace the placeholder with the desired value. And of course only the copied file in the Jenkins workspace is modified. Pretty straightforward solution, isn’t it?

With this kind of stupid method we can parametrize almost every field in our Kubernetes files, without needing to install anything else nor reading documentation for extra tools.

kubeSubst('IMAGE_TAG', '88c2058f564', '/deployments/my-deployment')

Again, thanks to my mates! And thank you for reading, hope this helps you in some way.