mirror of https://github.com/ansible/ansible.git
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
314 lines
11 KiB
Python
314 lines
11 KiB
Python
12 years ago
|
#!/usr/bin/python
|
||
12 years ago
|
# -*- coding: utf-8 -*-
|
||
12 years ago
|
|
||
|
# (c) 2012, Jan-Piet Mens <jpmens () gmail.com>
|
||
|
#
|
||
|
# This file is part of Ansible
|
||
|
#
|
||
|
# Ansible is free software: you can redistribute it and/or modify
|
||
|
# it under the terms of the GNU General Public License as published by
|
||
|
# the Free Software Foundation, either version 3 of the License, or
|
||
|
# (at your option) any later version.
|
||
|
#
|
||
|
# Ansible is distributed in the hope that it will be useful,
|
||
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||
|
# GNU General Public License for more details.
|
||
|
#
|
||
|
# You should have received a copy of the GNU General Public License
|
||
|
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
||
|
#
|
||
12 years ago
|
# see examples/playbooks/get_url.yml
|
||
12 years ago
|
|
||
|
import shutil
|
||
|
import datetime
|
||
11 years ago
|
import re
|
||
12 years ago
|
import tempfile
|
||
|
|
||
12 years ago
|
DOCUMENTATION = '''
|
||
|
---
|
||
|
module: get_url
|
||
|
short_description: Downloads files from HTTP, HTTPS, or FTP to node
|
||
12 years ago
|
description:
|
||
|
- Downloads files from HTTP, HTTPS, or FTP to the remote server. The remote
|
||
12 years ago
|
server I(must) have direct access to the remote resource.
|
||
12 years ago
|
- By default, if an environment variable C(<protocol>_proxy) is set on
|
||
|
the target host, requests will be sent through that proxy. This
|
||
12 years ago
|
behaviour can be overridden by setting a variable for this task
|
||
12 years ago
|
(see `setting the environment
|
||
11 years ago
|
<http://docs.ansible.com/playbooks_environment.html>`_),
|
||
12 years ago
|
or by using the use_proxy option.
|
||
11 years ago
|
version_added: "0.6"
|
||
12 years ago
|
options:
|
||
12 years ago
|
url:
|
||
|
description:
|
||
12 years ago
|
- HTTP, HTTPS, or FTP URL in the form (http|https|ftp)://[user[:pass]]@host.domain[:port]/path
|
||
12 years ago
|
required: true
|
||
|
default: null
|
||
|
aliases: []
|
||
|
dest:
|
||
|
description:
|
||
|
- absolute path of where to download the file to.
|
||
11 years ago
|
- If C(dest) is a directory, either the server provided filename or, if
|
||
|
none provided, the base name of the URL on the remote server will be
|
||
|
used. If a directory, C(force) has no effect.
|
||
11 years ago
|
If C(dest) is a directory, the file will always be
|
||
|
downloaded (regardless of the force option), but replaced only if the contents changed.
|
||
12 years ago
|
required: true
|
||
|
default: null
|
||
12 years ago
|
force:
|
||
12 years ago
|
description:
|
||
11 years ago
|
- If C(yes) and C(dest) is not a directory, will download the file every
|
||
|
time and replace the file if the contents change. If C(no), the file
|
||
|
will only be downloaded if the destination does not exist. Generally
|
||
|
should be C(yes) only for small local files. Prior to 0.6, this module
|
||
|
behaved as if C(yes) was the default.
|
||
12 years ago
|
version_added: "0.7"
|
||
|
required: false
|
||
|
choices: [ "yes", "no" ]
|
||
|
default: "no"
|
||
12 years ago
|
aliases: [ "thirsty" ]
|
||
12 years ago
|
sha256sum:
|
||
|
description:
|
||
|
- If a SHA-256 checksum is passed to this parameter, the digest of the
|
||
|
destination file will be calculated after it is downloaded to ensure
|
||
|
its integrity and verify that the transfer completed successfully.
|
||
12 years ago
|
version_added: "1.3"
|
||
12 years ago
|
required: false
|
||
|
default: null
|
||
12 years ago
|
use_proxy:
|
||
|
description:
|
||
12 years ago
|
- if C(no), it will not use a proxy, even if one is defined in
|
||
|
an environment variable on the target hosts.
|
||
12 years ago
|
required: false
|
||
12 years ago
|
default: 'yes'
|
||
|
choices: ['yes', 'no']
|
||
11 years ago
|
validate_certs:
|
||
|
description:
|
||
|
- If C(no), SSL certificates will not be validated. This should only be used
|
||
|
on personally controlled sites using self-signed certificates.
|
||
|
required: false
|
||
|
default: 'yes'
|
||
|
choices: ['yes', 'no']
|
||
10 years ago
|
timeout:
|
||
|
description:
|
||
|
- Timeout for URL request
|
||
|
required: false
|
||
|
default: 10
|
||
|
version_added: '1.8'
|
||
11 years ago
|
url_username:
|
||
|
description:
|
||
|
- The username for use in HTTP basic authentication. This parameter can be used
|
||
|
without C(url_password) for sites that allow empty passwords.
|
||
|
required: false
|
||
|
version_added: '1.6'
|
||
|
url_password:
|
||
|
description:
|
||
|
- The password for use in HTTP basic authentication. If the C(url_username)
|
||
|
parameter is not specified, the C(url_password) parameter will not be used.
|
||
|
required: false
|
||
|
version_added: '1.6'
|
||
12 years ago
|
others:
|
||
|
description:
|
||
|
- all arguments accepted by the M(file) module also work here
|
||
|
required: false
|
||
12 years ago
|
notes:
|
||
12 years ago
|
- This module doesn't yet support configuration for proxies.
|
||
12 years ago
|
# informational: requirements for nodes
|
||
|
requirements: [ urllib2, urlparse ]
|
||
12 years ago
|
author: Jan-Piet Mens
|
||
12 years ago
|
'''
|
||
|
|
||
12 years ago
|
EXAMPLES='''
|
||
12 years ago
|
- name: download foo.conf
|
||
|
get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf mode=0440
|
||
12 years ago
|
|
||
12 years ago
|
- name: download file with sha256 check
|
||
|
get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf sha256sum=b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c
|
||
12 years ago
|
'''
|
||
|
|
||
12 years ago
|
try:
|
||
|
import hashlib
|
||
|
HAS_HASHLIB=True
|
||
|
except ImportError:
|
||
|
HAS_HASHLIB=False
|
||
12 years ago
|
|
||
12 years ago
|
# ==============================================================
|
||
|
# url handling
|
||
|
|
||
|
def url_filename(url):
|
||
12 years ago
|
fn = os.path.basename(urlparse.urlsplit(url)[2])
|
||
|
if fn == '':
|
||
|
return 'index.html'
|
||
|
return fn
|
||
12 years ago
|
|
||
10 years ago
|
def url_get(module, url, dest, use_proxy, last_mod_time, force, timeout=10):
|
||
12 years ago
|
"""
|
||
11 years ago
|
Download data from the url and store in a temporary file.
|
||
|
|
||
12 years ago
|
Return (tempfile, info about the request)
|
||
12 years ago
|
"""
|
||
|
|
||
10 years ago
|
rsp, info = fetch_url(module, url, use_proxy=use_proxy, force=force, last_mod_time=last_mod_time, timeout=timeout)
|
||
12 years ago
|
|
||
|
if info['status'] == 304:
|
||
12 years ago
|
module.exit_json(url=url, dest=dest, changed=False, msg=info.get('msg', ''))
|
||
12 years ago
|
|
||
12 years ago
|
# create a temporary file and copy content to do md5-based replacement
|
||
|
if info['status'] != 200:
|
||
12 years ago
|
module.fail_json(msg="Request failed", status_code=info['status'], response=info['msg'], url=url, dest=dest)
|
||
12 years ago
|
|
||
|
fd, tempname = tempfile.mkstemp()
|
||
|
f = os.fdopen(fd, 'wb')
|
||
|
try:
|
||
11 years ago
|
shutil.copyfileobj(rsp, f)
|
||
12 years ago
|
except Exception, err:
|
||
|
os.remove(tempname)
|
||
|
module.fail_json(msg="failed to create temporary content file: %s" % str(err))
|
||
|
f.close()
|
||
11 years ago
|
rsp.close()
|
||
12 years ago
|
return tempname, info
|
||
12 years ago
|
|
||
11 years ago
|
def extract_filename_from_headers(headers):
|
||
|
"""
|
||
|
Extracts a filename from the given dict of HTTP headers.
|
||
|
|
||
|
Looks for the content-disposition header and applies a regex.
|
||
|
Returns the filename if successful, else None."""
|
||
10 years ago
|
cont_disp_regex = 'attachment; ?filename="?([^"]+)'
|
||
11 years ago
|
res = None
|
||
|
|
||
|
if 'content-disposition' in headers:
|
||
|
cont_disp = headers['content-disposition']
|
||
|
match = re.match(cont_disp_regex, cont_disp)
|
||
|
if match:
|
||
|
res = match.group(1)
|
||
|
# Try preventing any funny business.
|
||
|
res = os.path.basename(res)
|
||
|
|
||
|
return res
|
||
|
|
||
12 years ago
|
# ==============================================================
|
||
|
# main
|
||
|
|
||
|
def main():
|
||
12 years ago
|
|
||
11 years ago
|
argument_spec = url_argument_spec()
|
||
|
argument_spec.update(
|
||
11 years ago
|
url = dict(required=True),
|
||
11 years ago
|
dest = dict(required=True),
|
||
|
sha256sum = dict(default=''),
|
||
10 years ago
|
timeout = dict(required=False, type='int', default=10),
|
||
11 years ago
|
)
|
||
12 years ago
|
|
||
12 years ago
|
module = AnsibleModule(
|
||
12 years ago
|
# not checking because of daisy chain to file module
|
||
11 years ago
|
argument_spec = argument_spec,
|
||
12 years ago
|
add_file_common_args=True
|
||
12 years ago
|
)
|
||
12 years ago
|
|
||
12 years ago
|
url = module.params['url']
|
||
|
dest = os.path.expanduser(module.params['dest'])
|
||
12 years ago
|
force = module.params['force']
|
||
12 years ago
|
sha256sum = module.params['sha256sum']
|
||
12 years ago
|
use_proxy = module.params['use_proxy']
|
||
10 years ago
|
timeout = module.params['timeout']
|
||
12 years ago
|
|
||
11 years ago
|
dest_is_dir = os.path.isdir(dest)
|
||
|
last_mod_time = None
|
||
12 years ago
|
|
||
11 years ago
|
if not dest_is_dir and os.path.exists(dest):
|
||
|
if not force:
|
||
12 years ago
|
module.exit_json(msg="file already exists", dest=dest, url=url, changed=False)
|
||
12 years ago
|
|
||
11 years ago
|
# If the file already exists, prepare the last modified time for the
|
||
|
# request.
|
||
|
mtime = os.path.getmtime(dest)
|
||
|
last_mod_time = datetime.datetime.utcfromtimestamp(mtime)
|
||
|
|
||
12 years ago
|
# download to tmpsrc
|
||
10 years ago
|
tmpsrc, info = url_get(module, url, dest, use_proxy, last_mod_time, force, timeout)
|
||
11 years ago
|
|
||
|
# Now the request has completed, we can finally generate the final
|
||
|
# destination file name from the info dict.
|
||
11 years ago
|
|
||
11 years ago
|
if dest_is_dir:
|
||
|
filename = extract_filename_from_headers(info)
|
||
|
if not filename:
|
||
|
# Fall back to extracting the filename from the URL.
|
||
11 years ago
|
# Pluck the URL from the info, since a redirect could have changed
|
||
|
# it.
|
||
|
filename = url_filename(info['url'])
|
||
11 years ago
|
dest = os.path.join(dest, filename)
|
||
|
|
||
12 years ago
|
md5sum_src = None
|
||
|
md5sum_dest = None
|
||
12 years ago
|
|
||
12 years ago
|
# raise an error if there is no tmpsrc file
|
||
|
if not os.path.exists(tmpsrc):
|
||
|
os.remove(tmpsrc)
|
||
|
module.fail_json(msg="Request failed", status_code=info['status'], response=info['msg'])
|
||
|
if not os.access(tmpsrc, os.R_OK):
|
||
|
os.remove(tmpsrc)
|
||
|
module.fail_json( msg="Source %s not readable" % (tmpsrc))
|
||
12 years ago
|
md5sum_src = module.md5(tmpsrc)
|
||
12 years ago
|
|
||
12 years ago
|
# check if there is no dest file
|
||
|
if os.path.exists(dest):
|
||
|
# raise an error if copy has no permission on dest
|
||
|
if not os.access(dest, os.W_OK):
|
||
|
os.remove(tmpsrc)
|
||
|
module.fail_json( msg="Destination %s not writable" % (dest))
|
||
|
if not os.access(dest, os.R_OK):
|
||
|
os.remove(tmpsrc)
|
||
|
module.fail_json( msg="Destination %s not readable" % (dest))
|
||
12 years ago
|
md5sum_dest = module.md5(dest)
|
||
12 years ago
|
else:
|
||
|
if not os.access(os.path.dirname(dest), os.W_OK):
|
||
|
os.remove(tmpsrc)
|
||
|
module.fail_json( msg="Destination %s not writable" % (os.path.dirname(dest)))
|
||
12 years ago
|
|
||
12 years ago
|
if md5sum_src != md5sum_dest:
|
||
|
try:
|
||
|
shutil.copyfile(tmpsrc, dest)
|
||
|
except Exception, err:
|
||
|
os.remove(tmpsrc)
|
||
12 years ago
|
module.fail_json(msg="failed to copy %s to %s: %s" % (tmpsrc, dest, str(err)))
|
||
12 years ago
|
changed = True
|
||
|
else:
|
||
|
changed = False
|
||
12 years ago
|
|
||
11 years ago
|
# Check the digest of the destination file and ensure that it matches the
|
||
12 years ago
|
# sha256sum parameter if it is present
|
||
|
if sha256sum != '':
|
||
11 years ago
|
# Remove any non-alphanumeric characters, including the infamous
|
||
|
# Unicode zero-width space
|
||
|
stripped_sha256sum = re.sub(r'\W+', '', sha256sum)
|
||
|
|
||
12 years ago
|
if not HAS_HASHLIB:
|
||
|
os.remove(dest)
|
||
|
module.fail_json(msg="The sha256sum parameter requires hashlib, which is available in Python 2.5 and higher")
|
||
11 years ago
|
else:
|
||
|
destination_checksum = module.sha256(dest)
|
||
|
|
||
11 years ago
|
if stripped_sha256sum.lower() != destination_checksum:
|
||
12 years ago
|
os.remove(dest)
|
||
11 years ago
|
module.fail_json(msg="The SHA-256 checksum for %s did not match %s; it was %s." % (dest, sha256sum, destination_checksum))
|
||
12 years ago
|
|
||
12 years ago
|
os.remove(tmpsrc)
|
||
12 years ago
|
|
||
12 years ago
|
# allow file attribute changes
|
||
|
module.params['path'] = dest
|
||
|
file_args = module.load_file_common_arguments(module.params)
|
||
|
file_args['path'] = dest
|
||
11 years ago
|
changed = module.set_fs_attributes_if_different(file_args, changed)
|
||
12 years ago
|
|
||
12 years ago
|
# Mission complete
|
||
12 years ago
|
module.exit_json(url=url, dest=dest, src=tmpsrc, md5sum=md5sum_src,
|
||
12 years ago
|
sha256sum=sha256sum, changed=changed, msg=info.get('msg', ''))
|
||
12 years ago
|
|
||
11 years ago
|
# import module snippets
|
||
11 years ago
|
from ansible.module_utils.basic import *
|
||
11 years ago
|
from ansible.module_utils.urls import *
|
||
12 years ago
|
main()
|