我必须检查/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很慢,并且收集了很多文件存在检查不需要的信息。 在花了一些时间寻找解决方案后,我发现了以下解决方案,它的工作速度更快:
- raw: test -e /path/to/something && echo -n true || echo -n false
register: file_exists
- debug: msg="Path exists"
when: file_exists.stdout == "true"
其他回答
我使用这段代码,它可以很好地用于文件夹和文件。只要确保文件夹名称后没有尾随空格即可。如果文件夹存在,则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"
您可以使用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
vars:
mypath: "/etc/file.txt"
tasks:
- name: checking the file exists
command: touch file.txt
when: mypath is not exists
这可以通过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
你可以使用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