Trying to run stat over a list if directories and perform some action if they exist in Ansible

Viewed 252

I'm an Ansible newbie so please bear with me.

I have a list of directories that I need to set FACLs on. Not all of these directories will exist on all hosts in my inventory. My Ansible playbook is trying to achieve the following:

-stat each directory listed in the dir_list variable file and register the results. -Run the acl module to assign FACL permissions to any directory that exists on the server.

Here is what my variable file - dir_list - looks like:

dir_path:
  - /tmp/testdir1
  - /tmp/testdir2
  - /tmp/testdir3
  - /tmp/testdir4

Here is what my playbook looks like:

---
- hosts: localhost
  connection: local
  become: yes
  become_method: sudo
  become_user: root
  gather_facts: yes
  any_errors_fatal: no
  vars_files:
    - /home/user1/ansible/dir_list
  tasks:
  - name: Check if directory exists
    stat:
      path: "{{ item }}"
    with_items:
      "{{ dir_path }}"
    register: dircheck

  - name: Set ACLs
    acl:
      path: "{{ item }}"
      entity: testuser
      etype: user
      permissions: rx
      state: present
    with_items: "{{ dircheck.results | selectattr('stat.isdir') | map(attribute='item') | list }}"
    when: item.stat.isdir is defined and (item.stat.isdir|bool)

I have obviously researched this and tried a a dozen+ suggested solutions to no avail. The last two lines are just two of the myriad combinations I've tried. I'm running Ansible version 2.9.10 on RHEL7.

Any help would be appreciated.

1 Answers

Q: "Stat each directory listed in the dir_list variable ... Run the acl module to assign FACL permissions to any directory that exists."

A: Given the dirs

shell> ls -d1 /tmp/* | grep testdir
/tmp/testdir1
/tmp/testdir2
/tmp/testdir3

The playbook

- hosts: localhost
  vars:
    dir_path:
      - /tmp/testdir1
      - /tmp/testdir2
      - /tmp/testdir3
      - /tmp/testdir4
  tasks:
    - stat:
        path: "{{ item }}"
      loop: "{{ dir_path }}"
      register: dircheck
    - debug:
        msg: "Set ACLs at {{ item.stat.path }}"
      loop: "{{ dircheck.results }}"
      loop_control:
        label: "{{ item.item }}"
      when:
        - item.stat.exists
        - item.stat.isdir|default(false)

gives (abridged)

TASK [stat] ****
ok: [localhost] => (item=/tmp/testdir1)
ok: [localhost] => (item=/tmp/testdir2)
ok: [localhost] => (item=/tmp/testdir3)
ok: [localhost] => (item=/tmp/testdir4)

TASK [debug] ****
ok: [localhost] => (item=/tmp/testdir1) => 
  msg: Set ACLs at /tmp/testdir1
ok: [localhost] => (item=/tmp/testdir2) => 
  msg: Set ACLs at /tmp/testdir2
ok: [localhost] => (item=/tmp/testdir3) => 
  msg: Set ACLs at /tmp/testdir3
skipping: [localhost] => (item=/tmp/testdir4)
Related