| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright: (c) 2012, Michael DeHaan <[email protected]> |
| 4 |
# Copyright: (c) 2017, Ansible Project |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
|
| 10 |
DOCUMENTATION = r""" |
| 11 |
--- |
| 12 |
module: copy |
| 13 |
version_added: historical |
| 14 |
short_description: Copy files to remote locations |
| 15 |
description: |
| 16 |
- The M(ansible.builtin.copy) module copies a file or a directory structure from the local or remote machine to a location on the remote machine. |
| 17 |
File system meta-information (permissions, ownership, etc.) may be set, even when the file or directory already exists on the target system. |
| 18 |
Some meta-information may be copied on request. |
| 19 |
- Get meta-information with the M(ansible.builtin.stat) module. |
| 20 |
- Set meta-information with the M(ansible.builtin.file) module. |
| 21 |
- Use the M(ansible.builtin.fetch) module to copy files from remote locations to the local box. |
| 22 |
- If you need variable interpolation in copied files, use the M(ansible.builtin.template) module. |
| 23 |
Using a variable with the O(content) parameter produces unpredictable results. |
| 24 |
- For Windows targets, use the M(ansible.windows.win_copy) module instead. |
| 25 |
options: |
| 26 |
src: |
| 27 |
description: |
| 28 |
- Local path to a file to copy to the remote server. |
| 29 |
- This can be absolute or relative. |
| 30 |
- If path is a directory, it is copied recursively. In this case, if path ends |
| 31 |
with C(/), only inside contents of that directory are copied to destination. |
| 32 |
Otherwise, if it does not end with C(/), the directory itself with all contents |
| 33 |
is copied. This behavior is similar to the C(rsync) command line tool. |
| 34 |
type: path |
| 35 |
content: |
| 36 |
description: |
| 37 |
- When used instead of O(src), sets the contents of a file directly to the specified value. |
| 38 |
- Works only when O(dest) is a file. Creates the file if it does not exist. |
| 39 |
- For advanced formatting or if O(content) contains a variable, use the |
| 40 |
M(ansible.builtin.template) module. |
| 41 |
type: str |
| 42 |
version_added: '1.1' |
| 43 |
dest: |
| 44 |
description: |
| 45 |
- Remote absolute path where the file should be copied to. |
| 46 |
- If O(src) is a directory, this must be a directory too. |
| 47 |
- If O(dest) is a non-existent path and if either O(dest) ends with C(/) or O(src) is a directory, O(dest) is created. |
| 48 |
- If O(dest) is a relative path, the starting directory is determined by the remote host. |
| 49 |
- If O(src) and O(dest) are files, the parent directory of O(dest) is not created and the task fails if it does not already exist. |
| 50 |
type: path |
| 51 |
required: yes |
| 52 |
backup: |
| 53 |
description: |
| 54 |
- Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly. |
| 55 |
type: bool |
| 56 |
default: no |
| 57 |
version_added: '0.7' |
| 58 |
force: |
| 59 |
description: |
| 60 |
- Influence whether the remote file must always be replaced. |
| 61 |
- If V(true), the remote file will be replaced when contents are different than the source. |
| 62 |
- If V(false), the file will only be transferred if the destination does not exist. |
| 63 |
type: bool |
| 64 |
default: yes |
| 65 |
version_added: '1.1' |
| 66 |
mode: |
| 67 |
description: |
| 68 |
- The permissions of the destination file or directory. |
| 69 |
- For those used to C(/usr/bin/chmod) remember that modes are actually octal numbers. |
| 70 |
You must either add a leading zero so that Ansible's YAML parser knows it is an octal number |
| 71 |
(like V(0644) or V(01777)) or quote it (like V('644') or V('1777')) so Ansible receives a string |
| 72 |
and can do its own conversion from string into number. Giving Ansible a number without following |
| 73 |
one of these rules will end up with a decimal number which will have unexpected results. |
| 74 |
- As of Ansible 1.8, the mode may be specified as a symbolic mode (for example, V(u+rwx) or V(u=rw,g=r,o=r)). |
| 75 |
- As of Ansible 2.3, the mode may also be the special string V(preserve). |
| 76 |
- V(preserve) means that the file will be given the same permissions as the source file. |
| 77 |
- When doing a recursive copy, see also O(directory_mode). |
| 78 |
- If O(mode) is not specified and the destination file B(does not) exist, the default C(umask) on the system will be used |
| 79 |
when setting the mode for the newly created file. |
| 80 |
- If O(mode) is not specified and the destination file B(does) exist, the mode of the existing file will be used. |
| 81 |
- Specifying O(mode) is the best way to ensure files are created with the correct permissions. |
| 82 |
See CVE-2020-1736 for further details. |
| 83 |
directory_mode: |
| 84 |
description: |
| 85 |
- Set the access permissions of newly created directories to the given mode. |
| 86 |
Permissions on existing directories do not change. |
| 87 |
- See O(mode) for the syntax of accepted values. |
| 88 |
- The target system's defaults determine permissions when this parameter is not set. |
| 89 |
type: raw |
| 90 |
version_added: '1.5' |
| 91 |
remote_src: |
| 92 |
description: |
| 93 |
- Influence whether O(src) needs to be transferred or already is present remotely. |
| 94 |
- If V(false), it will search for O(src) on the controller node. |
| 95 |
- If V(true), it will search for O(src) on the managed (remote) node. |
| 96 |
- O(remote_src) supports recursive copying as of version 2.8. |
| 97 |
- O(remote_src) only works with O(mode=preserve) as of version 2.6. |
| 98 |
- Auto-decryption of files does not work when O(remote_src=yes). |
| 99 |
type: bool |
| 100 |
default: no |
| 101 |
version_added: '2.0' |
| 102 |
follow: |
| 103 |
description: |
| 104 |
- This flag indicates that filesystem links in the destination, if they exist, should be followed. |
| 105 |
type: bool |
| 106 |
default: no |
| 107 |
version_added: '1.8' |
| 108 |
local_follow: |
| 109 |
description: |
| 110 |
- This flag indicates that filesystem links in the source tree, if they exist, should be followed. |
| 111 |
type: bool |
| 112 |
version_added: '2.4' |
| 113 |
checksum: |
| 114 |
description: |
| 115 |
- SHA1 checksum of the file being transferred. |
| 116 |
- Used to validate that the copy of the file was successful. |
| 117 |
- If this is not provided, ansible will use the local calculated checksum of the src file. |
| 118 |
type: str |
| 119 |
version_added: '2.5' |
| 120 |
extends_documentation_fragment: |
| 121 |
- decrypt |
| 122 |
- files |
| 123 |
- validate |
| 124 |
- action_common_attributes |
| 125 |
- action_common_attributes.files |
| 126 |
- action_common_attributes.flow |
| 127 |
notes: |
| 128 |
- The M(ansible.builtin.copy) module recursively copy facility does not scale to lots (>hundreds) of files. |
| 129 |
seealso: |
| 130 |
- module: ansible.builtin.assemble |
| 131 |
- module: ansible.builtin.fetch |
| 132 |
- module: ansible.builtin.file |
| 133 |
- module: ansible.builtin.template |
| 134 |
- module: ansible.posix.synchronize |
| 135 |
- module: ansible.windows.win_copy |
| 136 |
author: |
| 137 |
- Ansible Core Team |
| 138 |
- Michael DeHaan |
| 139 |
attributes: |
| 140 |
action: |
| 141 |
support: full |
| 142 |
async: |
| 143 |
support: none |
| 144 |
bypass_host_loop: |
| 145 |
support: none |
| 146 |
check_mode: |
| 147 |
support: full |
| 148 |
diff_mode: |
| 149 |
support: full |
| 150 |
platform: |
| 151 |
platforms: posix |
| 152 |
safe_file_operations: |
| 153 |
support: full |
| 154 |
vault: |
| 155 |
support: full |
| 156 |
version_added: '2.2' |
| 157 |
""" |
| 158 |
|
| 159 |
EXAMPLES = r""" |
| 160 |
- name: Copy file with owner and permissions |
| 161 |
ansible.builtin.copy: |
| 162 |
src: /srv/myfiles/foo.conf |
| 163 |
dest: /etc/foo.conf |
| 164 |
owner: foo |
| 165 |
group: foo |
| 166 |
mode: '0644' |
| 167 |
|
| 168 |
- name: Copy file with owner and permission, using symbolic representation |
| 169 |
ansible.builtin.copy: |
| 170 |
src: /srv/myfiles/foo.conf |
| 171 |
dest: /etc/foo.conf |
| 172 |
owner: foo |
| 173 |
group: foo |
| 174 |
mode: u=rw,g=r,o=r |
| 175 |
|
| 176 |
- name: Another symbolic mode example, adding some permissions and removing others |
| 177 |
ansible.builtin.copy: |
| 178 |
src: /srv/myfiles/foo.conf |
| 179 |
dest: /etc/foo.conf |
| 180 |
owner: foo |
| 181 |
group: foo |
| 182 |
mode: u+rw,g-wx,o-rwx |
| 183 |
|
| 184 |
- name: Copy a new "ntp.conf" file into place, backing up the original if it differs from the copied version |
| 185 |
ansible.builtin.copy: |
| 186 |
src: /mine/ntp.conf |
| 187 |
dest: /etc/ntp.conf |
| 188 |
owner: root |
| 189 |
group: root |
| 190 |
mode: '0644' |
| 191 |
backup: yes |
| 192 |
|
| 193 |
- name: Copy a new "sudoers" file into place, after passing validation with visudo |
| 194 |
ansible.builtin.copy: |
| 195 |
src: /mine/sudoers |
| 196 |
dest: /etc/sudoers |
| 197 |
validate: /usr/sbin/visudo -csf %s |
| 198 |
|
| 199 |
- name: Copy a "sudoers" file on the remote machine for editing |
| 200 |
ansible.builtin.copy: |
| 201 |
src: /etc/sudoers |
| 202 |
dest: /etc/sudoers.edit |
| 203 |
remote_src: yes |
| 204 |
validate: /usr/sbin/visudo -csf %s |
| 205 |
|
| 206 |
- name: Copy using inline content |
| 207 |
ansible.builtin.copy: |
| 208 |
content: '# This file was moved to /etc/other.conf' |
| 209 |
dest: /etc/mine.conf |
| 210 |
|
| 211 |
- name: If follow=yes, /path/to/file will be overwritten by contents of foo.conf |
| 212 |
ansible.builtin.copy: |
| 213 |
src: /etc/foo.conf |
| 214 |
dest: /path/to/link # link to /path/to/file |
| 215 |
follow: yes |
| 216 |
|
| 217 |
- name: If follow=no, /path/to/link will become a file and be overwritten by contents of foo.conf |
| 218 |
ansible.builtin.copy: |
| 219 |
src: /etc/foo.conf |
| 220 |
dest: /path/to/link # link to /path/to/file |
| 221 |
follow: no |
| 222 |
""" |
| 223 |
|
| 224 |
RETURN = r""" |
| 225 |
dest: |
| 226 |
description: Destination file/path. |
| 227 |
returned: success |
| 228 |
type: str |
| 229 |
sample: /path/to/file.txt |
| 230 |
src: |
| 231 |
description: Source file used for the copy on the target machine. |
| 232 |
returned: changed |
| 233 |
type: str |
| 234 |
sample: /home/httpd/.ansible/tmp/ansible-tmp-1423796390.97-147729857856000/source |
| 235 |
md5sum: |
| 236 |
description: MD5 checksum of the file after running copy. |
| 237 |
returned: when supported |
| 238 |
type: str |
| 239 |
sample: 2a5aeecc61dc98c4d780b14b330e3282 |
| 240 |
checksum: |
| 241 |
description: SHA1 checksum of the file after running copy. |
| 242 |
returned: success |
| 243 |
type: str |
| 244 |
sample: 6e642bb8dd5c2e027bf21dd923337cbb4214f827 |
| 245 |
backup_file: |
| 246 |
description: Name of backup file created. |
| 247 |
returned: changed and if backup=yes |
| 248 |
type: str |
| 249 |
sample: /path/to/file.txt.2015-02-12@22:09~ |
| 250 |
gid: |
| 251 |
description: Group id of the file, after execution. |
| 252 |
returned: success |
| 253 |
type: int |
| 254 |
sample: 100 |
| 255 |
group: |
| 256 |
description: Group of the file, after execution. |
| 257 |
returned: success |
| 258 |
type: str |
| 259 |
sample: httpd |
| 260 |
owner: |
| 261 |
description: Owner of the file, after execution. |
| 262 |
returned: success |
| 263 |
type: str |
| 264 |
sample: httpd |
| 265 |
uid: |
| 266 |
description: Owner id of the file, after execution. |
| 267 |
returned: success |
| 268 |
type: int |
| 269 |
sample: 100 |
| 270 |
mode: |
| 271 |
description: Permissions of the target, after execution. |
| 272 |
returned: success |
| 273 |
type: str |
| 274 |
sample: '0644' |
| 275 |
size: |
| 276 |
description: Size of the target, after execution. |
| 277 |
returned: success |
| 278 |
type: int |
| 279 |
sample: 1220 |
| 280 |
state: |
| 281 |
description: State of the target, after execution. |
| 282 |
returned: success |
| 283 |
type: str |
| 284 |
sample: file |
| 285 |
""" |
| 286 |
|
| 287 |
import errno |
| 288 |
import filecmp |
| 289 |
import os |
| 290 |
import os.path |
| 291 |
import shutil |
| 292 |
import stat |
| 293 |
import tempfile |
| 294 |
|
| 295 |
from ansible.module_utils.common.text.converters import to_bytes, to_native |
| 296 |
from ansible.module_utils.basic import AnsibleModule |
| 297 |
|
| 298 |
|
| 299 |
class AnsibleModuleError(Exception): |
| 300 |
def __init__(self, results): |
| 301 |
self.results = results |
| 302 |
|
| 303 |
|
| 304 |
def split_pre_existing_dir(dirname): |
| 305 |
""" |
| 306 |
Return the first pre-existing directory and a list of the new directories that will be created. |
| 307 |
""" |
| 308 |
head, tail = os.path.split(dirname) |
| 309 |
b_head = to_bytes(head, errors='surrogate_or_strict') |
| 310 |
if head == '': |
| 311 |
return ('.', [tail]) |
| 312 |
if not os.path.exists(b_head): |
| 313 |
if head == '/': |
| 314 |
raise AnsibleModuleError(results={'msg': "The '/' directory doesn't exist on this machine."}) |
| 315 |
(pre_existing_dir, new_directory_list) = split_pre_existing_dir(head) |
| 316 |
else: |
| 317 |
return (head, [tail]) |
| 318 |
new_directory_list.append(tail) |
| 319 |
return (pre_existing_dir, new_directory_list) |
| 320 |
|
| 321 |
|
| 322 |
def adjust_recursive_directory_permissions(pre_existing_dir, new_directory_list, module, directory_args, changed): |
| 323 |
""" |
| 324 |
Walk the new directories list and make sure that permissions are as we would expect |
| 325 |
""" |
| 326 |
|
| 327 |
if new_directory_list: |
| 328 |
working_dir = os.path.join(pre_existing_dir, new_directory_list.pop(0)) |
| 329 |
directory_args['path'] = working_dir |
| 330 |
changed = module.set_fs_attributes_if_different(directory_args, changed) |
| 331 |
changed = adjust_recursive_directory_permissions(working_dir, new_directory_list, module, directory_args, changed) |
| 332 |
return changed |
| 333 |
|
| 334 |
|
| 335 |
def chown_path(module, path, owner, group): |
| 336 |
"""Update the owner/group if specified and different from the current owner/group.""" |
| 337 |
changed = module.set_owner_if_different(path, owner, False) |
| 338 |
return module.set_group_if_different(path, group, changed) |
| 339 |
|
| 340 |
|
| 341 |
def chown_recursive(path, module): |
| 342 |
changed = False |
| 343 |
owner = module.params['owner'] |
| 344 |
group = module.params['group'] |
| 345 |
|
| 346 |
# TODO: Consolidate with the other methods calling set_*_if_different method, this is inefficient. |
| 347 |
for dirpath, dirnames, filenames in os.walk(path): |
| 348 |
changed |= chown_path(module, dirpath, owner, group) |
| 349 |
for subdir in [os.path.join(dirpath, d) for d in dirnames]: |
| 350 |
changed |= chown_path(module, subdir, owner, group) |
| 351 |
for filepath in [os.path.join(dirpath, f) for f in filenames]: |
| 352 |
changed |= chown_path(module, filepath, owner, group) |
| 353 |
|
| 354 |
return changed |
| 355 |
|
| 356 |
|
| 357 |
def copy_diff_files(src, dest, module): |
| 358 |
"""Copy files that are different between `src` directory and `dest` directory.""" |
| 359 |
|
| 360 |
changed = False |
| 361 |
owner = module.params['owner'] |
| 362 |
group = module.params['group'] |
| 363 |
local_follow = module.params['local_follow'] |
| 364 |
diff_files = filecmp.dircmp(src, dest).diff_files |
| 365 |
if len(diff_files): |
| 366 |
changed = True |
| 367 |
if not module.check_mode: |
| 368 |
for item in diff_files: |
| 369 |
src_item_path = os.path.join(src, item) |
| 370 |
dest_item_path = os.path.join(dest, item) |
| 371 |
b_src_item_path = to_bytes(src_item_path, errors='surrogate_or_strict') |
| 372 |
b_dest_item_path = to_bytes(dest_item_path, errors='surrogate_or_strict') |
| 373 |
if os.path.islink(b_src_item_path) and local_follow is False: |
| 374 |
linkto = os.readlink(b_src_item_path) |
| 375 |
os.symlink(linkto, b_dest_item_path) |
| 376 |
else: |
| 377 |
shutil.copyfile(b_src_item_path, b_dest_item_path) |
| 378 |
shutil.copymode(b_src_item_path, b_dest_item_path) |
| 379 |
|
| 380 |
chown_path(module, b_dest_item_path, owner, group) |
| 381 |
changed = True |
| 382 |
return changed |
| 383 |
|
| 384 |
|
| 385 |
def copy_left_only(src, dest, module): |
| 386 |
"""Copy files that exist in `src` directory only to the `dest` directory.""" |
| 387 |
|
| 388 |
changed = False |
| 389 |
owner = module.params['owner'] |
| 390 |
group = module.params['group'] |
| 391 |
local_follow = module.params['local_follow'] |
| 392 |
left_only = filecmp.dircmp(src, dest).left_only |
| 393 |
if len(left_only): |
| 394 |
changed = True |
| 395 |
if not module.check_mode: |
| 396 |
for item in left_only: |
| 397 |
src_item_path = os.path.join(src, item) |
| 398 |
dest_item_path = os.path.join(dest, item) |
| 399 |
b_src_item_path = to_bytes(src_item_path, errors='surrogate_or_strict') |
| 400 |
b_dest_item_path = to_bytes(dest_item_path, errors='surrogate_or_strict') |
| 401 |
|
| 402 |
if os.path.islink(b_src_item_path) and os.path.isdir(b_src_item_path) and local_follow is True: |
| 403 |
shutil.copytree(b_src_item_path, b_dest_item_path, symlinks=not local_follow) |
| 404 |
chown_recursive(b_dest_item_path, module) |
| 405 |
|
| 406 |
if os.path.islink(b_src_item_path) and os.path.isdir(b_src_item_path) and local_follow is False: |
| 407 |
linkto = os.readlink(b_src_item_path) |
| 408 |
os.symlink(linkto, b_dest_item_path) |
| 409 |
|
| 410 |
if os.path.islink(b_src_item_path) and os.path.isfile(b_src_item_path) and local_follow is True: |
| 411 |
shutil.copyfile(b_src_item_path, b_dest_item_path) |
| 412 |
chown_path(module, b_dest_item_path, owner, group) |
| 413 |
|
| 414 |
if os.path.islink(b_src_item_path) and os.path.isfile(b_src_item_path) and local_follow is False: |
| 415 |
linkto = os.readlink(b_src_item_path) |
| 416 |
os.symlink(linkto, b_dest_item_path) |
| 417 |
|
| 418 |
if not os.path.islink(b_src_item_path) and os.path.isfile(b_src_item_path): |
| 419 |
shutil.copyfile(b_src_item_path, b_dest_item_path) |
| 420 |
shutil.copymode(b_src_item_path, b_dest_item_path) |
| 421 |
chown_path(module, b_dest_item_path, owner, group) |
| 422 |
|
| 423 |
if not os.path.islink(b_src_item_path) and os.path.isdir(b_src_item_path): |
| 424 |
shutil.copytree(b_src_item_path, b_dest_item_path, symlinks=not local_follow) |
| 425 |
chown_recursive(b_dest_item_path, module) |
| 426 |
|
| 427 |
changed = True |
| 428 |
return changed |
| 429 |
|
| 430 |
|
| 431 |
def copy_common_dirs(src, dest, module): |
| 432 |
changed = False |
| 433 |
common_dirs = filecmp.dircmp(src, dest).common_dirs |
| 434 |
for item in common_dirs: |
| 435 |
src_item_path = os.path.join(src, item) |
| 436 |
dest_item_path = os.path.join(dest, item) |
| 437 |
b_src_item_path = to_bytes(src_item_path, errors='surrogate_or_strict') |
| 438 |
b_dest_item_path = to_bytes(dest_item_path, errors='surrogate_or_strict') |
| 439 |
diff_files_changed = copy_diff_files(b_src_item_path, b_dest_item_path, module) |
| 440 |
left_only_changed = copy_left_only(b_src_item_path, b_dest_item_path, module) |
| 441 |
if diff_files_changed or left_only_changed: |
| 442 |
changed = True |
| 443 |
|
| 444 |
# recurse into subdirectory |
| 445 |
changed = copy_common_dirs(os.path.join(src, item), os.path.join(dest, item), module) or changed |
| 446 |
return changed |
| 447 |
|
| 448 |
|
| 449 |
def copy_directory(src, dest, module): |
| 450 |
if not os.path.exists(dest): |
| 451 |
if not module.check_mode: |
| 452 |
shutil.copytree(src, dest, symlinks=not module.params['local_follow']) |
| 453 |
chown_recursive(dest, module) |
| 454 |
changed = True |
| 455 |
else: |
| 456 |
diff_files_changed = copy_diff_files(src, dest, module) |
| 457 |
left_only_changed = copy_left_only(src, dest, module) |
| 458 |
common_dirs_changed = copy_common_dirs(src, dest, module) |
| 459 |
owner_group_changed = chown_recursive(dest, module) |
| 460 |
changed = any([diff_files_changed, left_only_changed, common_dirs_changed, owner_group_changed]) |
| 461 |
return changed |
| 462 |
|
| 463 |
|
| 464 |
def main(): |
| 465 |
|
| 466 |
module = AnsibleModule( |
| 467 |
# not checking because of daisy chain to file module |
| 468 |
argument_spec=dict( |
| 469 |
src=dict(type='path'), |
| 470 |
_original_basename=dict(type='str'), # used to handle 'dest is a directory' via template, a slight hack |
| 471 |
content=dict(type='str', no_log=True), |
| 472 |
dest=dict(type='path', required=True), |
| 473 |
backup=dict(type='bool', default=False), |
| 474 |
force=dict(type='bool', default=True), |
| 475 |
validate=dict(type='str'), |
| 476 |
directory_mode=dict(type='raw'), |
| 477 |
remote_src=dict(type='bool', default=False), |
| 478 |
local_follow=dict(type='bool'), |
| 479 |
checksum=dict(type='str'), |
| 480 |
follow=dict(type='bool', default=False), |
| 481 |
), |
| 482 |
add_file_common_args=True, |
| 483 |
supports_check_mode=True, |
| 484 |
) |
| 485 |
|
| 486 |
src = module.params['src'] |
| 487 |
b_src = to_bytes(src, errors='surrogate_or_strict') |
| 488 |
dest = module.params['dest'] |
| 489 |
# Make sure we always have a directory component for later processing |
| 490 |
if os.path.sep not in dest: |
| 491 |
dest = '.{0}{1}'.format(os.path.sep, dest) |
| 492 |
b_dest = to_bytes(dest, errors='surrogate_or_strict') |
| 493 |
backup = module.params['backup'] |
| 494 |
force = module.params['force'] |
| 495 |
_original_basename = module.params.get('_original_basename', None) |
| 496 |
validate = module.params.get('validate', None) |
| 497 |
follow = module.params['follow'] |
| 498 |
local_follow = module.params['local_follow'] |
| 499 |
mode = module.params['mode'] |
| 500 |
owner = module.params['owner'] |
| 501 |
group = module.params['group'] |
| 502 |
remote_src = module.params['remote_src'] |
| 503 |
checksum = module.params['checksum'] |
| 504 |
|
| 505 |
if not os.path.exists(b_src): |
| 506 |
module.fail_json(msg="Source %s not found" % (src)) |
| 507 |
if not os.access(b_src, os.R_OK): |
| 508 |
module.fail_json(msg="Source %s not readable" % (src)) |
| 509 |
|
| 510 |
# Preserve is usually handled in the action plugin but mode + remote_src has to be done on the |
| 511 |
# remote host |
| 512 |
if module.params['mode'] == 'preserve': |
| 513 |
module.params['mode'] = '0%03o' % stat.S_IMODE(os.stat(b_src).st_mode) |
| 514 |
mode = module.params['mode'] |
| 515 |
|
| 516 |
changed = False |
| 517 |
|
| 518 |
checksum_dest = None |
| 519 |
checksum_src = None |
| 520 |
md5sum_src = None |
| 521 |
|
| 522 |
if os.path.isfile(src): |
| 523 |
try: |
| 524 |
checksum_src = module.sha1(src) |
| 525 |
except OSError as ex: |
| 526 |
module.error_as_warning("Unable to calculate src checksum, assuming change.", exception=ex) |
| 527 |
try: |
| 528 |
# Backwards compat only. This will be None in FIPS mode |
| 529 |
md5sum_src = module.md5(src) |
| 530 |
except ValueError: |
| 531 |
pass |
| 532 |
elif remote_src and not os.path.isdir(src): |
| 533 |
module.fail_json("Cannot copy invalid source '%s': not a file" % to_native(src)) |
| 534 |
|
| 535 |
if checksum and checksum_src != checksum: |
| 536 |
module.fail_json( |
| 537 |
msg='Copied file does not match the expected checksum. Transfer failed.', |
| 538 |
checksum=checksum_src, |
| 539 |
expected_checksum=checksum |
| 540 |
) |
| 541 |
|
| 542 |
# Special handling for recursive copy - create intermediate dirs |
| 543 |
if dest.endswith(os.sep): |
| 544 |
if _original_basename: |
| 545 |
dest = os.path.join(dest, _original_basename) |
| 546 |
b_dest = to_bytes(dest, errors='surrogate_or_strict') |
| 547 |
dirname = os.path.dirname(dest) |
| 548 |
b_dirname = to_bytes(dirname, errors='surrogate_or_strict') |
| 549 |
if not os.path.exists(b_dirname): |
| 550 |
try: |
| 551 |
(pre_existing_dir, new_directory_list) = split_pre_existing_dir(dirname) |
| 552 |
except AnsibleModuleError as e: |
| 553 |
e.result['msg'] += ' Could not copy to {0}'.format(dest) |
| 554 |
module.fail_json(**e.results) |
| 555 |
|
| 556 |
if module.check_mode: |
| 557 |
module.exit_json(msg='dest directory %s would be created' % dirname, changed=True, src=src) |
| 558 |
os.makedirs(b_dirname) |
| 559 |
changed = True |
| 560 |
directory_args = module.load_file_common_arguments(module.params) |
| 561 |
directory_mode = module.params["directory_mode"] |
| 562 |
if directory_mode is not None: |
| 563 |
directory_args['mode'] = directory_mode |
| 564 |
else: |
| 565 |
directory_args['mode'] = None |
| 566 |
adjust_recursive_directory_permissions(pre_existing_dir, new_directory_list, module, directory_args, changed) |
| 567 |
|
| 568 |
if os.path.isdir(b_dest): |
| 569 |
basename = os.path.basename(src) |
| 570 |
if _original_basename: |
| 571 |
basename = _original_basename |
| 572 |
dest = os.path.join(dest, basename) |
| 573 |
b_dest = to_bytes(dest, errors='surrogate_or_strict') |
| 574 |
|
| 575 |
if os.path.exists(b_dest): |
| 576 |
if os.path.islink(b_dest) and follow: |
| 577 |
b_dest = os.path.realpath(b_dest) |
| 578 |
dest = to_native(b_dest, errors='surrogate_or_strict') |
| 579 |
if not force: |
| 580 |
module.exit_json(msg="file already exists", src=src, dest=dest, changed=False) |
| 581 |
if os.access(b_dest, os.R_OK) and os.path.isfile(b_dest): |
| 582 |
checksum_dest = module.sha1(dest) |
| 583 |
else: |
| 584 |
if not os.path.exists(os.path.dirname(b_dest)): |
| 585 |
try: |
| 586 |
# os.path.exists() can return false in some |
| 587 |
# circumstances where the directory does not have |
| 588 |
# the execute bit for the current user set, in |
| 589 |
# which case the stat() call will raise an OSError |
| 590 |
os.stat(os.path.dirname(b_dest)) |
| 591 |
except OSError as e: |
| 592 |
if "permission denied" in to_native(e).lower(): |
| 593 |
module.fail_json(msg="Destination directory %s is not accessible" % (os.path.dirname(dest))) |
| 594 |
module.fail_json(msg="Destination directory %s does not exist" % (os.path.dirname(dest))) |
| 595 |
|
| 596 |
if not os.access(os.path.dirname(b_dest), os.W_OK) and not module.params['unsafe_writes']: |
| 597 |
module.fail_json(msg="Destination %s not writable" % (os.path.dirname(dest))) |
| 598 |
|
| 599 |
backup_file = None |
| 600 |
if checksum_src != checksum_dest or os.path.islink(b_dest): |
| 601 |
|
| 602 |
if not module.check_mode: |
| 603 |
try: |
| 604 |
if backup: |
| 605 |
if os.path.exists(b_dest): |
| 606 |
backup_file = module.backup_local(dest) |
| 607 |
# allow for conversion from symlink. |
| 608 |
if os.path.islink(b_dest): |
| 609 |
os.unlink(b_dest) |
| 610 |
open(b_dest, 'w').close() |
| 611 |
if validate: |
| 612 |
# if we have a mode, make sure we set it on the temporary |
| 613 |
# file source as some validations may require it |
| 614 |
module.set_mode_if_different(src, mode, False) |
| 615 |
chown_path(module, src, owner, group) |
| 616 |
if "%s" not in validate: |
| 617 |
module.fail_json(msg="validate must contain %%s: %s" % (validate)) |
| 618 |
(rc, out, err) = module.run_command(validate % src) |
| 619 |
if rc != 0: |
| 620 |
module.fail_json(msg="failed to validate", exit_status=rc, stdout=out, stderr=err) |
| 621 |
|
| 622 |
b_mysrc = b_src |
| 623 |
if remote_src and os.path.isfile(b_src): |
| 624 |
|
| 625 |
dummy, b_mysrc = tempfile.mkstemp(dir=os.path.dirname(b_dest)) |
| 626 |
|
| 627 |
shutil.copyfile(b_src, b_mysrc) |
| 628 |
try: |
| 629 |
shutil.copystat(b_src, b_mysrc) |
| 630 |
except OSError as err: |
| 631 |
if err.errno == errno.ENOSYS and mode == "preserve": |
| 632 |
module.warn("Unable to copy stats {0}".format(to_native(b_src))) |
| 633 |
else: |
| 634 |
raise |
| 635 |
|
| 636 |
# at this point we should always have tmp file |
| 637 |
module.atomic_move(b_mysrc, dest, unsafe_writes=module.params['unsafe_writes'], keep_dest_attrs=not remote_src) |
| 638 |
|
| 639 |
except OSError as ex: |
| 640 |
raise Exception(f"Failed to copy {src!r} to {dest!r}.") from ex |
| 641 |
changed = True |
| 642 |
|
| 643 |
# If neither have checksums, both src and dest are directories. |
| 644 |
checksums_none = checksum_src is None and checksum_dest is None |
| 645 |
both_directories = os.path.isdir(module.params['src']) and (os.path.isdir(module.params['dest']) or not os.path.exists(module.params['dest'])) |
| 646 |
if checksums_none and remote_src and both_directories: |
| 647 |
b_src = to_bytes(module.params['src'], errors='surrogate_or_strict') |
| 648 |
b_dest = to_bytes(module.params['dest'], errors='surrogate_or_strict') |
| 649 |
|
| 650 |
if not b_src.endswith(to_bytes(os.path.sep)): |
| 651 |
b_basename = os.path.basename(b_src) |
| 652 |
b_dest = os.path.join(b_dest, b_basename) |
| 653 |
b_src = os.path.join(b_src, b'') |
| 654 |
|
| 655 |
changed |= copy_directory(b_src, b_dest, module) |
| 656 |
|
| 657 |
res_args = dict( |
| 658 |
dest=dest, src=src, md5sum=md5sum_src, checksum=checksum_src, changed=changed |
| 659 |
) |
| 660 |
if backup_file: |
| 661 |
res_args['backup_file'] = backup_file |
| 662 |
|
| 663 |
file_args = module.load_file_common_arguments(module.params, path=dest) |
| 664 |
directory_mode = module.params['directory_mode'] |
| 665 |
if os.path.isdir(b_dest) and directory_mode is not None: |
| 666 |
file_args['mode'] = directory_mode |
| 667 |
res_args['changed'] = module.set_fs_attributes_if_different(file_args, res_args['changed']) |
| 668 |
|
| 669 |
module.exit_json(**res_args) |
| 670 |
|
| 671 |
|
| 672 |
if __name__ == '__main__': |
| 673 |
main() |