我必須檢查文件是否存在/etc/
。如果文件存在,那麼我必須跳過這個任務。 這裏是我使用的代碼:如何檢查文件是否存在?
- name: checking the file exists
command: touch file.txt
when: $(! -s /etc/file.txt)
如果file.txt
存在,那麼我不得不跳過任務。
我必須檢查文件是否存在/etc/
。如果文件存在,那麼我必須跳過這個任務。 這裏是我使用的代碼:如何檢查文件是否存在?
- name: checking the file exists
command: touch file.txt
when: $(! -s /etc/file.txt)
如果file.txt
存在,那麼我不得不跳過任務。
一般來說,你可以用stat module來做到這一點。但command module有creates
選項,這使得這個非常簡單:
- name: touch file
command: touch /etc/file.txt
args:
creates: /etc/file.txt
我猜你的觸摸命令只是一個例子?最好的做法是不檢查任何東西,讓正確的模塊完成工作。所以,如果你想確保該文件存在,你會使用文件模塊:
- 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
這是更好的選項 – julestruong
您可以先檢查目標文件是否存在,然後根據其結果的輸出做出決定。
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: stat_result.stat.exists == False
這可以通過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
'state:file'不會創建文件。請參閱http://docs.ansible.com/ansible/file_module.html –