Jinja2 for Ansible Templates

This (like so much of my blog) is as much a reminder to myself as anything else. I often make an effort to make those notes more readable to others, but this probably doesn't fall into that category.

Having sorted out a systemd service for a project, I needed to implement it as a Jinja2 template in Ansible. This seemed like a good example of exactly that, so I thought I'd post it to the blog.

Variables can be defined anywhere in in the current collection of Ansible scripts and used here. They're contained in {{ and }}. Commands are defined inside {% and %}.

{# /etc/systemd/system/booklist.service #}
{# these are Jinja2 comments: they don't appear in the generated file #}
[Unit]
Description=Run the Book List application
Requires=network.target

[Service]
{# if the process backgrounds itself, "forking", if it foregrounds, "simple" #}
Type=simple
Environment=PATH={{ ansible_env.PATH }}:{{ ruby_bin_folder }}
WorkingDirectory={{ code_folder }}
PIDFile=/var/run/puma.pid
{# Environment=RACK_ENV={{ env }} #}
ExecStart={{ ruby_bin_folder }}/bundle exec {{ ruby_bin_folder }}/puma -b unix:///var/run/{{ app_name }}.sock --pidfile /var/run/puma.pid
ExecStop={{ ruby_bin_folder }}/bundle exec {{ ruby_bin_folder }}/pumactl --pidfile /var/run/puma.pid stop
ExecReload={{ ruby_bin_folder }}/bundle exec {{ ruby_bin_folder }}/pumactl --pidfile /var/run/puma.pid reload
Restart=always
{% set items = [ "BookList", "EventList", "StoryList" ] %}
ExecStartPost={% for item in items %}{{ ruby_bin_folder }}/bundle exec rails runner {{ item }}; {% endfor %}

[Install]
WantedBy=multi-user.target

The lists and loops are very Python-like (Ansible is a Python application), which made it easier for me to work with them. See the systemd service entry for the generated output.

Bibliography