How to create, but not overwrite, a file and manage its permissions with ansible?
-
The task seems simple. If the file does not exist, create it, otherwise retain the file and its content. In both cases, apply permissions (
owner
,group
,mode
).The most obvious candidate to this task is
ansible.builtin.file
withstate: touch
. However, it always appears as changed as the times need to be updated. Rather, once it exists and modes are ok, it should just be ok.The next candidate likely is
ansible.builtin.copy
. If passingforce: false
, it creates the file. However, it does not fix up permission on an already existing file.
-
The most obvious candidate to this task is
ansible.builtin.file
withstate: touch
.Right, this could be an option.
However, it always appears as changed as the times need to be updated.
According the documentation https://docs.ansible.com/ansible/latest/collections/ansible/builtin/file_module.html#parameters not necessarily since
access_time
andmodification_time
Should be
preserve
when no modification is requiredThe following minimal example
--- - hosts: localhost become: false gather_facts: false
tasks:
-
name: Create file
file:
path: "/home/{{ ansible_user }}/test.file"
owner: "{{ ansible_user }}"
group: "users"
access_time: preserve
modification_time: preserve
state: touch -
name: Touch again
file:
path: "/home/{{ ansible_user }}/test.file"
owner: "{{ ansible_user }}"
group: "users"
access_time: preserve
modification_time: preserve
state: touch
will result into an output of
TASK [Create file] *************************** changed: [localhost]
TASK [Touch again] ***************************
ok: [localhost]PLAY RECAP ***********************************
localhost : ok=2 changed=1
-