Issue
I have this playbook that is working fine, but not as I need it and I cannot find the problem. The playbook should allow me to change permissions to a filesystem recursively or else to a particular file.
- name: Playbook to change file and directory permissions
hosts: '{{ target_hosts }}'
vars:
PATH: '{{ target_path }}'
PERMISSIONS: '{{ number }}'
OWNER: '{{ target_owner }}'
GROUP: '{{ target_group }}'
tasks:
- name: Checking that it is not a system mount point
fail:
msg: "Changing permissions on system fs is not allowed"
when: PATH in ["/etc", "/var", "/tmp", "/usr", "/", "/opt", "/home", "/boot"]
- name: Checking if the path is a file or a filesystem
stat:
path: '{{ PATH }}'
register: path_status
- name: Applying permissions on the filesystem
block:
- name: Report if directory exists
debug:
msg: "Directory {{ PATH }} is present on the server"
when: path_status.stat.exists
- name: Applying permissions recursively
file:
path: '{{ PATH }}'
mode: '0{{ PERMISSIONS }}'
owner: '{{ OWNER }}'
group: '{{ GROUP }}'
recurse: yes
when: path_status.stat.isdir is defined and path_status.stat.isdir
- name: Applying permissions on the file
block:
- name: Report if file exists
debug:
msg: "File {{ PATH }} is present on the server"
when: path_status.stat.exists
- name: Applying permissions
file:
path: '{{ PATH }}'
state: file
mode: '0{{ PERMISSIONS }}'
owner: '{{ OWNER }}'
group: '{{ GROUP }}'
when: path_status.stat.isreg is defined and path_status.stat.isreg
The first 2 tasks
- Verify that it is not a system filesystem
- Using the Ansible stat module, I register the path that is being passed as a parameter of the PATH variable
When I execute just passing a filesystem like in the following example
ansible-playbook change_fs_permissions.yml -e "target_hosts=centoslabs target_path=/etc number=755 target_owner=root target_group=testing"
the execution ends because it's a system mount point. (What do I expect)
But if I enter something like /tmp/somefile.txt as a parameter of the PATH variable, my idea is that the playbook will fail again since it cannot change anything within that filesystem but it does not continue executing and changes the permissions.
They will see that I use the BLOCK module since it seemed to me the best so that if a filesystem is passed to it, it executes those tasks and if it is a file it executes the others.
Can you give me some ideas on how to approach this problem?
Solution
I did it and it's working now. What I did was change this part:
- name: Checking that it is not a system mount point
fail:
msg: "Changing permissions on system fs is not allowed"
when: PATH in ["/etc", "/var", "/tmp", "/usr", "/", "/opt", "/home", "/boot"]
For:
- name: Checking that it is not a system mount point
fail:
msg: "Changing permissions on system fs is not allowed"
when: PATH.split('/')[1] in ["/etc", "/var", "/tmp", "/usr", "/", "/opt", "/home", "/boot"]
Answered By - Fede Berbara Answer Checked By - Marie Seifert (WPSolving Admin)