Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if file has been downloaded in ansible

Tags:

ansible

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.

like image 553
user1994660 Avatar asked Mar 18 '14 03:03

user1994660


People also ask

How do I view Ansible files?

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.


2 Answers

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 
like image 135
pfalcon Avatar answered Oct 07 '22 17:10

pfalcon


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 
like image 34
DomaNitro Avatar answered Oct 07 '22 16:10

DomaNitro