0

This is part of Ansible automation where I have to run a single chmod command and read the permission from the users. Thus,

chmod -R $fileperm <filename>

However, at times the user may not provide any fileperm thus $fileperm is empty in which case the file permissions should remain unchanged however the above command fails.

I do not wish to have two chmod commands having different when conditions.

Can you please suggest how can I accommodate whether the user provides or does not provide permissions in the same command if possible? I am currently using Ansible's command module to execute chmod.

4
  • I don't know what you mean by when. Which automation language are you using? If it's the shell, you can use a compact command like [ -z "$fileperm" ] || chmod $fileperm <filename>. The part after || is only executed if the preceding test is false, i.e. $fileperm is non-empty. Commented Jan 30, 2021 at 12:24
  • I'm using ansible so can you give me the equivalent of [ -z "$fileperm" ] || considering my current code is command: chmod -R $fileperm <filename>
    – Ashar
    Commented Jan 30, 2021 at 12:46
  • 1
    Ignoring for the moment that there's probably a module you could be using for that, u+ (add nothing extra for owner) seems to be a valid symbolic permission string for (GNUs implementation of) chmod, so I guess you could use that as a default? Commented Jan 30, 2021 at 12:54
  • Check the documentation (docs.ansible.com/ansible/latest/collections/ansible/builtin/…). "The command(s) will not be processed through the shell (...). Use the ansible.builtin.shell module if you need these features." Commented Jan 30, 2021 at 13:41

1 Answer 1

4

Don't call chmod via command or shell. Use the file module to set permissions, see documentation. This is idempotent. The module will check the current state of the file/directory and will only change it, if necesary.

In that case, you add this task

- set_fact:
    files:
      - name: file1
        mode: 0755
      - name: file2
      - name: file3
        mode: 0644

- file:
    path: "{{ item.name }}"
    mode: "{{ item.mode | default(omit) }}"
  loop: "{{ files }}"

I'm not sure, what you mean with "at times the user may not provide". Ansible is nothing interactice. So I'm not sure, what you mean. Also you're talking about bash vars like $fileperm. Ansible has no "bash vars". They are facts and uses Jinja to evaluate them.

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .