Debian Codegraph @

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