A simple Ansible playbook for updating multiple Pihole DNS

I wrote a very simple little playbook for updating my local DNS records for my piholes. For me it’s easier than manually ssh’ing onto each node and editing a file and restarting the service. Here’s the playbook:


#!/usr/bin/env ansible-playbook

- hosts: ns-01, ns-02
gather_facts: yes
sudo: yes
- name: TASK | Copy dnsmasq config for cbnet
template: src=templates/02-localnet.conf.j2 dest=/etc/dnsmasq.d/02-localnet.conf force=yes
- name: TASK | Copy updated dns file
template: src=templates/localnet.list.j2 dest=/etc/pihole/localnet.list force=yes
- name: TASK | Restart dnsmasq
name: dnsmasq
state: restarted

This playbook adds a DNSmasq config file for my local network and copies a template file (dnsmasq include file for my local network) and restarts DNSmasq. Here is the template (sample):


# Chris Local Network
# Gateway pfsense-01
# Static DHCP Reservations gitlab-ce-01 dockerhost-01 nextcloud-01 elk-01 checkmk-01 homeassistant-01 ns-01 ns-02
# DHCP Range - 5 - 25 cbguest-05 cbguest-19
# VPN Reservations vpn-01 vpn-02
# Split DNS Entries www.chrisbergeron.com www.chrisbergeron.com chrisbergeron.com chrisbergeron.com

The DNSmasq config file

### templates02-localnet.conf.j2

# Local network dnsmasq config

You’ll also need an Ansible hosts file with entries for your piholes. Here’s a sample:
checkmk-01 ansible_ssh_host=checkmk-01 ansible_ssh_user=cbergeron ansible_ssh_pass="" host_key_checking=false
db-01 ansible_ssh_host=db-01 ansible_ssh_user=cbergeron ansible_ssh_pass="" host_key_checking=false
dockerhost-01 ansible_ssh_host=dockerhost-01 ansible_ssh_user=cbergeron ansible_ssh_pass="" host_key_checking=false
ns-01 ansible_ssh_host=ns-01 ansible_ssh_user=cbergeron ansible_ssh_pass="" host_key_checking=false
ns-02 ansible_ssh_host=ns-02 ansible_ssh_user=cbergeron ansible_ssh_pass="" host_key_checking=false

### Running the playbook
To update my local DNS, I just edit the templates/localnet.conf.j2 Jinja2 YAML file. I then run the playbook like so:

ansible-playbook update_dns.yml -e @vault/vault.yml --vault-password-file ~/.somefile.password.txt

I get the following output when it’s complete:

PLAY [ns-01, ns-02]
TASK [Gathering Facts]
ok: [ns-02]
ok: [ns-01]

TASK [TASK | Copy dnsmasq config for cbnet]
ok: [ns-02]
ok: [ns-01]

TASK [TASK | Copy updated dns file]
changed: [ns-02]
changed: [ns-01]

TASK [TASK | Restart dnsmasq]
changed: [ns-02]
changed: [ns-01]

ns-01 : ok=4 changed=2 unreachable=0 failed=0
ns-02 : ok=4 changed=2 unreachable=0 failed=0

real 0m14.294s
user 0m2.977s
sys 0m1.437s

It takes 15 seconds to run this on 1 Pihole as a VM and 1 Pihole on a Raspberry Pi.

Technology Used: