Debian Codegraph @

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