Ansible: How to chmod +x a file with Ansible?

59,410

Solution 1

ansible has mode parameter in file module exactly for this purpose.

To add execute permission for everyone (i.e. chmod a+x on command line):

- name: Changing perm of "/foo/bar.sh", adding "+x"
  file: dest=/foo/bar.sh mode=a+x

Symbolic modes are supported since version 1.8, on a prior version you need to use the octal bits.

Solution 2

The mode parameter should be specified when using the copy module.

Example:

- name: copy file and set permissions
  copy:
    src: script.sh
    dest: /directory/script.sh
    mode: a+x

Solution 3

You can change the permission of a file without copy module.

- name: Change permission on myScript.sh file
  file:
    path: /path/to/directory/myScript.sh
    state: file
    owner: root
    group: root
    mode: 0755

Solution 4

A good and verbose way of doing it while using the copy module is with the Ansible symbolic mode:

  copy:
    src: create_rules.sh
    dest: ~/rules/
    owner: root
    group: root
    mode: u+rwx,g=,o=

The mode above is equivalent to chmod 0700

u+rwx means "give read(r), write(w) and execution(x) permissions to owner(u)", which is a 7 in the octal's second field '07'

You are able to do also ug+rwx,o= which is equivalent to chmod 0770.

Please notice to not use spacing after the comma.

The documentation also shows that ug=rwx,o= is O.K. too.

Share:
59,410
Atlantic0
Author by

Atlantic0

Updated on July 05, 2022

Comments

  • Atlantic0
    Atlantic0 11 months

    What is the best way to chmod + x a file with ansible.

    Converting the following script to ansible format.

    mv /tmp/metadata.sh /usr/local/bin/meta.sh
    chmod +x /usr/local/bin/meta.sh
    

    This is what I have so far..

    - name: move /tmp/metadata.sh to /usr/local/bin/metadata.sh
      command: mv /tmp/metadata.sh /usr/local/bin/metadata.sh
    
  • digitalformula
    digitalformula over 4 years
    2 years later and this answer helped me with an Ansible issue. Thanks everyone.
  • aseriesofdarkcaves
    aseriesofdarkcaves over 2 years
    @DustWolf - do you have a reference for that? I use symbolic mode exclusively and have not seen anything in the documentation stating that only octal is idempotent.
  • homeOfTheWizard
    homeOfTheWizard 11 months