HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

How to create, but not overwrite, a file and manage its permissions with ansible?

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
overwritefilepermissionscreatewithbutmanageitshowand

Problem

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 with state: 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 passing force: false, it creates the file. However, it does not fix up permission on an already existing file.

Solution

The most obvious candidate to this task is ansible.builtin.file with state: touch.

Right, this could be an option.

However, it always appears as changed as the times need to be updated.

According the documentation file module - Parameters not necessarily since access_time and modification_time

Should be preserve when no modification is required

The 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

Context

StackExchange DevOps Q#17006, answer score: 3

Revisions (0)

No revisions yet.