/ Yet another SRE (and other fun tech) blog / blog

Auto Generating INI config files via Ansible

July 20, 2020

Auto-generating configuration files in the INI format is easily accomplished via a Jinja2 for loop.

It is a prerequisite that variables are organized in a list of dicts, so that they are iterable (in general, as it is a very effective way of dealing with variables).

In this list, the dash - must include the filename, and further options the configuration.

For example, in your vars/main.yml:

sshd_config:
  - filename: '/etc/ssh/sshd_conf'
    Ciphers: 'aes128-ctr,aes192-ctr,aes256-ctr'
    LogLevel: 'verbose'
    PermitRootLogin: 'prohibit-password'
  - filename: '/etc/ssh/another_config'
    LogLevel: 'debug'
    PermitRootLogin: 'prohibit-password'
    AllowTcpForwarding: 'no'
    PermitTunnel: 'no'

Then some Jinja2 magic:

{% for file in sshd_config %}
  {% for key in file if file['filename'] == file.filename %}
    {% if key not in 'filename' %}
{{ key }} {{ file[key] }}
    {% endif %} 
  {% endfor %}
{% endfor %}

From there, it is easy to template out any configuration file using Ansible’s template module.

In tasks/main.yml:

- name: Create configuration files
  template:
    src: 'templates/config_file.j2'
    dest: "{{ item.filename }}"