Apr
08
2015
ansible Jinja2 template example with for loop

Disclaimer: This blog post has one purpose only: be a proof of concept - not the “perfect” ansible playbook.

When managing a server farm, you will -soon enough- start using Jinja templates. Cause -let’s face it- static files are very easy to copy through servers but with templates, you are making magic!

This ansible example will create a bind-format slave zones configuration file.

You need to have in mind, the typical structure of that configuration file:



zone "balaskas.gr" {
    type slave;
    file "sec/balaskas.gr";
    masters {
        158.255.214.14;
    };
};

Let’s start with the actual data. I like to keep my configuration separated from my playbooks. With this approach is easy to re-use your variables in other playbooks.

So my variable list is looking like this:

zones.yml


---
zones:
  - { zone: 'balaskas.gr', master: '158.255.214.14', extras: '' }
  - { zone: 'example.com', master: '1.2.3.4', extras: '' }

My slavezone yml ansible playbook is very similar to this:

SecondaryDNS.yml


SecondaryDNS.yml

---

- hosts: myslavens
  gather_facts: no
  user: root

  vars_files:
    - [ "files/SecondaryDNS/zones.yml" ]

  tasks:
  - name: Create named.slavezone
    template:
      src="files/SecondaryDNS/slavezones.j2"
      dest="/etc/named.slavezones"
      owner=named
      group=named
      mode=0440

...

(This is not the entire playbook, but I am guessing you get the point)

To recap, we want to create a [new (if not exist)] file, with a very specific output for every line in our configuration.
So here is my Jinja2 template file:

slavezones.j2



{% for item in zones %}
zone "{{item.zone}}" { type slave; file "sec/{{item.zone}}"; masters { {{item.master}}; }; {{item.extra}} };
{% endfor %}

This template will loop for every line (item) of our zones.yml and create the desirable output.

And that’s how you can create ansible magic !

Tag(s): ansible

Add comment

Fill out the form below to add your own comments