2016-02-26 4 views
28

मुझे यह जांचना है कि /etc/ में कोई फ़ाइल मौजूद है या नहीं। अगर फ़ाइल मौजूद है तो मुझे कार्य को छोड़ना होगा।उत्तरदायी में फ़ाइल कैसे जांचती है?

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

file.txt मौजूद है, तो फिर मैं काम को छोड़ने के लिए है: यहाँ कोड मैं का उपयोग कर रहा है।

उत्तर

4

सामान्य रूप से आप इसे stat module के साथ करेंगे।

- name: touch file 
    command: touch /etc/file.txt 
    args: 
    creates: /etc/file.txt 

मुझे लगता है कि अपने स्पर्श आदेश सिर्फ एक उदाहरण है: लेकिन command modulecreates विकल्प जो इस बहुत ही सरल बनाता है? सबसे अच्छा अभ्यास कुछ भी जांचना नहीं होगा और सही मॉड्यूल के साथ जवाब देना चाहिए। यदि आप फ़ाइल सुनिश्चित करना चाहते हैं मौजूद है तो आप फ़ाइल मॉड्यूल का प्रयोग करेंगे:

- name: make sure file exists 
    file: 
    path: /etc/file.txt 
    state: touch 
+1

'राज्य: फ़ाइल' फाइलें नहीं बनाती है। 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' में गलत का' stat_result.state.exists' होगा (और वह दूसरा कार्य चलता है)। आप यहां स्टेट मॉड्यूल का विवरण देख सकते हैं: http://docs.ansible.com/ansible/stat_module.html – Will

+0

जब: stat_result.stat.exists परिभाषित किया गया है और stat_result.stat.exists – danday74

1

यह फ़ाइल मौजूद होने पर कार्य को छोड़ने के लिए स्टेट मॉड्यूल के साथ हासिल किया जा सकता है।

- 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 
संबंधित मुद्दे