Using the Ansible find module to search based on permissions

Viewed 149

How could this be done in Ansible?

find . -name "*.sh" -type f  ! -perm 754

So, using the Ansible find module to search based on permissions.

1 Answers

You cannot bake this into the find module itself.

But you can get all the files matching your pattern and then, filter the result based on the rights you want.

So, this will be a two tasks solution:

- find:
    paths: /usr/local/ansible
    patterns: '*.sh'
  register: find

- debug:
    var: find.files | selectattr('mode', '!=', '0754')

Given the playbook (with shell tasks for comparison):

- hosts: localhost
  gather_facts: no

  tasks:
    - find:
        paths: /usr/local/ansible
        patterns: '*.sh'
      register: find

    - shell: find /usr/local/ansible/*.sh  -type f
      register: shell
    - name: All shell files via shell
      debug:
        var: shell.stdout
    - name: All shell files via find
      debug:
        var: find.files | map(attribute="path")

    - shell: find /usr/local/ansible/*.sh  -type f  ! -perm 754
      register: shell
    - name: All shell files having 754 perm via shell
      debug:
        var: shell.stdout
    - name: All shell files having 754 perm via find
      debug:
        var: >
          find.files
          | selectattr('mode', '!=', '0754')
          | map(attribute="path")

This yields:

TASK [shell] **************************************************************
changed: [localhost]

TASK [All shell files via shell] ******************************************
ok: [localhost] => 
  shell.stdout: |-
    /usr/local/ansible/a.sh
    /usr/local/ansible/b.sh

TASK [All shell files via find] *******************************************
ok: [localhost] => 
  find.files | map(attribute="path"):
  - /usr/local/ansible/a.sh
  - /usr/local/ansible/b.sh

TASK [shell] **************************************************************
changed: [localhost]

TASK [All shell files having 754 perm via shell] **************************
ok: [localhost] => 
  shell.stdout: /usr/local/ansible/a.sh

TASK [All shell files having 754 perm via find] ***************************
ok: [localhost] => 
  find.files | selectattr('mode', '!=', '0754') | map(attribute="path"):
  - /usr/local/ansible/a.sh
Related