6

What’s the best way to use registered variable ‘audit_tools’ to check if all items are own by root ? Do I need to use Jinja2 filter or something ?

Thanks

- name: Verify audit tools are own by root user.
  block: 
    - name: check if audit tools are own by root user.
      become: true
      stat:
        path: "/sbin/{{ audit_loop }}"
      loop:
        - auditctl
        - aureport
        - ausearch
        - autrace
        - auditd
        - audispd
        - augenrules
      loop_control:
        loop_var: audit_loop
      register: audit_tools
debug:
  msg: “one or more tools are not own by root.”
When: .....



Rescue ......

sudoi
  • 61
  • 1
  • 4

1 Answers1

6

Q: "Check if all items are own by root."

A: Put the list of the tools into the variable audit_tools. Compare the length of the lists. For example

- hosts: localhost
  vars:
    audit_tools:
      - auditctl
      - aureport
      - ausearch
      - autrace
      - auditd
      - audispd
      - augenrules
  tasks:
    - block:
        - stat:
            path: "/sbin/{{ item }}"
          loop: "{{ audit_tools }}"
          register: result
        - assert:
            that: no_audit_tools == no_owner_root
            fail_msg: "One or more tools are not own by root."
          vars:
            no_audit_tools: "{{ audit_tools|length }}"
            no_owner_root: "{{ result.results|
                               json_query('[?stat.pw_name==`root`]')|
                               length }}"
      rescue:
        - debug:
            msg: "Rescue: audit tools not owned by root."

If not all items are owned by root assert will fail and the block will proceed to the rescue section

TASK [assert] ****
fatal: [localhost]: FAILED! => changed=false 
  assertion: no_audit_tools == no_owner_root
  evaluated_to: false
  msg: One or more tools are not own by root.

TASK [debug] **** ok: [localhost] => msg: 'Rescue: audit tools not owned by root.'


Q: "This solution requires JMESPath to be installed. Is there an alternative solution?"

A: Yes. It is. Use Jinja filter selectattr

            no_owner_root: "{{ result.results|
                               selectattr('stat.pw_name', 'eq', 'root')|
                               list|length }}"
Vladimir Botka
  • 1,946
  • 6
  • 12