2016-02-26 241 views
28

我必須檢查文件是否存在/etc/。如果文件存在,那麼我必須跳過這個任務。 這裏是我使用的代碼:如何檢查文件是否存在?

- name: checking the file exists 
    command: touch file.txt 
    when: $(! -s /etc/file.txt) 

如果file.txt存在,那麼我不得不跳過任務。

回答

4

一般來說,你可以用stat module來做到這一點。但command modulecreates選項,這使得這個非常簡單:

- 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 
+1

'state:file'不會創建文件。請參閱http://docs.ansible.com/ansible/file_module.html –

9

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 
+0

這是更好的選項 – julestruong

54

您可以先檢查目標文件是否存在,然後根據其結果的輸出做出決定。

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 
+0

如果該目錄不存在,該怎麼辦? – ram4nd

+1

如果該目錄不存在,則寄存器'stat_result'將具有False的「stat_result.state.exists」(並且在第二個任務運行時)。您可以在此處查看stat模塊的詳細信息:http://docs.ansible.com/ansible/stat_module.html – Will

+0

when:stat_result.stat.exists is defined and stat_result.stat.exists – danday74

1

這可以通過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