如何在ansible中检查文件?

E D*_* Sh 96 ansible

我必须检查文件是否存在/etc/.如果该文件存在,那么我必须跳过该任务.这是我正在使用的代码:

- name: checking the file exists
  command: touch file.txt
  when: $(! -s /etc/file.txt)
Run Code Online (Sandbox Code Playgroud)

如果file.txt存在则我必须跳过任务.

Arb*_*zar 157

您可以先检查目标文件是否存在,然后根据其结果输出做出决定.

tasks:
  - name: Check that the somefile.conf exists
    stat:
      path: /etc/file.txt
    register: stat_result

  - name: Create the file, if it doesnt exist already
    file:
      path: /etc/file.txt
      state: touch
    when: stat_result.stat.exists == False 
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你。此外,如果发现你可以写:`when: stat_result.stat.exists == False` 到 `when: not stat_result.stat.exists` 如果你想让它读起来更自然。 (5认同)
  • 如果该目录不存在,那么寄存器 `stat_result` 的 `stat_result.state.exists` 将为 False(这是第二个任务运行的时间)。您可以在此处查看 stat 模块的详细信息:http://docs.ansible.com/ansible/stat_module.html (4认同)
  • 请您使用“not Foo”而不是“Foo == False”吗? (3认同)
  • 除了指定“path”之外,还应该指定“get_checksum: false”、“get_mime: false”和“get_attributes: false”。否则它会默认完成所有额外的工作。 (3认同)
  • 如果目录不存在怎么办? (2认同)

Bru*_*e P 26

统计模块将做到这一点,以及获得许多其他信息的文件.从示例文档:

- stat: path=/path/to/something
  register: p

- debug: msg="Path exists and is a directory"
  when: p.stat.isdir is defined and p.stat.isdir
Run Code Online (Sandbox Code Playgroud)


Raj*_*nna 19

这可以通过stat模块在文件存在时跳过任务来实现.

- hosts: servers
  tasks:
  - name: Ansible check file exists.
    stat:
      path: /etc/issue
    register: p
  - debug:
      msg: "File exists..."
    when: p.stat.exists
  - debug:
      msg: "File not found"
    when: p.stat.exists == False
Run Code Online (Sandbox Code Playgroud)


udo*_*dan 13

通常,您可以使用stat模块执行此操作.但命令模块creates选项,这使得这很简单:

- name: touch file
  command: touch /etc/file.txt
  args:
    creates: /etc/file.txt
Run Code Online (Sandbox Code Playgroud)

我想你的触摸命令只是一个例子?最佳做法是不检查任何内容,让ansible完成其工作 - 使用正确的模块.因此,如果您想确保文件存在,您将使用文件模块:

- name: make sure file exists
  file:
    path: /etc/file.txt
    state: touch
Run Code Online (Sandbox Code Playgroud)

  • 请注意,您可以通过添加“modification_time=preserve access_time=preserve”来使其幂等。这绝对是最紧凑、最符合 Ansible 正确的方法。 (3认同)
  • `state: file` 不创建文件。请参阅 http://docs.ansible.com/ansible/file_module.html (2认同)
  • 我会根据用户问题的具体情况、用户对命令模块的使用以及 ansible 最佳实践,将本答案中的第一个示例视为该问题的正确答案。 (2认同)

小智 7

发现调用速度stat很慢,并且收集了大量文件存在检查不需要的信息。
在花了一些时间寻找解决方案之后,我发现了以下解决方案,它的工作速度要快得多:

- raw: test -e /path/to/something && echo -n true || echo -n false
  register: file_exists

- debug: msg="Path exists"
  when: file_exists.stdout == "true"
Run Code Online (Sandbox Code Playgroud)