patternMinor
Ansible: register variable with loop
Viewed 0 times
withloopregistervariableansible
Problem
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
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
......Solution
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
If not all items are owned by root assert will fail and the block will proceed to the rescue section
Q: "This solution requires JMESPath to be installed. Is there an alternative solution?"
A: Yes. It is. Use Jinja filter selectattr
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 }}"
Context
StackExchange DevOps Q#13004, answer score: 6
Revisions (0)
No revisions yet.