FreeKB - Ansible file module (create file touch)
Ansible - file module (create file touch)

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.

- 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

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter c4087 in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |