JinjaCompose

Docker compose with magic ✨

PythonpipDocker

jinja-compose is a tool for running docker-compose commands with Jinja2 templating.

Usage

Jinja Compose operates using the same syntax as docker-compose, but with the addition of a template and optional injection file. The typical project setup looks like this:

/project_dir
├── compose.jyml
├── compose.py
└── compose.yaml  [generated by jinja-compose]

Where compose.jyml is a Jinja2 template file, compose.py is an optional Python file containing variables to be injected into the template, and compose.yaml is the generated docker-compose file.

Example

In compose.jyml we define a service called server, which only runs in production when the is_production variable is defined and only forwards ports on a certain host.

services:
  server:
    build:
      context: .
    image: sid220/apriltag_localisation:latest
    environment:
      - DAPRILTAG_PRODUCTION={{ MyJinjaComposeInjection.is_production }}
      - OPENCV_VIDEOIO_DEBUG=1
    {% if MyJinjaComposeInjection.my_static_method() == 'special_host' %}
    ports:
        - "5000:5000"
    {% endif %}

To define the is_production variable and my_static_method method, we create a compose.py file with a class that inherits from JinjaComposeInject.

from jinja_compose_wrapper.libjinja_compose import JinjaComposeInject
import socket
 
class MyJinjaComposeInjection(JinjaComposeInject):
    is_production = 1
 
    @staticmethod
    def my_static_method():
        return socket.gethostname()

Once done we can now bring this service up:

jinja_compose up

Or just build the yaml file:

jinja_compose -d echo