-1

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

isilia
  • 379
  • 1
  • 11
  • 2
    Why do you want to write to a file, that's usually not required and not a logic choice to make. Ansible is desired state. You should either define whether you want that user in the sudoers file or not. – Kevin C Aug 23 '23 at 11:54
  • I am not deleting user. I am just testing the edge case. is there a way to make the above use case in ansible? – isilia Aug 23 '23 at 12:07
  • 1
    That shouldn't be required. Why would you want this, and why this clunky setup of writing something to a file based on the other condition. – Kevin C Aug 23 '23 at 12:08
  • 1
    @isilia then run the modification of user in `check_mode: true` and act on the result of that task in dry mode: https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_checkmode.html#enforcing-or-preventing-check-mode-on-tasks – β.εηοιτ.βε Aug 23 '23 at 12:12

0 Answers0