我必须检查/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)
当前回答
我使用这段代码,它可以很好地用于文件夹和文件。只要确保文件夹名称后没有尾随空格即可。如果文件夹存在,则file_exists。Stdout将为true否则它将只是一个空字符串"
- name: check filesystem existence
shell: if [[ -d "/folder_name" ]]; then echo "true"; fi
register: file_exists
- name: debug data
debug:
msg: "Folder exists"
when: file_exists.stdout == "true"
其他回答
vars:
mypath: "/etc/file.txt"
tasks:
- name: checking the file exists
command: touch file.txt
when: mypath is not exists
我使用这段代码,它可以很好地用于文件夹和文件。只要确保文件夹名称后没有尾随空格即可。如果文件夹存在,则file_exists。Stdout将为true否则它将只是一个空字符串"
- name: check filesystem existence
shell: if [[ -d "/folder_name" ]]; then echo "true"; fi
register: file_exists
- name: debug data
debug:
msg: "Folder exists"
when: file_exists.stdout == "true"
通常情况下,您可以使用stat模块来完成此操作。但是命令模块有创建选项,这使得这非常简单:
- name: touch file
command: touch /etc/file.txt
args:
creates: /etc/file.txt
我猜你的触摸命令只是一个例子?最好的做法是不检查任何东西,让ansible用正确的模块完成它的工作。所以如果你想确保文件存在,你可以使用file模块:
- name: make sure file exists
file:
path: /etc/file.txt
state: touch
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
您可以首先检查目标文件是否存在,然后根据其结果的输出做出决定:
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