Debian Codegraph @

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