I have a playbook I’m developing where I’m trying to find any server that has a 0 length /var/log/messages files. When I find those, I want to restart the rsyslog service on those. So right now I’m setting this fact as follows:
- How can I NOT print what server2 is printing/showing?
I’d say add a when clause to the task, like:
- name: Print results
ansible.builtin.debug:
msg: “{{ zero }}”
when: “some condition here”
so the print only happens when the condition is met. The condition might be some value from the message_files variable
Or maybe something like:
when: meages_files.ssfiles | selectattr(‘size’, ‘==’, 0)
not sure about that though because I don’t understand really what meages_files.ssfiles | selectattr(‘size’, ‘==’, 0) does
Well, the set_fact is supposed to only register or select anything where the size parameter of the files attributes is 0. The ones that are printing just don’t fit that criteria, and therefore, shouldn’t be included in the debug output. Yet they are, so that’s what I’m trying to fix/clean up first.
Thanks,
Harry
You’re drifting from your goal, which was to restart a service based on a zero-length /var/log/messages file. Now you’re getting mired down because of a set_fact (which you don’t need) on hosts on which the find module (which is the wrong module) failed to find the file in question.
You probably want to use ansible.builtin.stat which will tell you both whether the file exists (find doesn’t find it if it doesn’t) and what size it is.
- name: Get stat for /var/log/messages
ansible.builtin.stat:
path: /var/log/messages
register: messages_files
- name: What to do about missing /var/log/messages?
ansible.builtin.debug:
msg: '{{ inventory_hostname }} has no /var/log/messages. Now what?'
when: not messages_files.stat.exists
- name: Restart syslog if /var/log/messages is zero-length
ansible.builtin.service:
name: syslog
state: restarted
when: messages_files.stat.exists and messages_files.stat.size == 0
There’s no need to start another play to do the service restarts.
The module always returns a list. You’re doing an on all the hosts, the value of which is a subset of that list. But that, too, is a list, even if it is an empty list. So you’ll get an empty list for any host where either (a) no file was found (not likely), or (b) where is not zero-length. But there’s nothing in your first few tasks to preclude from showing these very real and very much there empty lists.
Something like this should work?
I used the stat module as suggested by Todd and it worked perfectly. I appreciate the suggestion and for setting me straight.
Thanks,
Harry