FreeKB - Ansible file module (change owner group mode permissions chown chgrp chmod)
Ansible - file module (change owner group mode permissions chown chgrp chmod)

If you are not familiar with modules, check out Ansible - Getting Started with Modules.

The file module can be used to change the owner, group, and/or mode of a file or directory on a managed node (e.g. target system). 

AVOID TROUBLE

If the file or directory does not exist, attempting to change the owner, group or permission of the file should return "file is absent, cannot continue". For this reason, you will almost always want to use the file module to create the file or create the directory if it doesn't exist, or use the stat module to determine if the file or directory exists.

 

Here is how you would update the owner, group and mode of /tmp/foo.txt using the file module.

- name: update foo.txt owner group mode
  file:
    path: /tmp/foo.txt
    owner: john.doe
    group: admins
    mode: "0770"

 

If the playbook is being invoked by the user that owns /tmp/foo.txt (root in this example), then the owner, group and mode will be updated. 

TASK [update foo.txt owner group mode]
changed: [server1.example.com]

 

On the other hand, if the playbook is being invoked by anyone other than root, a fatal error "Operation not permitted" would be returned. Or, become could be used to become root.

TASK [update /tmp/foo.txt owner group mode]
fatal: [server1.example.com]: FAILED! => {"changed": false, "gid": 10, "group": "root", "mode": "0644", "msg": "chown failed: [Errno 1] Operation not permitted: '/tmp/foo.txt'", "owner": "root", "path": "/tmp/foo.txt", "secontext": "unconfined_u:object_r:user_tmp_t:s0", "size": 0, "state": "file", "uid": 0}

 


Recursive directory

state: directory and recurse: yes can be used to update the owner of every file and directory at and below a certain directory. In this example, every file and directory below the /tmp directory will be updated to be owned by root.

AVOID TROUBLE

When recurse is used, the owner will be changed at and below the target directory. In this example, the /tmp directory and every file and directory below /tmp will be updated to be owned by root.

- name: recursively update /tmp directory owner
  file:
    path: /tmp
    state: directory
    recurse: yes
    owner: root

 

Or like this, to give "group" the "write" permission.

- name: recursively update /tmp directory
  file:
    path: /tmp
    state: directory
    recurse: yes
    mode: g+w

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 25dfe in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |