Docker image templating with Jinja

Why to template

Sometimes there is a need to create Dockerfiles dynamically.
Perhaps it’s necessary as part of your CI/CD flow. So let’s try to create python script which is templating Dockerfile.

What is Jinja

Jinja is templating system widely used for templating HTML pages. Typical use case when we use Jinja is situation we want to create web app and render dynamic html pages with frameworks (like flask).
But nobody said you cannot use Jinja for creating dynamic Dockers or any other text files 🙂

Installation / requirements.txt

Only one non std lib package we just need is jinja2. Of course after you install jinja2 from pypy it will install MarkupSafe as well (because of dependencies).

pip install jinja2

So at the moment of writing this article Jinja2 (August 2019) is at 2.10 version

Jinja2==2.10.1
MarkupSafe==1.1.1

Template

In a template file called Dockerfile_template we will be defining places where we will put content dynamically.

  • Typically each code block is open with “{{” and closed with “}}” inside of brackets you need to put variable name ex. base.
  • In case if we have many elements we need to iterate over using {% for and {% endfor %}
FROM {{ base }}
LABEL maintainer="{{ maintainer }}"

RUN yum install -y  {% for pc in packages %}{{pc}} {% endfor %}

So in our case we will dynamically say

  • what base image to use,
  • who is maintainer of docker file,
  • which additional packages to install in container

How to run script

We need to set couple parameters: base-img, tag, maintainer.
As optional we can specify packages

usage of the script

So lets execute

python create_dockerfile.py --base-img centos -n centos_base -m "Kamil Pazik pazik.kamil@gmail.com" -p tcpdump nmap
execution of the script

The script created Dockerfile

FROM centos
LABEL maintainer="Kamil Pazik pazik.kamil@gmail.com"

RUN yum install -y  tcpdump nmap

Repository

Leave a Reply

Your email address will not be published. Required fields are marked *