ansible logo

Ansible is a fantastic technology that allows you to deploy and manage servers easily and in a repeatable fashion. One thing that can be tricky is using templates to create complex configuration files. In this example, I'll demonstrate how to use nested variables to create a sample Sanoid config file:

 1# Ansible managed: DO NOT EDIT BY HAND
 2
 3[myzpool/mydataset1]
 4       use_template = production
 5
 6[myzpool/mydataset2]
 7       use_template = production
 8       hourly = 6
 9
10
11#############################
12# templates below this line #
13#############################
14
15[template_production]
16       hourly = 0
17       daily = 30
18       monthly = 12

We first create a list variable for the dataset section and then another for the template sections. Then, populate these variables with a list item for each dataset and template respectively. Then for each list item, you can define multiple values in the list using a dictionary, and even nest lists inside dictionary items (like shown here with the config dictionary item):

 1sanoid_datasets:
 2 - name: "myzpool/mydataset1"
 3   config:
 4    - "use_template = production"
 5 - name: "myzpool/mydataset2"
 6   config:
 7    - "use_template = production"
 8    - "hourly = 6"
 9
10sanoid_templates:
11 - name: "production"
12   config:
13    - "hourly = 0"
14    - "daily = 30"
15    - "monthly = 12"

For more information on variables, see the Ansible documentation. Now, create the template file that will iterate through each dataset, creating each with its own name and settings and then repeat the process for each template:

 1# {{ ansible_managed }}
 2
 3{% for dataset in sanoid_datasets %}
 4[{{ dataset.name }}]
 5{% for item in dataset.config %}
 6        {{ item }}
 7{% endfor %}
 8
 9{% endfor %}
10
11#############################
12# templates below this line #
13#############################
14
15{% for template in sanoid_templates %}
16[template_{{ template.name }}]
17{% for item in template.config %}
18        {{ item }}
19{% endfor %}
20
21{% endfor %}

The result is an easy-to-read vars file that you can easily modify values in without needing to remember the structure of the config file - the template figures it out for you.


Support Us

If you found this article helpful, please support us on Patreon and get access to bonus features!

Questions? Comments?

Do you have questions or comments about this article? If so, please contact us; we'd like to hear from you!