2

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.

1 Answer 1

3

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 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.