Categories
Ansible Debian Linux

Efficient DNS Management for Debian Servers

Prerequisites

Ansible Installed: Ensure Ansible is installed on your control machine. If not, you can install it using pip:

pip install ansible

Inventory File: Have an inventory file that lists your Debian hosts. For example, create a file named inventory with the following content:

[debian_servers] host1 ansible_host=hostname_or_ip host2 ansible_host=hostname_or_ip ...

SSH Access: Ensure you have SSH access to the Debian hosts from your control machine.

Step 1: Create the Playbook

Create a YAML file for your Ansible playbook, e.g., set_dns.yml. This playbook will configure DNS servers using resolvconf.

---
- name: Configure DNS servers using resolvconf on Debian hosts
  hosts: debian_servers
  become: yes
  tasks:
    - name: Install resolvconf if not installed
      apt:
        name: resolvconf
        state: present

    - name: Set DNS nameservers
      copy:
        dest: /etc/resolvconf/resolv.conf.d/head
        content: |
          nameserver 8.8.8.8
          nameserver 8.8.4.4
      notify:
        - reload resolvconf

  handlers:
    - name: reload resolvconf
      command: resolvconf -u

Explanation

  1. Install resolvconf: This task ensures that resolvconf is installed on the host. If it’s already installed, this task will do nothing.
  2. Set DNS nameservers: This task writes the specified nameservers to /etc/resolvconf/resolv.conf.d/head. The notify directive triggers the handler to reload resolvconf.
  3. Reload resolvconf: This handler runs resolvconf -u to update the DNS configuration.

Step 2: Run the Playbook

Open your terminal and navigate to the directory containing your playbook and inventory file. Then, run the following command:

ansible-playbook -i inventory set_dns.yml

This command will execute the playbook on all hosts listed in the [debian_servers] group of your inventory file.

Additional Customization

  • Different Nameservers: Modify the content field in the copy task to use different DNS servers as needed.
  • Conditional Installation: The apt module ensures idempotent installation of resolvconf.
  • Error Handling: Ansible handles errors gracefully, and you can add more tasks or handlers for advanced error handling.

Verification

After running the playbook, you can verify the DNS configuration on each host by checking the /etc/resolv.conf file, which should reflect the nameservers specified in the playbook.

cat /etc/resolv.conf

You should see entries similar to:

nameserver 8.8.8.8
nameserver 8.8.4.4

This confirms that the DNS servers have been successfully set using resolvconf via Ansible.

Conclusion

Using Ansible to manage DNS configurations on Debian hosts via resolvconf is efficient and scalable. This approach ensures consistency across multiple servers and simplifies management tasks.

Leave a Reply

Your email address will not be published. Required fields are marked *