我目前正在构建一个剧本来测试某些 conf 文件是否存在,然后检查其内容。文件如下
- /etc/resolv.conf - 然后检查名称服务器是否配置正确
- /etc/systemd/timesyncd.conf - 检查是否已配置
- /etc/ntp.conf - 还检查是否已配置某些内容
.yml 代码如下,如您所见,每次检查的任务都是相同的,只需重新配置文件路径和正则表达式部分(如果需要)。
tasks:
# RESOLV.CONF
- name: Check if resolv.conf exist
stat:
path: /etc/resolv.conf
register: resolv_conf
- name: Retrieve nameservers
debug:
msg: "{{ contents }}"
vars:
contents: "{{ lookup('file', '/etc/resolv.conf') | regex_findall('\\s*nameserver\\s*(.*)') }}"
when: resolv_conf.stat.exists == True
# NTP.CONF
- name: check if ntp.conf exists
stat:
path: /etc/ntp.conf
register: ntp_conf
- name: retrieve ntp conf server content
debug:
msg: "{{ contents }}"
vars:
contents: "{{ lookup('file', '/etc/ntp.conf') | regex_search('^server.*') }}"
when: ntp_conf.stat.exists == True
# TIMESYNC.CONF
- name: check if timesyncd
stat:
path: /etc/systemd/timesyncd.conf
register: timesyncd_conf
- name: Affiche le contenu de timesyncd.conf s'il est configure
debug:
msg: "{{ contents }}"
vars:
contents: "{{ lookup('file', '/etc/systemd/timesyncd.conf') | regex_search('^NTP=.*') }}"
when: timesyncd_conf.stat.exists == True
除有关 NTP.CONF 检查的任务外,其他任务运行良好,该任务失败,并出现以下情况:
vendredi 07 octobre 2022 08:28:07 +0200 (0:00:00.509) 0:00:05.115 ******
[WARNING]: Unable to find '/etc/ntp.conf' in expected paths (use -vvvvv to see paths)
fatal: [my_server]: FAILED! => {"msg": "An unhandled exception occurred while templating '{{ lookup('file', '/etc/ntp.conf') | regex_search('^server.*') }}'. Error was a <class 'ansible.errors.AnsibleError'>, original message: An unhandled exception occurred while running the lookup plugin 'file'. Error was a <class 'ansible.errors.AnsibleError'>, original message: could not locate file in lookup: /etc/ntp.conf. could not locate file in lookup: /etc/ntp.conf"}
我不明白为什么它会失败,因为我使用相同的功能,用户和文件获得的权利与 /etc/ 中的其他用户相同。 此外,我很快尝试用“cat”做同样的事情并且它有效:
- name: check ntp.conf content
command: "cat /etc/ntp.conf"
register: ntp_conf_contenu
- debug:
msg:
- " {{ ntp_conf_contenu | regex_findall ('server') }}"
你知道它为什么会失败吗?
多谢 !