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.
291 lines
9.4 KiB
Plaintext
291 lines
9.4 KiB
Plaintext
13 years ago
|
#!/usr/bin/python
|
||
12 years ago
|
# -*- coding: utf-8 -*-
|
||
13 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
|
||
13 years ago
|
|
||
|
import shutil
|
||
|
import datetime
|
||
|
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
|
||
|
behaviour can be overriden by setting a variable for this task
|
||
|
(see `setting the environment
|
||
|
<http://ansible.cc/docs/playbooks2.html#setting-the-environment-and-working-with-proxies>`_),
|
||
|
or by using the use_proxy option.
|
||
12 years ago
|
version_added: "0.6"
|
||
|
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.
|
||
12 years ago
|
- If I(dest) is a directory, the basename of the file on the remote server will be used. If a directory, C(force=yes) must also be set.
|
||
12 years ago
|
required: true
|
||
|
default: null
|
||
12 years ago
|
force:
|
||
12 years ago
|
description:
|
||
|
- if C(yes), will download the file every time and replace the
|
||
12 years ago
|
file if the contents change. If C(no), the file will only be downloaded if
|
||
12 years ago
|
the destination does not exist. Generally should be C(yes) only for small
|
||
|
local files. prior to 0.6, acts if C(yes) by default.
|
||
|
version_added: "0.7"
|
||
|
required: false
|
||
|
choices: [ "yes", "no" ]
|
||
|
default: "no"
|
||
12 years ago
|
aliases: [ "thirsty" ]
|
||
12 years ago
|
use_proxy:
|
||
|
description:
|
||
12 years ago
|
- if C(no), it will not use a proxy, even if one is defined by
|
||
12 years ago
|
in an environment variable on the target hosts.
|
||
12 years ago
|
required: false
|
||
|
default: yes
|
||
|
choices: [yes, no]
|
||
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
|
get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf mode=0440
|
||
12 years ago
|
'''
|
||
|
|
||
|
|
||
12 years ago
|
HAS_URLLIB2 = True
|
||
13 years ago
|
try:
|
||
|
import urllib2
|
||
12 years ago
|
except ImportError:
|
||
12 years ago
|
HAS_URLLIB2 = False
|
||
|
HAS_URLPARSE = True
|
||
12 years ago
|
|
||
13 years ago
|
try:
|
||
|
import urlparse
|
||
|
import socket
|
||
12 years ago
|
except ImportError:
|
||
13 years ago
|
HAS_URLPARSE=False
|
||
|
|
||
|
# ==============================================================
|
||
|
# url handling
|
||
|
|
||
|
def url_filename(url):
|
||
12 years ago
|
fn = os.path.basename(urlparse.urlsplit(url)[2])
|
||
|
if fn == '':
|
||
|
return 'index.html'
|
||
|
return fn
|
||
13 years ago
|
|
||
12 years ago
|
def url_do_get(module, url, dest, use_proxy):
|
||
12 years ago
|
"""
|
||
|
Get url and return request and info
|
||
|
Credits: http://stackoverflow.com/questions/7006574/how-to-download-file-from-ftp
|
||
13 years ago
|
"""
|
||
12 years ago
|
|
||
13 years ago
|
USERAGENT = 'ansible-httpget'
|
||
12 years ago
|
info = dict(url=url, dest=dest)
|
||
13 years ago
|
r = None
|
||
12 years ago
|
handlers = []
|
||
|
|
||
12 years ago
|
parsed = urlparse.urlparse(url)
|
||
12 years ago
|
|
||
12 years ago
|
if '@' in parsed[1]:
|
||
|
credentials, netloc = parsed[1].split('@', 1)
|
||
12 years ago
|
if ':' in credentials:
|
||
12 years ago
|
username, password = credentials.split(':', 1)
|
||
|
else:
|
||
|
username = credentials
|
||
|
password = ''
|
||
12 years ago
|
parsed = list(parsed)
|
||
|
parsed[1] = netloc
|
||
|
|
||
|
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
|
||
|
# this creates a password manager
|
||
|
passman.add_password(None, netloc, username, password)
|
||
|
# because we have put None at the start it will always
|
||
|
# use this username/password combination for urls
|
||
|
# for which `theurl` is a super-url
|
||
|
|
||
|
authhandler = urllib2.HTTPBasicAuthHandler(passman)
|
||
|
# create the AuthHandler
|
||
12 years ago
|
handlers.append(authhandler)
|
||
12 years ago
|
|
||
|
#reconstruct url without credentials
|
||
|
url = urlparse.urlunparse(parsed)
|
||
13 years ago
|
|
||
12 years ago
|
if not use_proxy:
|
||
|
proxyhandler = urllib2.ProxyHandler({})
|
||
|
handlers.append(proxyhandler)
|
||
|
|
||
|
opener = urllib2.build_opener(*handlers)
|
||
|
urllib2.install_opener(opener)
|
||
13 years ago
|
request = urllib2.Request(url)
|
||
|
request.add_header('User-agent', USERAGENT)
|
||
|
|
||
12 years ago
|
if os.path.exists(dest) and not module.params['force']:
|
||
12 years ago
|
t = datetime.datetime.utcfromtimestamp(os.path.getmtime(dest))
|
||
13 years ago
|
tstamp = t.strftime('%a, %d %b %Y %H:%M:%S +0000')
|
||
|
request.add_header('If-Modified-Since', tstamp)
|
||
|
|
||
|
try:
|
||
|
r = urllib2.urlopen(request)
|
||
12 years ago
|
info.update(r.info())
|
||
|
info.update(dict(msg="OK (%s bytes)" % r.headers.get('Content-Length', 'unknown'), status=200))
|
||
12 years ago
|
except urllib2.HTTPError, e:
|
||
13 years ago
|
# Must not fail_json() here so caller can handle HTTP 304 unmodified
|
||
12 years ago
|
info.update(dict(msg=str(e), status=e.code))
|
||
13 years ago
|
return r, info
|
||
12 years ago
|
except urllib2.URLError, e:
|
||
12 years ago
|
code = getattr(e, 'code', -1)
|
||
|
module.fail_json(msg="Request failed: %s" % str(e), status_code=code)
|
||
13 years ago
|
|
||
|
return r, info
|
||
|
|
||
12 years ago
|
def url_get(module, url, dest, use_proxy):
|
||
12 years ago
|
"""
|
||
12 years ago
|
Download url and store at dest.
|
||
12 years ago
|
If dest is a directory, determine filename from url.
|
||
|
Return (tempfile, info about the request)
|
||
13 years ago
|
"""
|
||
|
|
||
12 years ago
|
req, info = url_do_get(module, url, dest, use_proxy)
|
||
13 years ago
|
|
||
12 years ago
|
# TODO: should really handle 304, but how? src file could exist (and be newer) but empty
|
||
13 years ago
|
if info['status'] == 304:
|
||
12 years ago
|
module.exit_json(url=url, dest=dest, changed=False, msg=info.get('msg', ''))
|
||
13 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:
|
||
|
shutil.copyfileobj(req, f)
|
||
|
except Exception, err:
|
||
|
os.remove(tempname)
|
||
|
module.fail_json(msg="failed to create temporary content file: %s" % str(err))
|
||
|
f.close()
|
||
|
req.close()
|
||
|
return tempname, info
|
||
13 years ago
|
|
||
|
# ==============================================================
|
||
|
# main
|
||
|
|
||
|
def main():
|
||
12 years ago
|
|
||
|
# does this really happen on non-ancient python?
|
||
12 years ago
|
if not HAS_URLLIB2:
|
||
|
module.fail_json(msg="urllib2 is not installed")
|
||
|
if not HAS_URLPARSE:
|
||
|
module.fail_json(msg="urlparse is not installed")
|
||
|
|
||
13 years ago
|
module = AnsibleModule(
|
||
12 years ago
|
# not checking because of daisy chain to file module
|
||
13 years ago
|
argument_spec = dict(
|
||
|
url = dict(required=True),
|
||
|
dest = dict(required=True),
|
||
12 years ago
|
force = dict(default='no', aliases=['thirsty'], type='bool'),
|
||
|
use_proxy = dict(default='yes', type='bool')
|
||
12 years ago
|
),
|
||
|
add_file_common_args=True
|
||
13 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
|
use_proxy = module.params['use_proxy']
|
||
12 years ago
|
|
||
12 years ago
|
if os.path.isdir(dest):
|
||
|
dest = os.path.join(dest, url_filename(url))
|
||
|
|
||
12 years ago
|
if not force:
|
||
12 years ago
|
if os.path.exists(dest):
|
||
12 years ago
|
module.exit_json(msg="file already exists", dest=dest, url=url, changed=False)
|
||
12 years ago
|
|
||
12 years ago
|
# download to tmpsrc
|
||
12 years ago
|
tmpsrc, info = url_get(module, url, dest, use_proxy)
|
||
12 years ago
|
md5sum_src = None
|
||
|
md5sum_dest = None
|
||
12 years ago
|
|
||
13 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
|
|
||
13 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)
|
||
13 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
|
|
||
13 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)))
|
||
13 years ago
|
changed = True
|
||
|
else:
|
||
|
changed = False
|
||
12 years ago
|
|
||
13 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
|
||
|
changed = module.set_file_attributes_if_different(file_args, changed)
|
||
|
|
||
12 years ago
|
# Mission complete
|
||
12 years ago
|
module.exit_json(url=url, dest=dest, src=tmpsrc, md5sum=md5sum_src,
|
||
12 years ago
|
changed=changed, msg=info.get('msg', ''))
|
||
13 years ago
|
|
||
|
# this is magic, see lib/ansible/module_common.py
|
||
|
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
|
||
|
main()
|