0

I want to set nameservers in /etc/resolv.conf using ansible. I basically want to set variables (DNS1, DNS2, DNS3). I only want to apply DNS# if it is defined. I have the following so far.

# Run this playbook on all hosts that should query the DNS server.
- hosts: all
  vars:
    # dns_server: 192.168.1.190
    nameserver_ip: 192.168.1.214
    DNS2: 192.168.1.1
  tasks:
    - name: Add DNS server's IPv4 address to /etc/resolv.conf
      command: "nmcli con mod {{ ansible_default_ipv4['interface'] }} ipv4.dns {{ nameserver_ip }}"
    - name: Add non-authoritative DNS servers to /etc/resolv.conf
      shell: "nmcli con mod {{ ansible_default_ipv4['interface'] }} +ipv4.dns {{ item }}"
      when:  item is defined
      with_items:
        - DNS2
        - DNS3
    - name: Restart default network interface to update /etc/resolv.conf
      shell: "nmcli con reload && nmcli con up {{ ansible_default_ipv4['interface'] }}"

However, when I run this I get the following error

[root@ns1 dns]# ansible-playbook --user root -i ftp.home, dns_client.yaml -k
...
...
TASK [Add non-authoritative DNS servers to /etc/resolv.conf] *****************************************************************************************************************************************************
failed: [ftp.home] (item=DNS2) => {"changed": true, "cmd": "nmcli con mod eth0 +ipv4.dns DNS2", "delta": "0:00:00.055982", "end": "2019-04-01 12:25:53.029983", "item": "DNS2", "msg": "non-zero return code", "rc": 2, "start": "2019-04-01 12:25:52.974001", "stderr": "Error: failed to modify ipv4.dns: invalid IPv4 address 'DNS2'.", "stderr_lines": ["Error: failed to modify ipv4.dns: invalid IPv4 address 'DNS2'."], "stdout": "", "stdout_lines": []}
failed: [ftp.home] (item=DNS3) => {"changed": true, "cmd": "nmcli con mod eth0 +ipv4.dns DNS3", "delta": "0:00:00.056684", "end": "2019-04-01 12:25:53.782999", "item": "DNS3", "msg": "non-zero return code", "rc": 2, "start": "2019-04-01 12:25:53.726315", "stderr": "Error: failed to modify ipv4.dns: invalid IPv4 address 'DNS3'.", "stderr_lines": ["Error: failed to modify ipv4.dns: invalid IPv4 address 'DNS3'."], "stdout": "", "stdout_lines": []}
        to retry, use: --limit @/root/ansible/dns/dns_client.retry

It seems that, instead of using the value of DNS{2,3} it is just using the variable names (literally) DNS2 and DNS3. What am I doing wrong here?

1

I figured it out. I forgot that in order to used the value of a variable in Ansible you must surround the variable name in "{{ ... }}". The following changes fixed my issue.

  with_items:
    - "{{ DNS2 }}"
    - "{{ DNS3 }}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.