Skip to content

Linux bind9 dns server example

This example configures a bind9 dns server on Linux hosts. The first host in the inventory is the master dns server. All other hosts are configured as slave dns servers. It adds all host from the inventory as dns entries.

- name: configure dns server
  hosts: dns
  gather_facts: false
  tasks:

  - name: apt | install bind9
    apt: 
      name: bind9
      state: present

  - name: template | dns database file
    template:
      src: files/dns/db.empty.j2
      dest: /etc/bind/db.comp
    when: inventory_hostname == groups['dns'][0]
    register: dnsdb

  - name: template | dns config file
    template:
      src: files/dns/named.conf.local.j2
      dest: /etc/bind/named.conf.local
    register: dnsconf

  - name: service | restart dns server
    service:
      name: bind9
      state: restarted
    when: dnsconf.changed or dnsdb.changed
all:
hosts:
    LIN1:
        ansible_host: 10.0.0.1
        hostname: "COMP-LINUXHOST-001"
    LIN2:
        ansible_host: 10.0.0.2
        hostname: "COMP-LINUXHOST-002"
    LIN3:
        ansible_host: 10.0.0.3
        hostname: "COMP-LINUXHOST-003"
children:
    dns:
        hosts:
            LIN1:
            LIN2:
            LIN3:
;
; Generated by ansible 
;

$TTL    86400
@   IN  SOA localhost. root.localhost. (
                1       ; Serial
            604800      ; Refresh
            86400       ; Retry
            2419200     ; Expire
            86400 ) ; Negative Cache TTL

@   IN  NS  localhost.

;ansible host records
{% for host in groups['all'] %}
{{ hostvars[host]['hostname'] }} IN A {{ hostvars[host]['ansible_host'] }}
{% endfor %}

;static records
api         IN  A   10.0.0.10
intranet    IN  A   10.0.0.11
zone "comp.com" {
{% if inventory_hostname in hostvars[groups['dns'][0]]['inventory_hostname'] %}
type master;
file "/etc/bind/db.comp";
allow-transfer { any; };
{% else %}
type slave;
masters { {{ hostvars[groups['dns'][0]]['ansible_host'] }}; };
{% endif %}
};