Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_vm_hardware.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
12 short_description: Updates the virtual hardware settings of a virtual machine.
13 description: Updates the virtual hardware settings of a virtual machine.
14 options:
15 session_timeout:
16 description:
17 - 'Timeout settings for client session. '
18 - 'The maximal number of seconds for the whole operation including connection
19 establishment, request sending and response. '
20 - The default value is 300s.
21 type: float
22 version_added: 2.1.0
23 state:
24 choices:
25 - present
26 - upgrade
27 default: present
28 description: []
29 type: str
30 upgrade_policy:
31 choices:
32 - AFTER_CLEAN_SHUTDOWN
33 - ALWAYS
34 - NEVER
35 description:
36 - The I(upgrade_policy) enumerated type defines the valid virtual hardware
37 upgrade policies for a virtual machine.
38 type: str
39 upgrade_version:
40 choices:
41 - VMX_03
42 - VMX_04
43 - VMX_06
44 - VMX_07
45 - VMX_08
46 - VMX_09
47 - VMX_10
48 - VMX_11
49 - VMX_12
50 - VMX_13
51 - VMX_14
52 - VMX_15
53 - VMX_16
54 - VMX_17
55 - VMX_18
56 - VMX_19
57 - VMX_20
58 - VMX_21
59 description:
60 - The I(version) enumerated type defines the valid virtual hardware versions
61 for a virtual machine. See https://kb.vmware.com/s/article/1003746 (Virtual
62 machine hardware versions (1003746)).
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 version:
102 choices:
103 - VMX_03
104 - VMX_04
105 - VMX_06
106 - VMX_07
107 - VMX_08
108 - VMX_09
109 - VMX_10
110 - VMX_11
111 - VMX_12
112 - VMX_13
113 - VMX_14
114 - VMX_15
115 - VMX_16
116 - VMX_17
117 - VMX_18
118 - VMX_19
119 - VMX_20
120 - VMX_21
121 description:
122 - The I(version) enumerated type defines the valid virtual hardware versions
123 for a virtual machine. See https://kb.vmware.com/s/article/1003746 (Virtual
124 machine hardware versions (1003746)).
125 type: str
126 vm:
127 description:
128 - Virtual machine identifier.
129 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_info).
130 This parameter is mandatory.
131 required: true
132 type: str
133 author:
134 - Ansible Cloud Team (@ansible-collections)
135 version_added: 0.1.0
136 requirements:
137 - vSphere 7.0.3 or greater
138 - python >= 3.6
139 - aiohttp
140 notes:
141 - Tested on vSphere 7.0.3
142 """
143
144 EXAMPLES = r"""
145 - name: Upgrade the VM hardware version
146 vmware.vmware_rest.vcenter_vm_hardware:
147 upgrade_policy: AFTER_CLEAN_SHUTDOWN
148 upgrade_version: VMX_11
149 vm: "{{ lookup('vmware.vmware_rest.vm_moid', '/my_dc/vm/test_vm1') }}"
150 register: _result
151 """
152 RETURN = r"""
153 # content generated by the update_return_section callback# task: Upgrade the VM hardware version
154 id:
155 description: moid of the resource
156 returned: On success
157 sample: null
158 type: dict
159 value:
160 description: Upgrade the VM hardware version
161 returned: On success
162 sample: {}
163 type: dict
164 """
165
166
167 # This structure describes the format of the data expected by the end-points
168 PAYLOAD_FORMAT = {
169 "update": {
170 "query": {},
171 "body": {
172 "upgrade_policy": "upgrade_policy",
173 "upgrade_version": "upgrade_version",
174 },
175 "path": {"vm": "vm"},
176 },
177 "upgrade": {"query": {}, "body": {"version": "version"}, "path": {"vm": "vm"}},
178 } # pylint: disable=line-too-long
179
180 from ansible.module_utils.basic import env_fallback
181 import os
182
183 if os.getenv("VMWARE_ENABLE_TURBO", False):
184 try:
185 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
186 AnsibleTurboModule as AnsibleModule,
187 )
188
189 AnsibleModule.collection_name = "vmware.vmware_rest"
190 except ImportError:
191 from ansible.module_utils.basic import AnsibleModule
192 else:
193 from ansible.module_utils.basic import AnsibleModule
194
195 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
196 exists,
197 gen_args,
198 get_subdevice_type,
199 open_session,
200 prepare_payload,
201 session_timeout,
202 update_changed_flag,
203 )
204
205
206 def prepare_argument_spec():
207 argument_spec = {
208 "vcenter_hostname": dict(
209 type="str",
210 required=True,
211 fallback=(env_fallback, ["VMWARE_HOST"]),
212 ),
213 "vcenter_username": dict(
214 type="str",
215 required=True,
216 fallback=(env_fallback, ["VMWARE_USER"]),
217 ),
218 "vcenter_password": dict(
219 type="str",
220 required=True,
221 no_log=True,
222 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
223 ),
224 "vcenter_validate_certs": dict(
225 type="bool",
226 required=False,
227 default=True,
228 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
229 ),
230 "vcenter_rest_log_file": dict(
231 type="str",
232 required=False,
233 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
234 ),
235 "session_timeout": dict(
236 type="float",
237 required=False,
238 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
239 ),
240 }
241
242 argument_spec["state"] = {
243 "type": "str",
244 "choices": ["present", "upgrade"],
245 "default": "present",
246 }
247 argument_spec["upgrade_policy"] = {
248 "type": "str",
249 "choices": ["AFTER_CLEAN_SHUTDOWN", "ALWAYS", "NEVER"],
250 }
251 argument_spec["upgrade_version"] = {
252 "type": "str",
253 "choices": [
254 "VMX_03",
255 "VMX_04",
256 "VMX_06",
257 "VMX_07",
258 "VMX_08",
259 "VMX_09",
260 "VMX_10",
261 "VMX_11",
262 "VMX_12",
263 "VMX_13",
264 "VMX_14",
265 "VMX_15",
266 "VMX_16",
267 "VMX_17",
268 "VMX_18",
269 "VMX_19",
270 "VMX_20",
271 "VMX_21",
272 ],
273 }
274 argument_spec["version"] = {
275 "type": "str",
276 "choices": [
277 "VMX_03",
278 "VMX_04",
279 "VMX_06",
280 "VMX_07",
281 "VMX_08",
282 "VMX_09",
283 "VMX_10",
284 "VMX_11",
285 "VMX_12",
286 "VMX_13",
287 "VMX_14",
288 "VMX_15",
289 "VMX_16",
290 "VMX_17",
291 "VMX_18",
292 "VMX_19",
293 "VMX_20",
294 "VMX_21",
295 ],
296 }
297 argument_spec["vm"] = {"required": True, "type": "str"}
298
299 return argument_spec
300
301
302 async def main():
303 required_if = list([])
304
305 module_args = prepare_argument_spec()
306 module = AnsibleModule(
307 argument_spec=module_args, required_if=required_if, supports_check_mode=False
308 )
309 if not module.params["vcenter_hostname"]:
310 module.fail_json("vcenter_hostname cannot be empty")
311 if not module.params["vcenter_username"]:
312 module.fail_json("vcenter_username cannot be empty")
313 if not module.params["vcenter_password"]:
314 module.fail_json("vcenter_password cannot be empty")
315 try:
316 session = await open_session(
317 vcenter_hostname=module.params["vcenter_hostname"],
318 vcenter_username=module.params["vcenter_username"],
319 vcenter_password=module.params["vcenter_password"],
320 validate_certs=module.params["vcenter_validate_certs"],
321 log_file=module.params["vcenter_rest_log_file"],
322 )
323 except Exception as err:
324 if hasattr(err, "get_message"):
325 module.fail_json(err.get_message())
326 else:
327 module.fail_json(str(err))
328 result = await entry_point(module, session)
329 module.exit_json(**result)
330
331
332 # template: default_module.j2
333 def build_url(params):
334 return ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/hardware").format(
335 **params
336 )
337
338
339 async def entry_point(module, session):
340
341 if module.params["state"] == "present":
342 if "_create" in globals():
343 operation = "create"
344 else:
345 operation = "update"
346 elif module.params["state"] == "absent":
347 operation = "delete"
348 else:
349 operation = module.params["state"]
350
351 func = globals()["_" + operation]
352
353 return await func(module.params, session)
354
355
356 async def _update(params, session):
357 payload = prepare_payload(params, PAYLOAD_FORMAT["update"])
358 _url = ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/hardware").format(
359 **params
360 )
361 async with session.get(_url, **session_timeout(params)) as resp:
362 _json = await resp.json()
363 if "value" in _json:
364 value = _json["value"]
365 else: # 7.0.2 and greater
366 value = _json
367 for k, v in value.items():
368 if k in payload:
369 if isinstance(payload[k], dict) and isinstance(v, dict):
370 to_delete = True
371 for _k in list(payload[k].keys()):
372 if payload[k][_k] != v.get(_k):
373 to_delete = False
374 if to_delete:
375 del payload[k]
376 elif payload[k] == v:
377 del payload[k]
378 elif payload[k] == {}:
379 del payload[k]
380
381 if payload == {} or payload == {"spec": {}}:
382 # Nothing has changed
383 if "value" not in _json: # 7.0.2
384 _json = {"value": _json}
385 _json["id"] = params.get("None")
386 return await update_changed_flag(_json, resp.status, "get")
387 async with session.patch(_url, json=payload, **session_timeout(params)) as resp:
388 try:
389 if resp.headers["Content-Type"] == "application/json":
390 _json = await resp.json()
391 except KeyError:
392 _json = {}
393 if "value" not in _json: # 7.0.2
394 _json = {"value": _json}
395
396 # e.g: content_configuration
397 if not _json and resp.status == 204:
398 async with session.get(_url, **session_timeout(params)) as resp_get:
399 _json_get = await resp_get.json()
400 if _json_get:
401 _json = _json_get
402
403 _json["id"] = params.get("None")
404 return await update_changed_flag(_json, resp.status, "update")
405
406
407 async def _upgrade(params, session):
408 _in_query_parameters = PAYLOAD_FORMAT["upgrade"]["query"].keys()
409 payload = prepare_payload(params, PAYLOAD_FORMAT["upgrade"])
410 subdevice_type = get_subdevice_type("/api/vcenter/vm/{vm}/hardware?action=upgrade")
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?action=upgrade"
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, "upgrade")
430
431
432 if __name__ == "__main__":
433 import asyncio
434
435 current_loop = asyncio.new_event_loop()
436 try:
437 asyncio.set_event_loop(current_loop)
438 current_loop.run_until_complete(main())
439 finally:
440 current_loop.close()