I am trying to write one playbook that checks for sudoers syntax and logs the PASS or FAIL result in a file. When I run it initially , it logs PASS message saying everything is fine. But when I intentionally insert wrong syntax in the file , it gives me FAIL message. But in the result.txt I get both lines , whereas I need only one line in my result.txt. What I basically needs a override of the existing line (PASS should change to FAIL , and FAIL should change to PASS) depending on the result of condition.
---
- name: ANsible Testing
hosts: localhost
become: true
ignore_errors: true
tasks:
- name: Gather package facts
ansible.builtin.package_facts:
manager: auto
- name: Gather service facts
ansible.builtin.service_facts:
- name: Create final report file
file:
path: /tmp/test_results.txt
state: touch
- name: Check if infra_monitoring exists in sudoers file
shell: |
grep infra_monitoring /etc/sudoers
visudo -cf /etc/sudoers
register: sudoers_output
- name: Append the result to final report
lineinfile:
dest: /tmp/test_results.txt
line: "[FAIL] sudoers test is failed."
state: present
when: sudoers_output.rc != 0
- name: Append the result to final report
lineinfile:
dest: /tmp/test_results.txt
line: "[PASS] sudoers test is working fine."
state: present
when: sudoers_output.rc == 0
test_results.txt contents after two runs , where the main ask is to override the first line only with [FAIL] message if initially it logged [PASS] message , and [PASS] message if initially it logged [FAIL] message.
[PASS] sudoers test is working fine.
[FAIL] sudoers test is failed.
I am running out of ideas. Please help on the same