如何用Ansible创建一个空文件?

dok*_*par 102 file ansible

使用Ansible创建空文件的最简单方法是什么?我知道我可以将一个空文件保存到files目录中,然后将其复制到远程主机,但我觉得有点不尽如人意.

另一种方法是触摸远程主机上的文件:

- name: create fake 'nologin' shell
  file: path=/etc/nologin state=touch owner=root group=sys mode=0555
Run Code Online (Sandbox Code Playgroud)

但是每次文件都会被触摸,在日志中显示为黄线,这也是令人不满意的......

这个简单的问题有更好的解决方案吗?

Ren*_*ijl 164

文件模块的文档说

如果state=file,如果文件不存在,则不会创建该文件,如果您想要该行为,请参阅副本或模板模块.

因此我们使用复制模块,force=no仅在文件尚不存在时才创建新的空文件(如果文件存在,则保留其内容).

- name: ensure file exists
  copy:
    content: ""
    dest: /etc/nologin
    force: no
    group: sys
    owner: root
    mode: 0555
Run Code Online (Sandbox Code Playgroud)

这是一个声明性和优雅的解决方案.

  • @ÁkosVandra:实际上并没有.见:`force:no`. (15认同)
  • 如果文件已存在,它也会清空该文件 (2认同)
  • @Tasdik Rahman 只需设置 dest: "{{ item }}" ,然后使用 with_items: - /tmp/file1 - /tmp/file2 (2认同)

cee*_*yoz 34

这样的事情(stat首先使用模块收集有关它的数据,然后使用条件过滤)应该工作:

- stat: path=/etc/nologin
  register: p

- name: create fake 'nologin' shell
  file: path=/etc/nologin state=touch owner=root group=sys mode=0555
  when: p.stat.exists is defined and not p.stat.exists
Run Code Online (Sandbox Code Playgroud)

您也可以利用该changed_when功能.

  • 也许它应该是:"何时:不是p.stat.exists" (20认同)

Ley*_*nos 26

另一个选项,使用命令模块:

- name: Create file
  command: touch /path/to/file
  args:
    creates: /path/to/file
Run Code Online (Sandbox Code Playgroud)

'creates'参数确保在文件存在时不执行此操作.

  • @redshark1802 同意。尽管在这种情况下,任务是幂等的,因为如果“/path/to/file”已经存在,它将不会被执行。我认为 René Pijl 的解决方案是三个最佳答案中更像 Ansible 的解决方案,如果您需要设置所有权、模式等,绝对应该使用该解决方案。 (5认同)
  • 你应该尽可能地避免命令,因为它不是幂等的.http://ryaneschinger.com/blog/ensuring-command-module-task-is-repeatable-with-ansible/ (4认同)

Rav*_*rni 14

文件模块提供了在不修改时间的情况下触摸文件的方法。

- name: Touch again the same file, but dont change times this makes the task idempotent
  file:
    path: /etc/foo.conf
    state: touch
    mode: u+rw,g-wx,o-rwx
    modification_time: preserve
    access_time: preserve

Run Code Online (Sandbox Code Playgroud)

参考:https : //docs.ansible.com/ansible/latest/modules/file_module.html


All*_*ckt 13

基于接受的答案,如果您希望在每次运行时检查文件的权限,并且如果文件存在则相应地更改文件,或者只是创建文件(如果文件不存在),您可以使用以下内容:

- 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"}}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案很棒,因为它可以灵活地定义文件的文件属性(如果文件不存在)。 (2认同)

小智 10

file: path=/etc/nologin state=touch

完全相当于触摸(1.4+中的新功能) - 如果您不想更改文件时间戳,请使用stat.

  • 它不是幂等的,文件日期将在ansible剧本的每次执行时进行修改。 (3认同)
  • @JérômeB Ansible 2.7中的新功能:您可以使用`file:path = / etc / nologin state = touch modify_time = preserve access_time = preserve`使它成为幂等。 (2认同)