请帮助我编写可解析的剧本,从多个服务器读取/etc/resolv.conf文件中的名称服务器(DNS(,并将这些名称服务器写入一个文件。
我试图将内容放入名为contents
的变量中,如下所示:
- name: check resolv.conf exists
stat:
path: /etc/resolv.conf
register: resolv_conf
- name: check nameservers list in resolv.conf
vars:
contents: "{{ lookup('file', '/etc/resolv.conf') }}"
when: resolv_conf.stat.exists == True
然后不确定如何继续。
您可以使用带有过滤器regex_findall
的regex来实现这一点,特别是考虑到您可能在那里定义了多个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
在阿尔卑斯山集装箱上,它给出了回顾:
PLAY [localhost] ***************************************************************
TASK [check resolv.conf exists] ************************************************
ok: [localhost]
TASK [check nameservers list in resolv.conf] ***********************************
ok: [localhost] => {
"msg": [
"192.168.65.1"
]
}
PLAY RECAP *********************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
我不确定这是否正是您想要的,但您可以使用lineinfile将内容写入文件中,而不是使用replace模块从文件中替换除名称服务器之外的所有内容。像这样:
- name: Check if resolv exists
stat:
path: /etc/resolv.conf
register: resolv_conf
- set_fact:
content: "{{ lookup('file', '/etc/resolv.conf') }}"
when: resolv_conf.stat.exists
- name: Write them into a file
lineinfile:
line: "{{ content }}"
create: yes
state: present
path: /tmp/resolv_conf_nameservers
- name: Remove everything but nameservers
replace:
path: /tmp/resolv_conf_nameservers
regexp: "^(?!nameserver).*$"
replace: ""
~
请注意,您应该使用set_fact将内容加载到变量中。
如果您希望将包含名称服务器的文件放在您自己的计算机localhost中,请在最后两个任务中使用delegate_to:
- name: Check if resolv exists
stat:
path: /etc/resolv.conf
register: resolv_conf
- set_fact:
content: "{{ lookup('file', '/etc/resolv.conf') }}"
when: resolv_conf.stat.exists
- name: Write them into a file
lineinfile:
line: "{{ content }}"
create: yes
state: present
path: /tmp/resolv_conf_nameservers
delegate_to: localhost
- name: Remove everything but nameservers
replace:
path: /tmp/resolv_conf_nameservers
regexp: "^(?!nameserver).*$"
replace: ""
delegate_to: localhost