Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_vm_hardware_serial_info.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_info
12 short_description: Returns information about a virtual serial port.
13 description: Returns information about a virtual serial port.
14 options:
15 label:
16 description:
17 - The name of the item
18 type: str
19 port:
20 description:
21 - Virtual serial port identifier.
22 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_hardware_serial).
23 Required with I(state=['get'])
24 type: str
25 session_timeout:
26 description:
27 - 'Timeout settings for client session. '
28 - 'The maximal number of seconds for the whole operation including connection
29 establishment, request sending and response. '
30 - The default value is 300s.
31 type: float
32 version_added: 2.1.0
33 vcenter_hostname:
34 description:
35 - The hostname or IP address of the vSphere vCenter
36 - If the value is not specified in the task, the value of environment variable
37 C(VMWARE_HOST) will be used instead.
38 required: true
39 type: str
40 vcenter_password:
41 description:
42 - The vSphere vCenter password
43 - If the value is not specified in the task, the value of environment variable
44 C(VMWARE_PASSWORD) will be used instead.
45 required: true
46 type: str
47 vcenter_rest_log_file:
48 description:
49 - 'You can use this optional parameter to set the location of a log file. '
50 - 'This file will be used to record the HTTP REST interaction. '
51 - 'The file will be stored on the host that runs the module. '
52 - 'If the value is not specified in the task, the value of '
53 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
54 type: str
55 vcenter_username:
56 description:
57 - The vSphere vCenter username
58 - If the value is not specified in the task, the value of environment variable
59 C(VMWARE_USER) will be used instead.
60 required: true
61 type: str
62 vcenter_validate_certs:
63 default: true
64 description:
65 - Allows connection when SSL certificates are not valid. Set to C(false) when
66 certificates are not trusted.
67 - If the value is not specified in the task, the value of environment variable
68 C(VMWARE_VALIDATE_CERTS) will be used instead.
69 type: bool
70 vm:
71 description:
72 - Virtual machine identifier.
73 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_info).
74 This parameter is mandatory.
75 required: true
76 type: str
77 author:
78 - Ansible Cloud Team (@ansible-collections)
79 version_added: 0.1.0
80 requirements:
81 - vSphere 7.0.3 or greater
82 - python >= 3.6
83 - aiohttp
84 notes:
85 - Tested on vSphere 7.0.3
86 """
87
88 EXAMPLES = r"""
89 - name: Look up the VM called test_vm1 in the inventory
90 register: search_result
91 vmware.vmware_rest.vcenter_vm_info:
92 filter_names:
93 - test_vm1
94
95 - name: Collect information about a specific VM
96 vmware.vmware_rest.vcenter_vm_info:
97 vm: '{{ search_result.value[0].vm }}'
98 register: test_vm1_info
99
100 - name: Retrieve the serial ports information from the VM
101 vmware.vmware_rest.vcenter_vm_hardware_serial_info:
102 vm: '{{ test_vm1_info.id }}'
103 register: _result
104
105 - name: Get an existing serial port (label)
106 vmware.vmware_rest.vcenter_vm_hardware_serial_info:
107 vm: '{{ test_vm1_info.id }}'
108 label: Serial port 1
109 register: serial_port_1
110 """
111 RETURN = r"""
112 # content generated by the update_return_section callback# task: Get an existing serial port (label)
113 id:
114 description: moid of the resource
115 returned: On success
116 sample: '9000'
117 type: str
118 value:
119 description: Get an existing serial port (label)
120 returned: On success
121 sample:
122 allow_guest_control: 1
123 backing:
124 auto_detect: 1
125 host_device: ''
126 type: HOST_DEVICE
127 label: Serial port 1
128 start_connected: 0
129 state: NOT_CONNECTED
130 yield_on_poll: 0
131 type: dict
132 """
133
134
135 # This structure describes the format of the data expected by the end-points
136 PAYLOAD_FORMAT = {
137 "get": {"query": {}, "body": {}, "path": {"port": "port", "vm": "vm"}},
138 "list": {"query": {}, "body": {}, "path": {"vm": "vm"}},
139 } # pylint: disable=line-too-long
140
141 from ansible.module_utils.basic import env_fallback
142 import os
143
144 if os.getenv("VMWARE_ENABLE_TURBO", False):
145 try:
146 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
147 AnsibleTurboModule as AnsibleModule,
148 )
149
150 AnsibleModule.collection_name = "vmware.vmware_rest"
151 except ImportError:
152 from ansible.module_utils.basic import AnsibleModule
153 else:
154 from ansible.module_utils.basic import AnsibleModule
155
156 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
157 build_full_device_list,
158 exists,
159 gen_args,
160 open_session,
161 session_timeout,
162 update_changed_flag,
163 )
164
165
166 def prepare_argument_spec():
167 argument_spec = {
168 "vcenter_hostname": dict(
169 type="str",
170 required=True,
171 fallback=(env_fallback, ["VMWARE_HOST"]),
172 ),
173 "vcenter_username": dict(
174 type="str",
175 required=True,
176 fallback=(env_fallback, ["VMWARE_USER"]),
177 ),
178 "vcenter_password": dict(
179 type="str",
180 required=True,
181 no_log=True,
182 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
183 ),
184 "vcenter_validate_certs": dict(
185 type="bool",
186 required=False,
187 default=True,
188 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
189 ),
190 "vcenter_rest_log_file": dict(
191 type="str",
192 required=False,
193 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
194 ),
195 "session_timeout": dict(
196 type="float",
197 required=False,
198 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
199 ),
200 }
201
202 argument_spec["label"] = {"type": "str"}
203 argument_spec["port"] = {"type": "str"}
204 argument_spec["vm"] = {"required": True, "type": "str"}
205
206 return argument_spec
207
208
209 async def main():
210 required_if = list([])
211
212 module_args = prepare_argument_spec()
213 module = AnsibleModule(
214 argument_spec=module_args, required_if=required_if, supports_check_mode=True
215 )
216 if not module.params["vcenter_hostname"]:
217 module.fail_json("vcenter_hostname cannot be empty")
218 if not module.params["vcenter_username"]:
219 module.fail_json("vcenter_username cannot be empty")
220 if not module.params["vcenter_password"]:
221 module.fail_json("vcenter_password cannot be empty")
222 try:
223 session = await open_session(
224 vcenter_hostname=module.params["vcenter_hostname"],
225 vcenter_username=module.params["vcenter_username"],
226 vcenter_password=module.params["vcenter_password"],
227 validate_certs=module.params["vcenter_validate_certs"],
228 log_file=module.params["vcenter_rest_log_file"],
229 )
230 except Exception as err:
231 if hasattr(err, "get_message"):
232 module.fail_json(err.get_message())
233 else:
234 module.fail_json(str(err))
235 result = await entry_point(module, session)
236 module.exit_json(**result)
237
238
239 # template: info_list_and_get_module.j2
240 def build_url(params):
241 import yarl
242
243 if params.get("port"):
244 _in_query_parameters = PAYLOAD_FORMAT["get"]["query"].keys()
245 return yarl.URL(
246 (
247 "https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/hardware/serial/"
248 ).format(**params)
249 + params["port"]
250 + gen_args(params, _in_query_parameters),
251 encoded=True,
252 )
253 _in_query_parameters = PAYLOAD_FORMAT["list"]["query"].keys()
254 return yarl.URL(
255 ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/hardware/serial").format(
256 **params
257 )
258 + gen_args(params, _in_query_parameters),
259 encoded=True,
260 )
261
262
263 async def entry_point(module, session):
264 url = build_url(module.params)
265 async with session.get(url, **session_timeout(module.params)) as resp:
266 _json = await resp.json()
267
268 if "value" not in _json: # 7.0.2+
269 _json = {"value": _json}
270
271 if module.params.get("port"):
272 _json["id"] = module.params.get("port")
273 elif module.params.get("label"): # TODO extend the list of filter
274 _json = await exists(module.params, session, str(url))
275 elif (
276 isinstance(_json["value"], list)
277 and len(_json["value"]) > 0
278 and isinstance(_json["value"][0], str)
279 ):
280 # this is a list of id, we fetch the details
281 full_device_list = await build_full_device_list(session, str(url), _json)
282 _json = {"value": [i["value"] for i in full_device_list]}
283
284 return await update_changed_flag(_json, resp.status, "get")
285
286
287 if __name__ == "__main__":
288 import asyncio
289
290 current_loop = asyncio.new_event_loop()
291 try:
292 asyncio.set_event_loop(current_loop)
293 current_loop.run_until_complete(main())
294 finally:
295 current_loop.close()