我想使用 ansible 在 /etc/resolv.conf 中设置名称服务器。我基本上想设置变量(DNS1、DNS2、DNS3)。我只想应用 DNS#(如果已定义)。到目前为止我有以下内容。
# 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'] }}"
但是,当我运行这个时,我收到以下错误
[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
看起来,它只是使用变量名称(字面意思)DNS2 和 DNS3,而不是使用 DNS{2,3} 的值。我在这里做错了什么?
答案1
我想到了。我忘记了,为了在 Ansible 中使用变量的值,您必须将变量名称括在“{{ ... }}”中。以下更改解决了我的问题。
with_items:
- "{{ DNS2 }}"
- "{{ DNS3 }}"