How to create an empty file with Ansible?

后端 未结 10 756
傲寒
傲寒 2021-01-31 12:53

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 f

相关标签:
10条回答
  • 2021-01-31 13:41

    Building on the accepted answer, if you want the file to be checked for permissions on every run, and these changed accordingly if the file exists, or just create the file if it doesn't exist, you can use the following:

    - stat: path=/etc/nologin
      register: p
    
    - name: create fake 'nologin' shell
      file: path=/etc/nologin 
            owner=root
            group=sys
            mode=0555
            state={{ "file" if  p.stat.exists else "touch"}}
    
    0 讨论(0)
  • 2021-01-31 13:41

    Changed if file not exists. Create empty file.

    - name: create fake 'nologin' shell
      file:
        path: /etc/nologin
        state: touch
      register: p
      changed_when: p.diff.before.state == "absent"
    
    0 讨论(0)
  • 2021-01-31 13:45

    Turns out I don't have enough reputation to put this as a comment, which would be a more appropriate place for this:

    Re. AllBlackt's answer, if you prefer Ansible's multiline format you need to adjust the quoting for state (I spent a few minutes working this out, so hopefully this speeds someone else up),

    - stat:
        path: "/etc/nologin"
      register: p
    
    - name: create fake 'nologin' shell
      file:
        path: "/etc/nologin"
        owner: root
        group: sys
        mode: 0555
        state: '{{ "file" if  p.stat.exists else "touch" }}'
    
    0 讨论(0)
  • 2021-01-31 13:48

    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=no 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: no
        group: sys
        owner: root
        mode: 0555
    

    This is a declarative and elegant solution.

    0 讨论(0)
提交回复
热议问题