There is couple of things wrong here.
- You are using
list
notation for dict
([ type: A, name: mike, ip: 192.168.1.10 ]
should be { type: A, name: mike, ip: 192.168.1.10 }
)
- Your data structure requires two loops which you cannot do directly in the playbook.
- You probably also want to have the freedom to remove records when they are not needed which doesn't work just like that when using
lineinfile
.
The following solution fixes all the above problems:
# main.yaml
---
- hosts: all
gather_facts: no
connection: local
vars:
zones:
zone.name1:
- { type: A, name: mike, ip: 192.168.1.10 }
# Remove this record
- { type: A, name: bob, ip: 192.168.1.11, state: absent }
zone.name2:
- { type: A, name: alice, ip: 192.168.1.12 }
- { type: A, name: joanne, ip: 192.168.1.13 }
tasks:
- include_tasks: lines.yaml
loop: "{{ zones | dict2items }}"
loop_control:
loop_var: records
Another task file which we loop through:
# lines.yaml
---
- lineinfile:
path: /tmp/{{ records.key }}.zone
line: >-
@ IN "{{ item.type }}" "{{ item.name }}" "{{ item.ip }}"
regexp: >-
^@\s+IN\s+"{{ item.type }}"\s+"{{ item.name }}"\s+"{{ item.ip }}"$
state: >-
{{ 'present' if 'state' not in item or item.state == 'present' else 'absent' }}
loop: "{{ records.value }}"
Execute it with this command:
ansible-playbook -i localhost, --diff main.yaml