Debian Codegraph @

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