Debian Codegraph @

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