我必须检查/etc/中是否存在一个文件。如果文件存在,那么我必须跳过该任务。 这是我正在使用的代码:
- name: checking the file exists
command: touch file.txt
when: $(! -s /etc/file.txt)
我必须检查/etc/中是否存在一个文件。如果文件存在,那么我必须跳过该任务。 这是我正在使用的代码:
- name: checking the file exists
command: touch file.txt
when: $(! -s /etc/file.txt)
当前回答
stat模块将执行此操作,并为文件获取许多其他信息。从示例文档中:
- 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
其他回答
您可以使用shell命令检查文件是否存在
- set_fact:
file: "/tmp/test_file"
- name: check file exists
shell: "ls {{ file }}"
register: file_path
ignore_errors: true
- name: create file if don't exist
shell: "touch {{ file }}"
when: file_path.rc != 0
你可以使用Ansible的统计模块来注册文件,当模块来应用条件。
- name: Register file
stat:
path: "/tmp/test_file"
register: file_path
- name: Create file if it doesn't exists
file:
path: "/tmp/test_file"
state: touch
when: file_path.stat.exists == False
我发现这样做很烦人,而且容易出错。存在类型检查。例如,它们需要额外的注意才能使检查模式(——check)工作。
这里的许多答案表明
获取和注册 当寄存器表达式为真时应用
然而,有时这是一种代码气味,所以总是寻找更好的方法来使用Ansible,特别是使用正确的模块有许多优点。如。
- name: install ntpdate
package:
name: ntpdate
or
- file:
path: /etc/file.txt
owner: root
group: root
mode: 0644
但是当不能使用一个模块时,也要研究一下是否可以注册和检查前一个任务的结果。如。
# jmeter_version: 4.0
- name: Download Jmeter archive
get_url:
url: "http://archive.apache.org/dist/jmeter/binaries/apache-jmeter-{{ jmeter_version }}.tgz"
dest: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}.tgz"
checksum: sha512:eee7d68bd1f7e7b269fabaf8f09821697165518b112a979a25c5f128c4de8ca6ad12d3b20cd9380a2b53ca52762b4c4979e564a8c2ff37196692fbd217f1e343
register: download_result
- name: Extract apache-jmeter
unarchive:
src: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}.tgz"
dest: "/opt/jmeter/"
remote_src: yes
creates: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}"
when: download_result.state == 'file'
注意when:和created: so——check不会出错
我之所以提到这一点,是因为这些不太理想的做法通常是成对出现的,即没有apt/yum包,所以我们必须1)下载和2)解压缩
希望这能有所帮助
您可以首先检查目标文件是否存在,然后根据其结果的输出做出决定:
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: not stat_result.stat.exists
stat模块将执行此操作,并为文件获取许多其他信息。从示例文档中:
- 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