我必须检查/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)
当前回答
下面是ansible play,我用来删除文件,如果文件存在于操作系统端。
- name: find out /etc/init.d/splunk file exists or not'
stat:
path: /etc/init.d/splunk
register: splunkresult
tags:
- always
- name: 'Remove splunk from init.d file if splunk already running'
file:
path: /etc/init.d/splunk
state: absent
when: splunkresult.stat.exists == true
ignore_errors: yes
tags:
- always
我使用的发挥条件如下
when: splunkresult.stat.exists == true --> Remove the file
你可以根据你的要求给出真/假
when: splunkresult.stat.exists == false
when: splunkresult.stat.exists == true
其他回答
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
这可以通过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
发现调用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"
您可以首先检查目标文件是否存在,然后根据其结果的输出做出决定:
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
您可以使用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