Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_vm_hardware_boot.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_boot
12 short_description: Updates the boot-related settings of a virtual machine.
13 description: Updates the boot-related settings of a virtual machine.
14 options:
15 delay:
16 description:
17 - Delay in milliseconds before beginning the firmware boot process when the
18 virtual machine is powered on. This delay may be used to provide a time
19 window for users to connect to the virtual machine console and enter BIOS
20 setup mode.
21 - If unset, the value is unchanged.
22 type: int
23 efi_legacy_boot:
24 description:
25 - Flag indicating whether to use EFI legacy boot mode.
26 - If unset, the value is unchanged.
27 type: bool
28 enter_setup_mode:
29 description:
30 - Flag indicating whether the firmware boot process should automatically enter
31 setup mode the next time the virtual machine boots. Note that this flag
32 will automatically be reset to false once the virtual machine enters setup
33 mode.
34 - If unset, the value is unchanged.
35 type: bool
36 network_protocol:
37 choices:
38 - IPV4
39 - IPV6
40 description:
41 - The I(network_protocol) enumerated type defines the valid network boot protocols
42 supported when booting a virtual machine with EFI firmware over the network.
43 type: str
44 retry:
45 description:
46 - Flag indicating whether the virtual machine should automatically retry the
47 boot process after a failure.
48 - If unset, the value is unchanged.
49 type: bool
50 retry_delay:
51 description:
52 - Delay in milliseconds before retrying the boot process after a failure;
53 applicable only when I(retry) is true.
54 - If unset, the value is unchanged.
55 type: int
56 session_timeout:
57 description:
58 - 'Timeout settings for client session. '
59 - 'The maximal number of seconds for the whole operation including connection
60 establishment, request sending and response. '
61 - The default value is 300s.
62 type: float
63 version_added: 2.1.0
64 state:
65 choices:
66 - present
67 default: present
68 description: []
69 type: str
70 type:
71 choices:
72 - BIOS
73 - EFI
74 description:
75 - The I(type) enumerated type defines the valid firmware types for a virtual
76 machine.
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: Change a VM boot parameters
146 vmware.vmware_rest.vcenter_vm_hardware_boot:
147 vm: '{{ test_vm1_info.id }}'
148 efi_legacy_boot: true
149 type: EFI
150 register: _result
151 """
152 RETURN = r"""
153 # content generated by the update_return_section callback# task: Change a VM boot parameters
154 id:
155 description: moid of the resource
156 returned: On success
157 sample: null
158 type: dict
159 value:
160 description: Change a VM boot parameters
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 "delay": "delay",
173 "efi_legacy_boot": "efi_legacy_boot",
174 "enter_setup_mode": "enter_setup_mode",
175 "network_protocol": "network_protocol",
176 "retry": "retry",
177 "retry_delay": "retry_delay",
178 "type": "type",
179 },
180 "path": {"vm": "vm"},
181 }
182 } # pylint: disable=line-too-long
183
184 from ansible.module_utils.basic import env_fallback
185 import os
186
187 if os.getenv("VMWARE_ENABLE_TURBO", False):
188 try:
189 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
190 AnsibleTurboModule as AnsibleModule,
191 )
192
193 AnsibleModule.collection_name = "vmware.vmware_rest"
194 except ImportError:
195 from ansible.module_utils.basic import AnsibleModule
196 else:
197 from ansible.module_utils.basic import AnsibleModule
198
199 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
200 open_session,
201 prepare_payload,
202 session_timeout,
203 update_changed_flag,
204 )
205
206
207 def prepare_argument_spec():
208 argument_spec = {
209 "vcenter_hostname": dict(
210 type="str",
211 required=True,
212 fallback=(env_fallback, ["VMWARE_HOST"]),
213 ),
214 "vcenter_username": dict(
215 type="str",
216 required=True,
217 fallback=(env_fallback, ["VMWARE_USER"]),
218 ),
219 "vcenter_password": dict(
220 type="str",
221 required=True,
222 no_log=True,
223 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
224 ),
225 "vcenter_validate_certs": dict(
226 type="bool",
227 required=False,
228 default=True,
229 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
230 ),
231 "vcenter_rest_log_file": dict(
232 type="str",
233 required=False,
234 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
235 ),
236 "session_timeout": dict(
237 type="float",
238 required=False,
239 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
240 ),
241 }
242
243 argument_spec["delay"] = {"type": "int"}
244 argument_spec["efi_legacy_boot"] = {"type": "bool"}
245 argument_spec["enter_setup_mode"] = {"type": "bool"}
246 argument_spec["network_protocol"] = {"type": "str", "choices": ["IPV4", "IPV6"]}
247 argument_spec["retry"] = {"type": "bool"}
248 argument_spec["retry_delay"] = {"type": "int"}
249 argument_spec["state"] = {
250 "type": "str",
251 "choices": ["present"],
252 "default": "present",
253 }
254 argument_spec["type"] = {"type": "str", "choices": ["BIOS", "EFI"]}
255 argument_spec["vm"] = {"required": True, "type": "str"}
256
257 return argument_spec
258
259
260 async def main():
261 required_if = list([])
262
263 module_args = prepare_argument_spec()
264 module = AnsibleModule(
265 argument_spec=module_args, required_if=required_if, supports_check_mode=False
266 )
267 if not module.params["vcenter_hostname"]:
268 module.fail_json("vcenter_hostname cannot be empty")
269 if not module.params["vcenter_username"]:
270 module.fail_json("vcenter_username cannot be empty")
271 if not module.params["vcenter_password"]:
272 module.fail_json("vcenter_password cannot be empty")
273 try:
274 session = await open_session(
275 vcenter_hostname=module.params["vcenter_hostname"],
276 vcenter_username=module.params["vcenter_username"],
277 vcenter_password=module.params["vcenter_password"],
278 validate_certs=module.params["vcenter_validate_certs"],
279 log_file=module.params["vcenter_rest_log_file"],
280 )
281 except Exception as err:
282 if hasattr(err, "get_message"):
283 module.fail_json(err.get_message())
284 else:
285 module.fail_json(str(err))
286 result = await entry_point(module, session)
287 module.exit_json(**result)
288
289
290 # template: default_module.j2
291 def build_url(params):
292 return ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/hardware/boot").format(
293 **params
294 )
295
296
297 async def entry_point(module, session):
298
299 if module.params["state"] == "present":
300 if "_create" in globals():
301 operation = "create"
302 else:
303 operation = "update"
304 elif module.params["state"] == "absent":
305 operation = "delete"
306 else:
307 operation = module.params["state"]
308
309 func = globals()["_" + operation]
310
311 return await func(module.params, session)
312
313
314 async def _update(params, session):
315 payload = prepare_payload(params, PAYLOAD_FORMAT["update"])
316 _url = ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/hardware/boot").format(
317 **params
318 )
319 async with session.get(_url, **session_timeout(params)) as resp:
320 _json = await resp.json()
321 if "value" in _json:
322 value = _json["value"]
323 else: # 7.0.2 and greater
324 value = _json
325 for k, v in value.items():
326 if k in payload:
327 if isinstance(payload[k], dict) and isinstance(v, dict):
328 to_delete = True
329 for _k in list(payload[k].keys()):
330 if payload[k][_k] != v.get(_k):
331 to_delete = False
332 if to_delete:
333 del payload[k]
334 elif payload[k] == v:
335 del payload[k]
336 elif payload[k] == {}:
337 del payload[k]
338
339 if payload == {} or payload == {"spec": {}}:
340 # Nothing has changed
341 if "value" not in _json: # 7.0.2
342 _json = {"value": _json}
343 _json["id"] = params.get("None")
344 return await update_changed_flag(_json, resp.status, "get")
345 async with session.patch(_url, json=payload, **session_timeout(params)) as resp:
346 try:
347 if resp.headers["Content-Type"] == "application/json":
348 _json = await resp.json()
349 except KeyError:
350 _json = {}
351 if "value" not in _json: # 7.0.2
352 _json = {"value": _json}
353
354 # e.g: content_configuration
355 if not _json and resp.status == 204:
356 async with session.get(_url, **session_timeout(params)) as resp_get:
357 _json_get = await resp_get.json()
358 if _json_get:
359 _json = _json_get
360
361 _json["id"] = params.get("None")
362 return await update_changed_flag(_json, resp.status, "update")
363
364
365 if __name__ == "__main__":
366 import asyncio
367
368 current_loop = asyncio.new_event_loop()
369 try:
370 asyncio.set_event_loop(current_loop)
371 current_loop.run_until_complete(main())
372 finally:
373 current_loop.close()