Adding A records with Ansible

I have two raspberry pis that I use as DNS servers for my home network. The pis run dnsmasq and allow me to create custom internal records.

In order to add a new DNS entry for my internal network I simply add a record to pi-53 and pi-153’s /etc/hosts file. When other devices on my network query either pi for a name, pi-53/153 query their local hosts file first (for internal names) and then query Cloudflare for any external names.

Due to the repetive nature of this adding DNS entries I decided this would be a great place to add some automation to my network. The steps I would need to automate were as follows:

  1. Log into pi-53
  2. Add entry to /etc/hosts file
  3. Restart dnsmasq
  4. Repeat steps 1-3 for pi-153

Ansible provided a simple way for me to complete these tasks. My playbook is composed of two prompts followed by two tasks. Below is the playbook:

---

- hosts: pi-53,pi-153
  vars_prompt:
    - name: IP
      prompt: What IP address would you like added?
      private: no
    - name: HOSTNAME
      prompt: What Hostname would you like added
      private: no


  tasks:
  
  - name: Append DNS entry based off input variables
    lineinfile:
      path: "/etc/hosts"
      line: "{{ IP }} {{ HOSTNAME }} #Added by Ansible"
    become: yes

  - name: Restart dnsmasq
    ansible.builtin.systemd:
      state: restarted
      daemon_reload: yes
      name: dnsmasq
    become: yes

And the playbook in action:


While this was a simple task to manually complete, I found myself frustrated when I needed to quickly add a new A record on my network. Prior to creating this playbook I would have to log into two seperate devices and run the exact same commands. This simple problem helped me introduce a simple ansible solution into my network.