The file module with state: touch is used to create a file on a managed noded (e.g. target system). Or, the local_action module or delegate_to parmater can be used to invoke this module on the control node (that's your Ansible server).
The ansible-doc file command can be used to show the Ansible documention on the file module.
In this example, the /tmp/foo.txt file will be created if it does not exist.
- 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
The file module accepts the following options.
Here is an example of how these options would be used.
- name: "create foo.txt" file: path: "/tmp/foo.txt" state: "touch" owner: "foo" group: "foo" mode: "0644" seuser: "unconfined_u" serole: "object_r" setype: "httpd_sys_content_r" selevel: "s0"