我必须检查/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这样的特殊变量对于创建测试存在性所需的绝对路径非常有用。
其他回答
通常情况下,您可以使用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
下面是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模块实现,当文件存在时跳过任务。
- 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
关于相对路径的注释,以补充其他答案。
当把基础设施作为代码使用时,我通常使用接受相对路径的角色和任务,特别是对于在这些角色中定义的文件。
像playbook_dir和role_path这样的特殊变量对于创建测试存在性所需的绝对路径非常有用。
你可以使用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