I am downloading the file with wget
from ansible.
- name: Download Solr
shell: chdir={{project_root}}/solr wget http://mirror.mel.bkb.net.au/pub/apache/lucene/solr/4.7.0/solr-4.7.0.zip
but I only want to do that if zip file does not exist in that location. Currently the system is downloading it every time.
Many modules are already aware of the result and will be skipped if its already there, like
file
orgeturl
. Others likecommand
have acreates
option, which will skip this command if that file already exists (or doesn't exist, if you use theremoves
option).So you should first check the available modules, if they are smart enough already. If not: I recommend the
stats
module. Advantage over the other solution: No "red errors but ignored" in the output.There are at least two options here.
You can register a variable if the file exists, then use a when condition to execute the command on the condition that the file doesn't already exist:
You could also use the commands module with the
creates
option:This article might be useful
Out of it comes this example:
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:
Use the
creates
argumentSo basically you can do this checking by registering a variable from a command and checking its return code. (You can also do this by checking its stdout)
This basically says that if the
/usr/bin/test -e {{project_root}}/solr/solr-4.7.0.zip
command returns a code that is not 0, meaning it doesn't exist then execute the taskDownload Solr
Hope it helps.