I'm currently building a playbook to test if some conf files are existing and then check the contents. Files are the following
- /etc/resolv.conf - then check if nameservers are well configured
- /etc/systemd/timesyncd.conf - check if something has been configured
- /etc/ntp.conf - also check if something has been configured
.yml code is the following, as you can see the task is the same for every checks, just reconfigured filepath and the regex part if needed.
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
The tasks are running well except the one about NTP.CONF check that fails with the following :
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"}
I don't understand why it fails as i use the same function, users, and file got the same rights are some others within /etc/. Moreover, i quickly tried to do the same with "cat" and it works :
- name: check ntp.conf content
command: "cat /etc/ntp.conf"
register: ntp_conf_contenu
- debug:
msg:
- " {{ ntp_conf_contenu | regex_findall ('server') }}"
Do you have any idea why it fails ?
Thanks a lot !
Lookups are not executed on the remote host, they are executed locally.
From the documentation:
So you check if the file exists on the remote machine and then you read it from your local machine where the playbook is executed.
To read a file from the remote machine you can use the slurp module.