Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible - Mode 755 for directories and 644 for files recursively

I'd like to allow anyone to list and read all files in my directory tree, but I don't want to make the files executable :

dir
  \subdir1
      file1
  \subdir2
      file2
  ...
  \subdirX
      fileX

The following task makes my directories and files readable, but it makes all the files executable as well:

- name: Make my directory tree readable
  file:
    path: dir
    mode: 0755
    recurse: yes

On the other hand, if I choose mode 0644, then all my files are not executable, but I'm not able to list my directories.

Is it possible to set mode 755 for all directories and 644 for all files in a directory tree?

like image 297
mykola Avatar asked Feb 28 '15 06:02

mykola


People also ask

What does Permission 644 and 755 mean for a file?

Some file permission examples: 777 - all can read/write/execute (full access). 755 - owner can read/write/execute, group/others can read/execute. 644 - owner can read/write, group/others can read only.

How do I set permissions on 644?

Change Permissions Recursively Then use first command to chmod 755 for all directories and sub directories. The second command will change all the files permission to 0644 (chmod 644) under the directory tree. You can also change permission using xargs command to do this quickly.

What is recurse in Ansible?

recurse. boolean. added in 1.1 of ansible.builtin. Recursively set the specified file attributes on directory contents. This applies only when state is set to directory .


2 Answers

Since version 1.8, Ansible supports symbolic modes. Thus, the following would perform the task you want:

- name: Make my directory tree readable
  file:
    path: dir
    mode: u=rwX,g=rX,o=rX
    recurse: yes

Because X (instead of x) only applies to directories or files with at least one x bit set.

like image 124
Adrien Clerc Avatar answered Oct 11 '22 09:10

Adrien Clerc


The Ansible file/copy modules don't give you the granularity of specifying permissions based on file type so you'd most likely need to do this manually by doing something along these lines:

- name: Ensure directories are 0755
  command: find {{ path }} -type d -exec chmod -c 0755 {} \;
  register: chmod_result
  changed_when: "chmod_result.stdout != \"\""

- name: Ensure files are 0644
  command: find {{ path }} -type f -exec chmod -c 0644 {} \;
  register: chmod_result
  changed_when: "chmod_result.stdout != \"\""

These would have the effect of recursing through {{ path }} and changing the permissions of every file or directory to the specified permissions.

like image 28
Bruce P Avatar answered Oct 11 '22 09:10

Bruce P