Read DNS server configured on Linux and Windows hosts

Hi everyone, I’m starting to use Ansible and I’d like to make a workbook to read the DNS configuration on Linux and Windows virtual machines, with a view to then modifying them. Is there something like that, I guess yes, without having to go and read e.g. /etc/resolv.conf and run an ifconfig?

Thank you,
Matteo

I’ve not used Windows for 20+ years so can’t help with that aspect of this question…

You can’t assume that /etc/resolv.conf is used on Linux these days, systemd might have replaced it with a symlink:

ls -lah /etc/resolv.conf 
lrwxrwxrwx 1 root root 39 Jul 24  2023 /etc/resolv.conf -> ../run/systemd/resolve/stub-resolv.conf

Also ifconfig has been replaced on many (most?) distros with ip addr:

ifconfig
-bash: ifconfig: command not found

On Debian and Ubuntu servers I install the systemd-resolved package and generate a /etc/systemd/resolved.conf.d/resolved.conf file using Ansible and it generaly contains something like this:

# Ansible managed

[Resolve]
DNS=9.9.9.9 8.8.8.8

# vim: syntax=systemd

The setup module (gather facts) provides an ansible_dns dict with information gleaned from /etc/resolv.conf on Linux/Unix systems.

"ansible_dns": {
    "nameservers": [
        "192.168.1.82",
        "192.168.1.1"
    ],
    "search": [
        "ww.example.net"
    ]
}

I forget whether that is reported for Windows as well.

You might be able to use that information to decide whether you need/want to replace anything with, say, a template.

2 Likes

Thanks Jan-Piet, that was exactly what I needed and it works great with Linux hosts.

Documentation says it should work also with windows hosts, but I only get an empty string.

I search for other modules, but without success, except “ansible.windows.win_dns_client”, but it seems it can only set DNS, not read them: is it possible that no one else has ever had this need? :slight_smile:

---
- hosts: all
  gather_facts: false
  tasks:
    - name: Get all DNS
      ansible.builtin.setup:
        gather_subset:
          - '!all'
          - '!any'
          - dns

    - name: Run several insert queries against db test_db in single transaction
      vars:
        dns1: "{{ ansible_facts.dns.nameservers[0] | default('') }}"
        dns2: "{{ ansible_facts.dns.nameservers[1] | default('') }}"
        domain: "{{ ansible_facts.dns.domain | default('') }}"
        os: "{{ ansible_facts['lsb']['description'] | default('') }}"
      community.mysql.mysql_query:
        login_host: ***
        login_db: ***
        login_user: ***
        login_password: ***
        query:
          - INSERT INTO DNS (DNSId, Host, DNS1, DNS2, Domain, Timestamp, OS) VALUES (null, "{{ inventory_hostname }}", "{{ dns1 }}", "{{ dns2 }}", "{{ domain }}", NOW(), "{{ os }}");
      delegate_to: 127.0.0.1

Matteo