The file module doesn't recognise subdirectories:
/tmp/testdir
├── folder1
├── folder2
└── specific_folder
- name: Recursively change ownership
file:
path: /tmp/testdir/
state: directory
recurse: yes
owner: "{{ user }}"
group: "{{ user }}"
changed: [localhost] => {
"changed": true,
"diff": {
"after": {
"path": "/tmp/testdir/"
},
"before": {
"path": "/tmp/testdir/"
}
},
"gid": 0,
"group": "root",
"invocation": {
"module_args": {
"owner": "root",
"path": "/tmp/testdir/",
"recurse": true,
"state": "directory",
}
},
"mode": "0755",
"owner": "root",
"path": "/tmp/testdir/",
"size": 4096,
"state": "directory",
"uid": 0
}
So we should find a way to get a list of subdirectories, which is find module
---
- hosts: localhost
gather_facts: no
vars:
user: root
path: /tmp/testdir/
tasks:
- name: list directories
find:
paths: "{{ path }}"
file_type: any
register: directories
Output(shrinked):
ok: [localhost] => {
"changed": false,
"examined": 3,
"files": [
{
"mode": "0755",
"path": "/tmp/testdir/folder1",
"pw_name": "root",
},
{
"mode": "0755",
"path": "/tmp/testdir/folder2",
"pw_name": "root",
},
{
"mode": "0755",
"path": "/tmp/testdir/specific_folder",
"pw_name": "root",
}
],
"invocation": {
},
"matched": 3,
"msg": "All paths examined",
"skipped_paths": {}
Now we got the output as an array calles files in the register directories.
We can loop over the attribute path and set a condition to skip the task if the path includes name of the excluded directory.
---
- hosts: localhost
gather_facts: no
vars:
user: root
path: /tmp/testdir/
exclude_dir: specific_folder
tasks:
- name: list directories
find:
paths: "{{ path }}"
file_type: any
register: directories
- name: Recursively change ownership
file:
path: "{{ item.path }}"
state: directory
owner: "{{ user }}"
group: "{{ user }}"
loop: "{{ directories.files }}"
notify:
- Restart service
when:
- deploy
- exclude_dir not in item.path
TASK [Recursively change ownership] *****************************************
ok: [localhost] => (item={'path': '/tmp/testdir/folder1', ....})
ok: [localhost] => (item={'path': '/tmp/testdir/folder2', ....})
skipping: [localhost] => (item={'path': '/tmp/testdir/specific_folder', ...})