76

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
Promise Preston
  • 24,334
  • 12
  • 145
  • 143
Atlantic0
  • 3,271
  • 5
  • 17
  • 24

4 Answers4

107

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.

Jason
  • 9,408
  • 5
  • 36
  • 36
heemayl
  • 39,294
  • 7
  • 70
  • 76
  • 8
    2 years later and this answer helped me with an Ansible issue. Thanks everyone. –  Jan 04 '19 at 05:37
  • @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. – aseriesofdarkcaves Jan 08 '21 at 16:19
  • https://docs.ansible.com/ansible/latest/collections/ansible/builtin/file_module.html – Özgün Jun 14 '22 at 09:24
21

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
Adam
  • 639
  • 9
  • 22
5

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
Muhammad Tariq
  • 3,318
  • 5
  • 38
  • 42
1

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.

RicHincapie
  • 3,275
  • 1
  • 18
  • 30