fileansible

How to create an empty file with Ansible?


What is the easiest way to create an empty file using Ansible? I know I can save an empty file into the files directory and then copy it to the remote host, but I find that somewhat unsatisfactory.

Another way is to touch a file on the remote host:

- name: create fake 'nologin' shell
  file: path=/etc/nologin state=touch owner=root group=sys mode=0555

But then the file gets touched every time, showing up as a yellow line in the log, which is also unsatisfactory...

Is there any better solution to this simple problem?


Solution

  • The documentation of the file module says:

    If state=file, the file will NOT be created if it does not exist, see the copy or template module if you want that behavior.

    So we use the copy module, using force: false to create a new empty file only when the file does not yet exist (if the file exists, its content is preserved).

    - name: ensure file exists
      copy:
        content: ""
        dest: /etc/nologin
        force: false
        group: sys
        owner: root
        mode: 0555
    

    This is a declarative and elegant solution.