Debian Codegraph @

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