If you are not familiar with modules, check out Ansible - Getting Started with Modules.
The file module with state: touch is used to create a file on a managed noded (e.g. target system). In this example, the /tmp/foo.txt file will be created if it does not exist.
--- - hosts: all tasks: - name: create /tmp/foo.txt file: path: /tmp/foo.txt state: touch ...
The play should always indicate changed, regardless if the file was or was not created. If the file does not exist, it will be created. If the file exists, it will not be overwritten. However, the date and time of the file will be updated to reflect the current date time, and the file permissions and ownership will be updated. This is similar to the behavior of the Linux touch command.
TASK [create foo.txt] changed: [server1.example.com] PLAY RECAP server1.example.com : ok=1 changed=1 unreachable=0 failed=0
Skip if file exists
To prevent the target file from being modified in any way when the file exists, you can first use the stat module to determine if the file exists. Then, use when to only perform the touch if the file does not exist.
- name: "determine if /tmp/foo.txt exists" stat: path: "/tmp/foo.txt" register: "foo" - name: "create /tmp/foo.txt" file: path: "/tmp/foo.txt" state: "touch" when: "foo.stat.exists == false"
With stat and when, if the file was not created or modified, the play to determine if the file exists should return ok and the play to touch the file should return skipping.
TASK [determine if /tmp/foo.txt exists] ok: [server1.example.com] TASK [touch /tmp/foo.txt] skipping: [server1.example.com] PLAY RECAP server1.example.com : ok=2 changed=0 unreachable=0 failed=0