summaryrefslogtreecommitdiff
path: root/library/copy
blob: a5aef64cd5e49ecaba3a34d886f253bfd42952cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/python
# -*- coding: utf-8 -*-

# (c) 2012, Michael DeHaan <michael.dehaan@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/>.

import os
import shutil

def main():

    module = AnsibleModule(
        # not checking because of daisy chain to file module
        check_invalid_arguments = False,
        argument_spec = dict(
            src=dict(required=True),
            dest=dict(required=True)
        )
    ) 

    src  = os.path.expanduser(module.params['src'])
    dest = os.path.expanduser(module.params['dest'])

    if not os.path.exists(src):
        module.fail_json(msg="Source %s failed to transfer" % (src))
    if not os.access(src, os.R_OK):
        module.fail_json(msg="Source %s not readable" % (src))

    md5sum_src = module.md5(src)
    md5sum_dest = None

    if os.path.exists(dest):
        if not os.access(dest, os.W_OK):
            module.fail_json(msg="Destination %s not writable" % (dest))
        if not os.access(dest, os.R_OK):
            module.fail_json(msg="Destination %s not readable" % (dest))
        # Allow dest to be directory without compromising md5 check
        if (os.path.isdir(dest)):
            module.fail_json(msg="Destination %s cannot be a directory" % (dest))
        md5sum_dest = module.md5(dest)
    else:
        if not os.access(os.path.dirname(dest), os.W_OK):
            module.fail_json(msg="Destination %s not writable" % (os.path.dirname(dest)))

    if md5sum_src != md5sum_dest:
        try:
            shutil.copyfile(src, dest)
        except shutil.Error:
            module.fail_json(msg="failed to copy: %s and %s are the same" % (src, dest)) 
        except IOError:
            module.fail_json(msg="failed to copy: %s to %s" % (src, dest)) 
        changed = True
    else:
        changed = False

    module.exit_json(dest=dest, src=src, md5sum=md5sum_src, changed=changed)

# this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
main()