| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2015, Dag Wieers (@dagwieers) <[email protected]> |
| 5 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 7 |
|
| 8 |
from __future__ import absolute_import, division, print_function |
| 9 |
__metaclass__ = type |
| 10 |
|
| 11 |
|
| 12 |
DOCUMENTATION = r''' |
| 13 |
--- |
| 14 |
module: vsphere_copy |
| 15 |
short_description: Copy a file to a VMware datastore |
| 16 |
description: |
| 17 |
- Upload files to a VMware datastore through a vCenter REST API. |
| 18 |
author: |
| 19 |
- Dag Wieers (@dagwieers) |
| 20 |
options: |
| 21 |
src: |
| 22 |
description: |
| 23 |
- The file to push to vCenter. |
| 24 |
required: true |
| 25 |
type: str |
| 26 |
aliases: [ name ] |
| 27 |
datacenter: |
| 28 |
description: |
| 29 |
- The datacenter on the vCenter server that holds the datastore. |
| 30 |
required: false |
| 31 |
type: str |
| 32 |
datastore: |
| 33 |
description: |
| 34 |
- The datastore to push files to. |
| 35 |
required: true |
| 36 |
type: str |
| 37 |
path: |
| 38 |
description: |
| 39 |
- The file to push to the datastore. |
| 40 |
required: true |
| 41 |
type: str |
| 42 |
aliases: [ dest ] |
| 43 |
timeout: |
| 44 |
description: |
| 45 |
- The timeout in seconds for the upload to the datastore. |
| 46 |
default: 10 |
| 47 |
type: int |
| 48 |
diskformat: |
| 49 |
version_added: 4.2.0 |
| 50 |
description: |
| 51 |
- Optional argument - Set a diskformat for certain uploads like stream optimized VMDKs |
| 52 |
- There is no official documentation, but it looks like V(StreamVmdk) needs to be set for stream optimized VMDKs that are uploaded to vSAN storage |
| 53 |
- Setting this for non-VMDK files might lead to undefined behavior and is not supported. |
| 54 |
choices: ["StreamVmdk"] |
| 55 |
type: str |
| 56 |
|
| 57 |
notes: |
| 58 |
- "This module ought to be run from a system that can access the vCenter or the ESXi directly and has the file to transfer. |
| 59 |
It can be the normal remote target or you can change it either by using C(transport: local) or using C(delegate_to)." |
| 60 |
extends_documentation_fragment: |
| 61 |
- vmware.vmware.base_options |
| 62 |
|
| 63 |
''' |
| 64 |
|
| 65 |
EXAMPLES = r''' |
| 66 |
- name: Copy file to datastore using delegate_to |
| 67 |
community.vmware.vsphere_copy: |
| 68 |
hostname: '{{ vcenter_hostname }}' |
| 69 |
username: '{{ vcenter_username }}' |
| 70 |
password: '{{ vcenter_password }}' |
| 71 |
src: /some/local/file |
| 72 |
datacenter: DC1 Someplace |
| 73 |
datastore: datastore1 |
| 74 |
path: some/remote/file |
| 75 |
delegate_to: localhost |
| 76 |
|
| 77 |
- name: Copy file to datastore when datacenter is inside folder called devel |
| 78 |
community.vmware.vsphere_copy: |
| 79 |
hostname: '{{ vcenter_hostname }}' |
| 80 |
username: '{{ vcenter_username }}' |
| 81 |
password: '{{ vcenter_password }}' |
| 82 |
src: /some/local/file |
| 83 |
datacenter: devel/DC1 |
| 84 |
datastore: datastore1 |
| 85 |
path: some/remote/file |
| 86 |
delegate_to: localhost |
| 87 |
|
| 88 |
- name: Copy file to datastore using other_system |
| 89 |
community.vmware.vsphere_copy: |
| 90 |
hostname: '{{ vcenter_hostname }}' |
| 91 |
username: '{{ vcenter_username }}' |
| 92 |
password: '{{ vcenter_password }}' |
| 93 |
src: /other/local/file |
| 94 |
datacenter: DC2 Someplace |
| 95 |
datastore: datastore2 |
| 96 |
path: other/remote/file |
| 97 |
delegate_to: other_system |
| 98 |
|
| 99 |
- name: Copy file to datastore using other_system |
| 100 |
community.vmware.vsphere_copy: |
| 101 |
hostname: '{{ vcenter_hostname }}' |
| 102 |
username: '{{ vcenter_username }}' |
| 103 |
password: '{{ vcenter_password }}' |
| 104 |
src: /other/local/streamOptimized.vmdk |
| 105 |
datacenter: DC2 Someplace |
| 106 |
datastore: datastore2 |
| 107 |
path: disk_imports/streamOptimized.vmdk |
| 108 |
timeout: 360 |
| 109 |
diskformat: StreamVmdk |
| 110 |
delegate_to: other_system |
| 111 |
''' |
| 112 |
|
| 113 |
import atexit |
| 114 |
import errno |
| 115 |
import mmap |
| 116 |
import os |
| 117 |
import socket |
| 118 |
import traceback |
| 119 |
|
| 120 |
from ansible.module_utils.basic import AnsibleModule |
| 121 |
from urllib.parse import urlencode, quote |
| 122 |
from ansible.module_utils.common.text.converters import to_native |
| 123 |
from ansible.module_utils.urls import open_url |
| 124 |
from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec |
| 125 |
|
| 126 |
|
| 127 |
def vmware_path(datastore, datacenter, path, diskformat): |
| 128 |
''' Constructs a URL path that vSphere accepts reliably ''' |
| 129 |
path = "/folder/%s" % quote(path.lstrip("/")) |
| 130 |
# Due to a software bug in vSphere, it fails to handle ampersand in datacenter names |
| 131 |
# The solution is to do what vSphere does (when browsing) and double-encode ampersands, maybe others ? |
| 132 |
if not path.startswith("/"): |
| 133 |
path = "/" + path |
| 134 |
params = dict(dsName=datastore) |
| 135 |
if datacenter: |
| 136 |
datacenter = datacenter.replace('&', '%26') |
| 137 |
params["dcPath"] = datacenter |
| 138 |
if diskformat: |
| 139 |
params["diskFormat"] = diskformat |
| 140 |
params = urlencode(params) |
| 141 |
return "%s?%s" % (path, params) |
| 142 |
|
| 143 |
|
| 144 |
def main(): |
| 145 |
argument_spec = base_argument_spec() |
| 146 |
argument_spec.update(dict( |
| 147 |
src=dict(required=True, aliases=['name']), |
| 148 |
datacenter=dict(required=False), |
| 149 |
datastore=dict(required=True), |
| 150 |
path=dict(required=True, aliases=['dest'], type='str'), |
| 151 |
timeout=dict(default=10, type='int'), |
| 152 |
diskformat=dict(required=False, type='str', choices=['StreamVmdk'])) |
| 153 |
) |
| 154 |
|
| 155 |
module = AnsibleModule( |
| 156 |
argument_spec=argument_spec, |
| 157 |
# Implementing check-mode using HEAD is impossible, since size/date is not 100% reliable |
| 158 |
supports_check_mode=False, |
| 159 |
) |
| 160 |
|
| 161 |
hostname = module.params['hostname'] |
| 162 |
username = module.params['username'] |
| 163 |
password = module.params.get('password') |
| 164 |
src = module.params.get('src') |
| 165 |
datacenter = module.params.get('datacenter') |
| 166 |
datastore = module.params.get('datastore') |
| 167 |
path = module.params.get('path') |
| 168 |
diskformat = module.params.get('diskformat') |
| 169 |
validate_certs = module.params.get('validate_certs') |
| 170 |
timeout = module.params.get('timeout') |
| 171 |
|
| 172 |
try: |
| 173 |
fd = open(src, "rb") |
| 174 |
atexit.register(fd.close) |
| 175 |
except Exception as e: |
| 176 |
module.fail_json(msg="Failed to open src file %s" % to_native(e)) |
| 177 |
|
| 178 |
if os.stat(src).st_size == 0: |
| 179 |
data = '' |
| 180 |
else: |
| 181 |
data = mmap.mmap(fd.fileno(), 0, access=mmap.ACCESS_READ) |
| 182 |
atexit.register(data.close) |
| 183 |
|
| 184 |
remote_path = vmware_path(datastore, datacenter, path, diskformat) |
| 185 |
|
| 186 |
if not all([hostname, username, password]): |
| 187 |
module.fail_json(msg="One of following parameter is missing - hostname, username, password") |
| 188 |
url = 'https://%s%s' % (hostname, remote_path) |
| 189 |
|
| 190 |
headers = { |
| 191 |
"Content-Type": "application/octet-stream", |
| 192 |
"Content-Length": str(len(data)), |
| 193 |
} |
| 194 |
|
| 195 |
r = None |
| 196 |
try: |
| 197 |
r = open_url(url, data=data, headers=headers, method='PUT', timeout=timeout, |
| 198 |
url_username=username, url_password=password, validate_certs=validate_certs, |
| 199 |
force_basic_auth=True) |
| 200 |
except socket.error as e: |
| 201 |
if isinstance(e.args, tuple): |
| 202 |
if len(e.args) > 0: |
| 203 |
if e[0] == errno.ECONNRESET: |
| 204 |
# vSphere resets connection if the file is in use and cannot be replaced |
| 205 |
module.fail_json(msg='Failed to upload, image probably in use', status=None, errno=e[0], reason=to_native(e), url=url) |
| 206 |
else: |
| 207 |
module.fail_json(msg=to_native(e)) |
| 208 |
else: |
| 209 |
module.fail_json(msg=str(e), status=None, errno=e[0], reason=str(e), |
| 210 |
url=url, exception=traceback.format_exc()) |
| 211 |
except Exception as e: |
| 212 |
error_code = -1 |
| 213 |
try: |
| 214 |
if isinstance(e[0], int): |
| 215 |
error_code = e[0] |
| 216 |
except (KeyError, TypeError): |
| 217 |
pass |
| 218 |
module.fail_json(msg=to_native(e), status=None, errno=error_code, |
| 219 |
reason=to_native(e), url=url, exception=traceback.format_exc()) |
| 220 |
|
| 221 |
if not r: |
| 222 |
module.fail_json(msg="Failed to upload", url=url, |
| 223 |
errno=None, status=None, reason=None) |
| 224 |
status = r.getcode() |
| 225 |
if 200 <= status < 300: |
| 226 |
module.exit_json(changed=True, status=status, reason=r.msg, url=url) |
| 227 |
else: |
| 228 |
length = r.headers.get('content-length', None) |
| 229 |
if r.headers.get('transfer-encoding', '').lower() == 'chunked': |
| 230 |
chunked = 1 |
| 231 |
else: |
| 232 |
chunked = 0 |
| 233 |
|
| 234 |
module.fail_json(msg='Failed to upload', errno=None, status=status, reason=r.msg, length=length, headers=dict(r.headers), chunked=chunked, url=url) |
| 235 |
|
| 236 |
|
| 237 |
if __name__ == '__main__': |
| 238 |
main() |