2016-02-26 14 views
28

Devo verificare se esiste un file in /etc/. Se il file esiste, allora devo saltare l'attività. Ecco il codice che sto usando:Come controllare un file esiste in ansible?

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

Se il file.txt esiste poi devo saltare il compito.

risposta

4

In generale lo si farebbe con lo stat module. Ma la command module ha la possibilità creates che rende questo molto semplice:

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

penso che la comando touch è solo un esempio? La migliore pratica sarebbe quella di non controllare nulla e lasciare che sia ansibile fare il suo lavoro - con il modulo corretto. Quindi, se si vuole garantire il file esiste si può usare il modulo del file:

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

'state: file' non crea file. Vedi http://docs.ansible.com/ansible/file_module.html –

9

Il modulo stat farà questo così come ottenere un sacco di altre informazioni per i file. Dalla documentazione di esempio:

- 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

questa è l'opzione migliore – julestruong

54

È possibile innanzitutto verificare che il file di destinazione esista o meno e quindi prendere una decisione in base all'output del risultato.

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

Cosa succede se la directory non esiste? – ram4nd

+1

Se la directory non esiste, allora il registro 'stat_result' avrà un' stat_result.state.exists' di False (e questo è il momento in cui viene eseguita la seconda attività). Puoi vedere i dettagli del modulo stat qui: http://docs.ansible.com/ansible/stat_module.html – Will

+0

quando: stat_result.stat.exists è definito e stat_result.stat.exists – danday74

1

Questo può essere ottenuto con il modulo stat per saltare l'attività quando il file esiste.

- 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 
Problemi correlati