I am downloading the file with wget
from ansible.
- name: Download Solr shell: wget http://mirror.mel.bkb.net.au/pub/apache/lucene/solr/4.7.0/solr-4.7.0.zip args: chdir: {{project_root}}/solr
but I only want to do that if zip file does not exist in that location. Currently the system is downloading it every time.
To check whether the destination file exists and then run tasks based on its status, we can use the Ansible's stat module (or win_stat for Windows targets). With this module we can identify not only whether the destination path exists or not but also if it is a regular file, a directory or a symbolic link.
Note: this answer covers general question of "How can i check the file existence in ansible", not a specific case of downloading file.
The problems with the previous answers using "command" or "shell" actions is that they won't work in --check mode. Actually, first action will be skipped, and next will error out on "when: solr_exists.rc != 0" condition (due to variable not being defined).
Since Ansible 1.3, there's more direct way to check for file existance - using "stat" module. It of course also works well as "local_action" to check a local file existence:
- local_action: stat path={{secrets_dir}}/secrets.yml register: secrets_exist - fail: msg="Production credentials not found" when: secrets_exist.stat.exists == False
Unless you have a reason to use wget
why not use get_url
module. It will check if the file needs to be downloaded.
--- - hosts : all gather_facts : no tasks: - get_url: url="http://mirror.mel.bkb.net.au/pub/apache/lucene/solr/4.7.0/solr-4.7.0.zip" dest="{{project_root}}/solr-4.7.0.zip"
NOTE: If you put the directory and not the full path in the dest
ansible will still download the file to a temporary dir but do an md5 check to decide whether to copy to the dest dir.
And if you need to save state of download you can use:
--- - hosts : all gather_facts : no tasks: - get_url: url="http://mirror.mel.bkb.net.au/pub/apache/lucene/solr/4.7.0/solr-4.7.0.zip" dest="{{project_root}}/solr-4.7.0.zip" register: get_solr - debug: msg="solr was downloaded" when: get_solr|changed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With