Ansible recursively set permission on directory

Viewed 184

I am trying to set permission on directories from a list. Below is an example list where I would like dirA, dirB, dirC and dirD to get o-w permission.

"__cronjob_paths": [
        "/dirA/dirB",
        "/dirC/dirD",
    ] 

file module has recursive option but it also sets the permissions on the files within the directories so it's not an option.

Would a regex or filter be the best way to solve this? Maybe filter out the /and save the directories into another list which i can loop through and set permissions?

I also need to have in mind that there could be other directories within the system that has a directory with the same name as the one from the list (which should not get o-w)

1 Answers

Create lists of the subdirs and indexes, e.g.

    - set_fact:
        _paths: "{{ _paths|d([]) + [{'dir': _dir, 'idx': _idx}] }}"
      loop: "{{ __cronjob_paths }}"
      vars:
        _dir: "{{ item.split('/')|select() }}"
        _idx: "{{ range(1, _dir|length + 1) }}"

gives

  _paths:
  - dir:
    - dirA
    - dirB
    idx:
    - 1
    - 2
  - dir:
    - dirC
    - dirD
    idx:
    - 1
    - 2

Now, you can iterate idx subelements and join the subdirs, e.g.

    - debug:
        msg: "chmod o-w /{{ item.0.dir[:item.1]|join('/') }}"
      with_subelements:
        - "{{ _paths }}"
        - idx

gives

  msg: chmod o-w /dirA
  msg: chmod o-w /dirA/dirB
  msg: chmod o-w /dirC
  msg: chmod o-w /dirC/dirD

Proceed either with command or file module if this is what you want.

Related