2016-02-26 10 views
28

Muszę sprawdzić, czy plik istnieje w /etc/. Jeśli plik istnieje, muszę pominąć zadanie. Oto kod używam:Jak sprawdzić, czy plik istnieje w ansibla?

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

Jeśli file.txt istnieje wtedy muszę pominąć zadanie.

Odpowiedz

4

Ogólnie można to zrobić z stat module. Ale command module ma możliwość creates który sprawia, że ​​to bardzo proste:

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

Chyba twoja komenda dotykowy jest tylko przykładem? Najlepszą praktyką byłoby nie sprawdzanie czegokolwiek i pozwolić ansibli wykonywać swoją pracę - z odpowiednim modułem. Więc jeśli chcesz, aby upewnić się, że plik istnieje byłoby użyć modułu pliku:

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

'stan: plik' nie tworzy plików. Zobacz http://docs.ansible.com/ansible/file_module.html –

9

Moduł stat będzie to zrobić, a także uzyskać wiele innych informacji o plikach. Z przykładowej dokumentacji:

- 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

to jest lepsza opcja. – julestruong

54

Najpierw sprawdź, czy plik docelowy istnieje, a następnie podejmij decyzję na podstawie wyniku jego działania.

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

Co zrobić, jeśli katalog nie istnieje? – ram4nd

+1

Jeśli katalog nie istnieje, wówczas rejestr 'stat_result' będzie miał' stat_result.state.exists' of False (i to wtedy, gdy uruchomi się drugie zadanie). Możesz zobaczyć szczegóły modułu stat tutaj: http://docs.ansible.com/ansible/stat_module.html – Will

+0

kiedy: stat_result.stat.exists jest zdefiniowany i stat_result.stat.exists – danday74

1

Można to osiągnąć za pomocą modułu stat, aby pominąć zadanie, gdy plik istnieje.

- 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 
Powiązane problemy