我必须检查文件是否存在/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)
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)
小智 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)
归档时间: |
|
查看次数: |
144781 次 |
最近记录: |