Ansible - Generating a file with template multiple loops

Viewed 54

I have these variables:

ddns_domains:
  - domain: domain1.com
    hosts:
      - "@"
      - "cat"
      - "dog"
  - domain: domain2.com
    hosts:
      - "ghost"
      - "ship"
      - "house"
      - "door"
  - domain: domain3.com
    hosts:
      - "@"
      - "desk"

and I want to loop trough them and generate a file like this:

@ domain1.com
cat domain1.com
dog domain1.com
ghost domain2.com
ship domain2.com
house domain2.com
door domain2.com
@ domain3.com
desk domain3.com

I managed to debug them out correctly:

---
- name:
  debug:
    msg: "{{ item.0.domain }} {{ item.1 }}"
  with_subelements:
    - "{{ ddns_domains }}"
    - hosts

But I can't make the template. I keep getting variable not defined error.

Any help is much appreciated. :)

1 Answers

This is the template

shell> cat ddns.txt.j2
{% for i in ddns_domains %}
{% for host in i.hosts %}
{{ host }} {{ i.domain }}
{% endfor %}
{% endfor %}

The task below

    - template:
        src: ddns.txt.j2
        dest: ddns.txt

gives what you want

shell> cat ddns.txt
@ domain1.com
cat domain1.com
dog domain1.com
ghost domain2.com
ship domain2.com
house domain2.com
door domain2.com
@ domain3.com
desk domain3.com
Related