我必须检查/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)
当前回答
关于相对路径的注释,以补充其他答案。
当把基础设施作为代码使用时,我通常使用接受相对路径的角色和任务,特别是对于在这些角色中定义的文件。
像playbook_dir和role_path这样的特殊变量对于创建测试存在性所需的绝对路径非常有用。
其他回答
您可以使用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
关于相对路径的注释,以补充其他答案。
当把基础设施作为代码使用时,我通常使用接受相对路径的角色和任务,特别是对于在这些角色中定义的文件。
像playbook_dir和role_path这样的特殊变量对于创建测试存在性所需的绝对路径非常有用。
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
vars:
mypath: "/etc/file.txt"
tasks:
- name: checking the file exists
command: touch file.txt
when: mypath is not exists
你可以使用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