Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_vm_hardware_disk.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # Copyright: (c) 2021, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # template: header.j2
6 # This module is autogenerated using the ansible.content_builder.
7 # See: https://github.com/ansible-community/ansible.content_builder
8
9
10 DOCUMENTATION = r"""
11 module: vcenter_vm_hardware_disk
12 short_description: Adds a thin provisioned virtual disk to the virtual machine
13 description: Adds a virtual disk to the virtual machine. The disk (provision)
14 type is always 'thin'. While adding the virtual disk, a new VMDK file may
15 be created or an existing VMDK file may be used to back the virtual disk.
16 deprecated:
17 removed_in: 5.0.0
18 why: This module has been moved to the L(new vmware.vmware collection,https://forum.ansible.com/t/5880)
19 alternative: Use M(vmware.vmware.vm) instead.
20 options:
21 backing:
22 description:
23 - Existing physical resource backing for the virtual disk. Exactly one of
24 I(backing) or I(new_vmdk) must be specified.
25 - If unset, the virtual disk will not be connected to an existing backing.
26 Required with I(state=['present'])
27 - 'Valid attributes are:'
28 - ' - C(type) (str): This option defines the valid backing types for a virtual
29 disk. ([''present''])'
30 - ' This key is required with [''present''].'
31 - ' - Accepted values:'
32 - ' - VMDK_FILE'
33 - ' - C(vmdk_file) (str): Path of the VMDK file backing the virtual disk.'
34 - This field is optional and it is only relevant when the value of I(type)
35 is VMDK_FILE. (['present'])
36 type: dict
37 disk:
38 description:
39 - Virtual disk identifier.
40 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_hardware_disk).
41 Required with I(state=['absent', 'present'])
42 type: str
43 ide:
44 description:
45 - Address for attaching the device to a virtual IDE adapter.
46 - If unset, the server will choose an available address; if none is available,
47 the request will fail.
48 - 'Valid attributes are:'
49 - ' - C(primary) (bool): Flag specifying whether the device should be attached
50 to the primary or secondary IDE adapter of the virtual machine.'
51 - If unset, the server will choose a adapter with an available connection.
52 If no IDE connections are available, the request will be rejected. (['present'])
53 - ' - C(master) (bool): Flag specifying whether the device should be the master
54 or slave device on the IDE adapter.'
55 - If unset, the server will choose an available connection type. If no IDE
56 connections are available, the request will be rejected. (['present'])
57 type: dict
58 label:
59 description:
60 - The name of the item
61 type: str
62 new_vmdk:
63 description:
64 - Specification for creating a new VMDK backing for the virtual disk. Exactly
65 one of I(backing) or I(new_vmdk) must be specified.
66 - If unset, a new VMDK backing will not be created.
67 - 'Valid attributes are:'
68 - ' - C(name) (str): Base name of the VMDK file. The name should not include
69 the ''.vmdk'' file extension.'
70 - If unset, a name (derived from the name of the virtual machine) will be
71 chosen by the server. (['present'])
72 - ' - C(capacity) (int): Capacity of the virtual disk backing in bytes.'
73 - If unset, defaults to a guest-specific capacity. (['present'])
74 - ' - C(storage_policy) (dict): The I(storage_policy_spec) structure contains
75 information about the storage policy that is to be associated the with
76 VMDK file.'
77 - 'If unset the default storage policy of the target datastore (if applicable)
78 is applied. Currently a default storage policy is only supported by object
79 based datastores : VVol & vSAN. For non- object datastores, if unset then
80 no storage policy would be associated with the VMDK file. ([''present''])'
81 - ' - Accepted keys:'
82 - ' - policy (string): Identifier of the storage policy which should be
83 associated with the VMDK file.'
84 - 'When clients pass a value of this structure as a parameter, the field must
85 be the id of a resource returned by M(vmware.vmware_rest.vcenter_storage_policies_info). '
86 type: dict
87 nvme:
88 description:
89 - Address for attaching the device to a virtual NVMe adapter.
90 - If unset, the server will choose an available address; if none is available,
91 the request will fail. Required with I(state=['present'])
92 - 'Valid attributes are:'
93 - ' - C(bus) (int): Bus number of the adapter to which the device should be
94 attached. ([''present''])'
95 - ' This key is required with [''present''].'
96 - ' - C(unit) (int): Unit number of the device.'
97 - If unset, the server will choose an available unit number on the specified
98 adapter. If there are no available connections on the adapter, the request
99 will be rejected. (['present'])
100 type: dict
101 sata:
102 description:
103 - Address for attaching the device to a virtual SATA adapter.
104 - If unset, the server will choose an available address; if none is available,
105 the request will fail. Required with I(state=['present'])
106 - 'Valid attributes are:'
107 - ' - C(bus) (int): Bus number of the adapter to which the device should be
108 attached. ([''present''])'
109 - ' This key is required with [''present''].'
110 - ' - C(unit) (int): Unit number of the device.'
111 - If unset, the server will choose an available unit number on the specified
112 adapter. If there are no available connections on the adapter, the request
113 will be rejected. (['present'])
114 type: dict
115 scsi:
116 description:
117 - Address for attaching the device to a virtual SCSI adapter.
118 - If unset, the server will choose an available address; if none is available,
119 the request will fail. Required with I(state=['present'])
120 - 'Valid attributes are:'
121 - ' - C(bus) (int): Bus number of the adapter to which the device should be
122 attached. ([''present''])'
123 - ' This key is required with [''present''].'
124 - ' - C(unit) (int): Unit number of the device.'
125 - If unset, the server will choose an available unit number on the specified
126 adapter. If there are no available connections on the adapter, the request
127 will be rejected. (['present'])
128 type: dict
129 session_timeout:
130 description:
131 - 'Timeout settings for client session. '
132 - 'The maximal number of seconds for the whole operation including connection
133 establishment, request sending and response. '
134 - The default value is 300s.
135 type: float
136 version_added: 2.1.0
137 state:
138 choices:
139 - absent
140 - present
141 default: present
142 description: []
143 type: str
144 type:
145 choices:
146 - IDE
147 - NVME
148 - SATA
149 - SCSI
150 description:
151 - The I(host_bus_adapter_type) enumerated type defines the valid types of
152 host bus adapters that may be used for attaching a virtual storage device
153 to a virtual machine.
154 type: str
155 vcenter_hostname:
156 description:
157 - The hostname or IP address of the vSphere vCenter
158 - If the value is not specified in the task, the value of environment variable
159 C(VMWARE_HOST) will be used instead.
160 required: true
161 type: str
162 vcenter_password:
163 description:
164 - The vSphere vCenter password
165 - If the value is not specified in the task, the value of environment variable
166 C(VMWARE_PASSWORD) will be used instead.
167 required: true
168 type: str
169 vcenter_rest_log_file:
170 description:
171 - 'You can use this optional parameter to set the location of a log file. '
172 - 'This file will be used to record the HTTP REST interaction. '
173 - 'The file will be stored on the host that runs the module. '
174 - 'If the value is not specified in the task, the value of '
175 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
176 type: str
177 vcenter_username:
178 description:
179 - The vSphere vCenter username
180 - If the value is not specified in the task, the value of environment variable
181 C(VMWARE_USER) will be used instead.
182 required: true
183 type: str
184 vcenter_validate_certs:
185 default: true
186 description:
187 - Allows connection when SSL certificates are not valid. Set to C(false) when
188 certificates are not trusted.
189 - If the value is not specified in the task, the value of environment variable
190 C(VMWARE_VALIDATE_CERTS) will be used instead.
191 type: bool
192 vm:
193 description:
194 - Virtual machine identifier.
195 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_info).
196 This parameter is mandatory.
197 required: true
198 type: str
199 author:
200 - Ansible Cloud Team (@ansible-collections)
201 version_added: 0.1.0
202 requirements:
203 - vSphere 7.0.3 or greater
204 - python >= 3.6
205 - aiohttp
206 notes:
207 - Tested on vSphere 7.0.3
208 """
209
210 EXAMPLES = r"""
211 - name: Look up the VM called test_vm1 in the inventory
212 register: search_result
213 vmware.vmware_rest.vcenter_vm_info:
214 filter_names:
215 - test_vm1
216
217 - name: Collect information about a specific VM
218 vmware.vmware_rest.vcenter_vm_info:
219 vm: '{{ search_result.value[0].vm }}'
220 register: test_vm1_info
221
222 - name: Create a new disk
223 vmware.vmware_rest.vcenter_vm_hardware_disk:
224 vm: '{{ test_vm1_info.id }}'
225 type: SATA
226 new_vmdk:
227 capacity: 320000
228 register: my_new_disk
229
230 - name: Delete the disk
231 vmware.vmware_rest.vcenter_vm_hardware_disk:
232 vm: '{{ test_vm1_info.id }}'
233 disk: '{{ my_new_disk.id }}'
234 state: absent
235 register: _result
236 """
237 RETURN = r"""
238 # content generated by the update_return_section callback# task: Create a new disk
239 id:
240 description: moid of the resource
241 returned: On success
242 sample: '16000'
243 type: str
244 value:
245 description: Create a new disk
246 returned: On success
247 sample:
248 backing:
249 type: VMDK_FILE
250 vmdk_file: '[local] test_vm1/test_vm1_1.vmdk'
251 capacity: 320000
252 label: Hard disk 2
253 sata:
254 bus: 0
255 unit: 0
256 type: SATA
257 type: dict
258 """
259
260
261 # This structure describes the format of the data expected by the end-points
262 PAYLOAD_FORMAT = {
263 "delete": {"query": {}, "body": {}, "path": {"disk": "disk", "vm": "vm"}},
264 "update": {
265 "query": {},
266 "body": {"backing": "backing"},
267 "path": {"disk": "disk", "vm": "vm"},
268 },
269 "create": {
270 "query": {},
271 "body": {
272 "backing": "backing",
273 "ide": "ide",
274 "new_vmdk": "new_vmdk",
275 "nvme": "nvme",
276 "sata": "sata",
277 "scsi": "scsi",
278 "type": "type",
279 },
280 "path": {"vm": "vm"},
281 },
282 } # pylint: disable=line-too-long
283
284 from ansible.module_utils.basic import env_fallback
285 import os
286
287 if os.getenv("VMWARE_ENABLE_TURBO", False):
288 try:
289 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
290 AnsibleTurboModule as AnsibleModule,
291 )
292
293 AnsibleModule.collection_name = "vmware.vmware_rest"
294 except ImportError:
295 from ansible.module_utils.basic import AnsibleModule
296 else:
297 from ansible.module_utils.basic import AnsibleModule
298
299 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
300 exists,
301 gen_args,
302 get_device_info,
303 get_subdevice_type,
304 open_session,
305 prepare_payload,
306 session_timeout,
307 update_changed_flag,
308 )
309
310
311 def prepare_argument_spec():
312 argument_spec = {
313 "vcenter_hostname": dict(
314 type="str",
315 required=True,
316 fallback=(env_fallback, ["VMWARE_HOST"]),
317 ),
318 "vcenter_username": dict(
319 type="str",
320 required=True,
321 fallback=(env_fallback, ["VMWARE_USER"]),
322 ),
323 "vcenter_password": dict(
324 type="str",
325 required=True,
326 no_log=True,
327 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
328 ),
329 "vcenter_validate_certs": dict(
330 type="bool",
331 required=False,
332 default=True,
333 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
334 ),
335 "vcenter_rest_log_file": dict(
336 type="str",
337 required=False,
338 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
339 ),
340 "session_timeout": dict(
341 type="float",
342 required=False,
343 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
344 ),
345 }
346
347 argument_spec["backing"] = {"type": "dict"}
348 argument_spec["disk"] = {"type": "str"}
349 argument_spec["ide"] = {"type": "dict"}
350 argument_spec["label"] = {"type": "str"}
351 argument_spec["new_vmdk"] = {"type": "dict"}
352 argument_spec["nvme"] = {"type": "dict"}
353 argument_spec["sata"] = {"type": "dict"}
354 argument_spec["scsi"] = {"type": "dict"}
355 argument_spec["state"] = {
356 "type": "str",
357 "choices": ["absent", "present"],
358 "default": "present",
359 }
360 argument_spec["type"] = {"type": "str", "choices": ["IDE", "NVME", "SATA", "SCSI"]}
361 argument_spec["vm"] = {"required": True, "type": "str"}
362
363 return argument_spec
364
365
366 async def main():
367 required_if = list([])
368
369 module_args = prepare_argument_spec()
370 module = AnsibleModule(
371 argument_spec=module_args, required_if=required_if, supports_check_mode=False
372 )
373 if not module.params["vcenter_hostname"]:
374 module.fail_json("vcenter_hostname cannot be empty")
375 if not module.params["vcenter_username"]:
376 module.fail_json("vcenter_username cannot be empty")
377 if not module.params["vcenter_password"]:
378 module.fail_json("vcenter_password cannot be empty")
379 try:
380 session = await open_session(
381 vcenter_hostname=module.params["vcenter_hostname"],
382 vcenter_username=module.params["vcenter_username"],
383 vcenter_password=module.params["vcenter_password"],
384 validate_certs=module.params["vcenter_validate_certs"],
385 log_file=module.params["vcenter_rest_log_file"],
386 )
387 except Exception as err:
388 if hasattr(err, "get_message"):
389 module.fail_json(err.get_message())
390 else:
391 module.fail_json(str(err))
392 result = await entry_point(module, session)
393 module.exit_json(**result)
394
395
396 # template: default_module.j2
397 def build_url(params):
398 return ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/hardware/disk").format(
399 **params
400 )
401
402
403 async def entry_point(module, session):
404
405 if module.params["state"] == "present":
406 if "_create" in globals():
407 operation = "create"
408 else:
409 operation = "update"
410 elif module.params["state"] == "absent":
411 operation = "delete"
412 else:
413 operation = module.params["state"]
414
415 func = globals()["_" + operation]
416
417 return await func(module.params, session)
418
419
420 async def _create(params, session):
421
422 lookup_url = per_id_url = build_url(params)
423 uniquity_keys = ["disk"]
424 comp_func = None
425
426 async def lookup_with_filters(params, session, url):
427 search_filter = ""
428
429 if "name" not in params:
430 return
431 async with session.get(f"{url}?names={params['name']}{search_filter}") as resp:
432 _json = await resp.json()
433 if isinstance(_json, list) and len(_json) == 1:
434 return await get_device_info(session, url, _json[0]["disk"])
435
436 _json = None
437
438 if params["disk"]:
439 _json = await get_device_info(session, build_url(params), params["disk"])
440
441 if not _json and (uniquity_keys or comp_func):
442 _json = await exists(
443 params,
444 session,
445 url=lookup_url,
446 uniquity_keys=uniquity_keys,
447 per_id_url=per_id_url,
448 comp_func=comp_func,
449 )
450
451 if not _json:
452 _json = await lookup_with_filters(params, session, build_url(params))
453
454 if _json:
455 if "value" not in _json: # 7.0.2+
456 _json = {"value": _json}
457 if "_update" in globals():
458 params["disk"] = _json["id"]
459 return await globals()["_update"](params, session)
460
461 return await update_changed_flag(_json, 200, "get")
462
463 payload = prepare_payload(params, PAYLOAD_FORMAT["create"])
464 _url = ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/hardware/disk").format(
465 **params
466 )
467 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
468 if resp.status == 500:
469 text = await resp.text()
470 raise Exception(f"Request has failed: status={resp.status}, {text}")
471 try:
472 if resp.headers["Content-Type"] == "application/json":
473 _json = await resp.json()
474 except KeyError:
475 _json = {}
476
477 if (resp.status in [200, 201]) and "error" not in _json:
478 if isinstance(_json, str): # 7.0.2 and greater
479 _id = _json # TODO: fetch the object
480 elif isinstance(_json, dict) and "value" not in _json:
481 _id = list(_json["value"].values())[0]
482 elif isinstance(_json, dict) and "value" in _json:
483 _id = _json["value"]
484 _json_device_info = await get_device_info(session, _url, _id)
485 if _json_device_info:
486 _json = _json_device_info
487
488 return await update_changed_flag(_json, resp.status, "create")
489
490
491 async def _delete(params, session):
492 _in_query_parameters = PAYLOAD_FORMAT["delete"]["query"].keys()
493 payload = prepare_payload(params, PAYLOAD_FORMAT["delete"])
494 subdevice_type = get_subdevice_type("/api/vcenter/vm/{vm}/hardware/disk/{disk}")
495 if subdevice_type and not params[subdevice_type]:
496 _json = await exists(params, session, build_url(params))
497 if _json:
498 params[subdevice_type] = _json["id"]
499 _url = (
500 "https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/hardware/disk/{disk}"
501 ).format(**params) + gen_args(params, _in_query_parameters)
502 async with session.delete(_url, json=payload, **session_timeout(params)) as resp:
503 try:
504 if resp.headers["Content-Type"] == "application/json":
505 _json = await resp.json()
506 except KeyError:
507 _json = {}
508 return await update_changed_flag(_json, resp.status, "delete")
509
510
511 async def _update(params, session):
512 payload = prepare_payload(params, PAYLOAD_FORMAT["update"])
513 _url = (
514 "https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/hardware/disk/{disk}"
515 ).format(**params)
516 async with session.get(_url, **session_timeout(params)) as resp:
517 _json = await resp.json()
518 if "value" in _json:
519 value = _json["value"]
520 else: # 7.0.2 and greater
521 value = _json
522 for k, v in value.items():
523 if k in payload:
524 if isinstance(payload[k], dict) and isinstance(v, dict):
525 to_delete = True
526 for _k in list(payload[k].keys()):
527 if payload[k][_k] != v.get(_k):
528 to_delete = False
529 if to_delete:
530 del payload[k]
531 elif payload[k] == v:
532 del payload[k]
533 elif payload[k] == {}:
534 del payload[k]
535
536 if payload == {} or payload == {"spec": {}}:
537 # Nothing has changed
538 if "value" not in _json: # 7.0.2
539 _json = {"value": _json}
540 _json["id"] = params.get("disk")
541 return await update_changed_flag(_json, resp.status, "get")
542 async with session.patch(_url, json=payload, **session_timeout(params)) as resp:
543 try:
544 if resp.headers["Content-Type"] == "application/json":
545 _json = await resp.json()
546 except KeyError:
547 _json = {}
548 if "value" not in _json: # 7.0.2
549 _json = {"value": _json}
550
551 # e.g: content_configuration
552 if not _json and resp.status == 204:
553 async with session.get(_url, **session_timeout(params)) as resp_get:
554 _json_get = await resp_get.json()
555 if _json_get:
556 _json = _json_get
557
558 _json["id"] = params.get("disk")
559 return await update_changed_flag(_json, resp.status, "update")
560
561
562 if __name__ == "__main__":
563 import asyncio
564
565 current_loop = asyncio.new_event_loop()
566 try:
567 asyncio.set_event_loop(current_loop)
568 current_loop.run_until_complete(main())
569 finally:
570 current_loop.close()