Generating BIND Config From Ansible hostvars

Table of Contents

Since streamlining my container deployment, I’ve been working on automating a BIND deployment. I found this excellent role over at, and I’m tailoring it to my needs.

Generating based on hostvars

For now, I’m statically mapping IPs, MAC addresses, and a few other machine facts in host_vars, so that I have a defined infrastructure, even when the hosts don’t exist.

fqdn: ''
ip_address: ''
mac_address: '52:54:00:76:b4:78'
services: [ 'dns', 'dhcp' ]

This allows me to keep key infrastructure facts in one place. The only problem is his dictionary format uses a key for the hostname, which presents a roadblock. His variables:

    type: A
    last: 11

His templates:

# forward
{% for key, value in records.iteritems() %}
{{ value.last }}   PTR   {{ value.rev }}
{% endfor %}

# reverse
{% for key, value in records.iteritems() %}
{{ key }}   {{ value.type }}   {{ value.forward }}
{% endfor %}

Called like so for the forward domain:

- name: Copy forward file
    src: db.forward.j2
    dest: /etc/named/zones/db.{{ domain }}
    owner: root
    group: named
    mode: 0640
  with_dict: "{{ records }}"
  notify: restart named

The fix

I pull the list of hosts into a variable:

# vars.yml
hostlist: "{{ groups['all'] }}"

And iterate against this list:

# forward
{% for host in hostlist %}
{{ host }}  IN  A  {{ hostvars[host].ip_address }}
{% endfor %}

{% for host in hostlist %}
{{ hostvars[host].ip_address|regex_replace('10.3.3.') }}  IN   PTR   {{ hostvars[host].fqdn }}.
{% endfor %}

And commented out the now non-existent records variable:

#  with_dict: "{{ records }}"


It now iterates through my hosts and pulls the variables I need. I had to make a few more minor edits to his templates. You can see the entire project at my github project