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

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

 


Optional Options

The file module accepts the following options.

  • owner (e.g. owner: "root")
  • group (e.g. group: "wheel")
  • mode (e.g. mode: "2775")
  • seuser - SELinux user (e.g. seuser: "unconfined_u")
  • serole - SELinux role (e.g. serole: "object_r")
  • setype - SELinux type (e.g. setype: "httpd_sys_content_t")
  • selevel - SELinux level (e.g. selevel: "s0")

 

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"

 



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 31df1 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   |