我需要從我的網路中獲取 DNS 服務器,我嘗試使用:
- hosts: localhost
gather_facts: no
tasks:
- name: check resolv.conf exists
stat:
path: /etc/resolv.conf
register: resolv_conf
- name: check nameservers list in resolv.conf
debug:
msg: "{{ contents }}"
vars:
contents: "{{ lookup('file', '/etc/resolv.conf') | regex_findall('\\s*nameserver\\s*(.*)') }}"
when: resolv_conf.stat.exists == True
但這并不能完全給出我需要的結果。
是否有可能以結果如下所示的方式撰寫劇本?
主機名;dns1;dns2;dnsN
uj5u.com熱心網友回復:
下面的宣告給出了名稱服務器的串列
nameservers: "{{ lookup('file', '/etc/resolv.conf').splitlines()|
select('match', '^nameserver.*$')|
map('split', ' ')|
map('last')|list }}"
您可以加入主機名和串列中的專案
msg: "{{ inventory_hostname }};{{ nameservers|join(';') }}"
筆記
- 用于測驗的完整劇本示例
- hosts: localhost
vars:
nameservers: "{{ lookup('file', '/etc/resolv.conf').splitlines()|
select('match', '^nameserver.*$')|
map('split', ' ')|
map('last')|list }}"
tasks:
- debug:
var: nameservers
- debug:
msg: |
{{ inventory_hostname }};{{ nameservers|join(';') }}
nameserver.*如果評論中沒有,下面的簡化宣告可以正常作業
nameservers: "{{ lookup('file', '/etc/resolv.conf')|
regex_findall('\\s*nameserver\\s*(.*)') }}"
不幸的是,Linux 默認檔案/etc/resolv.conf包含以下注釋:
| # 運行“systemd-resolve --status”以查看有關實際名稱服務器的詳細資訊。
此正則運算式將匹配nameservers.
nameservers:
- s.
您可以通過在關鍵字后面放置至少一個空格來解決此問題nameserver。
regex_findall('\\s*nameserver\\s (.*)') }}"
但是,如果評論中有關鍵字,這將無濟于事nameserver。
問:“沒有名為‘split’的過濾器”
A: Ansible 2.11 以下沒有過濾器拆分。改用regex_replace _
nameservers: "{{ lookup('file', '/etc/resolv.conf').splitlines()|
select('match', '^nameserver.*$')|
map('regex_replace', '^(.*) (.*)$', '\\2')|list }}"
uj5u.com熱心網友回復:
由于您regex_findall已經為您創建了一個包含所有 DNS 服務器的串列,您只需將主機名添加到該串列并join使用分號添加整個串列。
- name: check nameservers list in resolv.conf
debug:
msg: >-
{{
(
[ ansible_hostname ]
lookup('file', '/etc/resolv.conf', errors='ignore')
| regex_findall('\s*nameserver\s*(.*)')
) | join(';')
}}
這將導致類似(b176263884e6作為容器的實際主機名):
TASK [check nameservers list in resolv.conf] *****************************
ok: [localhost] =>
msg: b176263884e6;1.1.1.1;4.4.4.4;8.8.8.8
請注意,您甚至不需要該stat任務,因為您可以使用errors='ignore'.
然后,這將只為您提供主機名以及警告:
TASK [check nameservers list in resolv.conf] *****************************
[WARNING]: Unable to find '/etc/resolv.conf' in expected paths
(use -vvvvv to see paths)
ok: [localhost] =>
msg: b176263884e6
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/528969.html
標籤:重击联网可靠的主机
