Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_vm_hardware_boot_device.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_device
12 short_description: Sets the virtual devices that will be used to boot the virtual
13 machine
14 description: Sets the virtual devices that will be used to boot the virtual machine.
15 The virtual machine will check the devices in order, attempting to boot from each,
16 until the virtual machine boots successfully. If the list is empty, the virtual
17 machine will use a default boot sequence. There should be no more than one instance
18 of Device.Entry for a given device type except ETHERNET in the list.
19 options:
20 devices:
21 description:
22 - Ordered list of boot devices. This parameter is mandatory.
23 - 'Valid attributes are:'
24 - ' - C(type) (str): This option defines the valid device types that may be
25 used as bootable devices. ([''set''])'
26 - ' This key is required with [''set''].'
27 - ' - Accepted values:'
28 - ' - CDROM'
29 - ' - DISK'
30 - ' - ETHERNET'
31 - ' - FLOPPY'
32 - ' - C(nic) (str): Virtual Ethernet device. Ethernet device to use as boot
33 device for this entry.'
34 - This field is optional and it is only relevant when the value of I(type)
35 is ETHERNET.
36 - When clients pass a value of this structure as a parameter, the field must
37 be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_hardware_ethernet).
38 (['set'])
39 - ' - C(disks) (list): Virtual disk device. List of virtual disks in boot
40 order.'
41 - This field is optional and it is only relevant when the value of I(type)
42 is DISK.
43 - When clients pass a value of this structure as a parameter, the field must
44 contain the id of resources returned by M(vmware.vmware_rest.vcenter_vm_hardware_disk).
45 (['set'])
46 elements: dict
47 required: true
48 type: list
49 session_timeout:
50 description:
51 - 'Timeout settings for client session. '
52 - 'The maximal number of seconds for the whole operation including connection
53 establishment, request sending and response. '
54 - The default value is 300s.
55 type: float
56 version_added: 2.1.0
57 state:
58 choices:
59 - set
60 default: set
61 description: []
62 type: str
63 vcenter_hostname:
64 description:
65 - The hostname or IP address of the vSphere vCenter
66 - If the value is not specified in the task, the value of environment variable
67 C(VMWARE_HOST) will be used instead.
68 required: true
69 type: str
70 vcenter_password:
71 description:
72 - The vSphere vCenter password
73 - If the value is not specified in the task, the value of environment variable
74 C(VMWARE_PASSWORD) will be used instead.
75 required: true
76 type: str
77 vcenter_rest_log_file:
78 description:
79 - 'You can use this optional parameter to set the location of a log file. '
80 - 'This file will be used to record the HTTP REST interaction. '
81 - 'The file will be stored on the host that runs the module. '
82 - 'If the value is not specified in the task, the value of '
83 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
84 type: str
85 vcenter_username:
86 description:
87 - The vSphere vCenter username
88 - If the value is not specified in the task, the value of environment variable
89 C(VMWARE_USER) will be used instead.
90 required: true
91 type: str
92 vcenter_validate_certs:
93 default: true
94 description:
95 - Allows connection when SSL certificates are not valid. Set to C(false) when
96 certificates are not trusted.
97 - If the value is not specified in the task, the value of environment variable
98 C(VMWARE_VALIDATE_CERTS) will be used instead.
99 type: bool
100 vm:
101 description:
102 - Virtual machine identifier.
103 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_info).
104 This parameter is mandatory.
105 required: true
106 type: str
107 author:
108 - Ansible Cloud Team (@ansible-collections)
109 version_added: 0.1.0
110 requirements:
111 - vSphere 7.0.3 or greater
112 - python >= 3.6
113 - aiohttp
114 notes:
115 - Tested on vSphere 7.0.3
116 """
117
118 EXAMPLES = r"""
119 - name: Look up the VM called test_vm1 in the inventory
120 register: search_result
121 vmware.vmware_rest.vcenter_vm_info:
122 filter_names:
123 - test_vm1
124
125 - name: Collect information about a specific VM
126 vmware.vmware_rest.vcenter_vm_info:
127 vm: '{{ search_result.value[0].vm }}'
128 register: test_vm1_info
129
130 - name: Set a boot device
131 vmware.vmware_rest.vcenter_vm_hardware_boot_device:
132 vm: '{{ test_vm1_info.id }}'
133 devices:
134 - type: CDROM
135 register: _result
136 """
137 RETURN = r"""
138 # content generated by the update_return_section callback# task: Set a boot device
139 value:
140 description: Set a boot device
141 returned: On success
142 sample: {}
143 type: dict
144 """
145
146
147 # This structure describes the format of the data expected by the end-points
148 PAYLOAD_FORMAT = {
149 "set": {"query": {}, "body": {"devices": "devices"}, "path": {"vm": "vm"}}
150 } # pylint: disable=line-too-long
151
152 from ansible.module_utils.basic import env_fallback
153 import os
154
155 if os.getenv("VMWARE_ENABLE_TURBO", False):
156 try:
157 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
158 AnsibleTurboModule as AnsibleModule,
159 )
160
161 AnsibleModule.collection_name = "vmware.vmware_rest"
162 except ImportError:
163 from ansible.module_utils.basic import AnsibleModule
164 else:
165 from ansible.module_utils.basic import AnsibleModule
166
167 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
168 exists,
169 gen_args,
170 get_subdevice_type,
171 open_session,
172 prepare_payload,
173 session_timeout,
174 update_changed_flag,
175 )
176
177
178 def prepare_argument_spec():
179 argument_spec = {
180 "vcenter_hostname": dict(
181 type="str",
182 required=True,
183 fallback=(env_fallback, ["VMWARE_HOST"]),
184 ),
185 "vcenter_username": dict(
186 type="str",
187 required=True,
188 fallback=(env_fallback, ["VMWARE_USER"]),
189 ),
190 "vcenter_password": dict(
191 type="str",
192 required=True,
193 no_log=True,
194 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
195 ),
196 "vcenter_validate_certs": dict(
197 type="bool",
198 required=False,
199 default=True,
200 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
201 ),
202 "vcenter_rest_log_file": dict(
203 type="str",
204 required=False,
205 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
206 ),
207 "session_timeout": dict(
208 type="float",
209 required=False,
210 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
211 ),
212 }
213
214 argument_spec["devices"] = {"required": True, "type": "list", "elements": "dict"}
215 argument_spec["state"] = {"type": "str", "choices": ["set"], "default": "set"}
216 argument_spec["vm"] = {"required": True, "type": "str"}
217
218 return argument_spec
219
220
221 async def main():
222 required_if = list([])
223
224 module_args = prepare_argument_spec()
225 module = AnsibleModule(
226 argument_spec=module_args, required_if=required_if, supports_check_mode=False
227 )
228 if not module.params["vcenter_hostname"]:
229 module.fail_json("vcenter_hostname cannot be empty")
230 if not module.params["vcenter_username"]:
231 module.fail_json("vcenter_username cannot be empty")
232 if not module.params["vcenter_password"]:
233 module.fail_json("vcenter_password cannot be empty")
234 try:
235 session = await open_session(
236 vcenter_hostname=module.params["vcenter_hostname"],
237 vcenter_username=module.params["vcenter_username"],
238 vcenter_password=module.params["vcenter_password"],
239 validate_certs=module.params["vcenter_validate_certs"],
240 log_file=module.params["vcenter_rest_log_file"],
241 )
242 except Exception as err:
243 if hasattr(err, "get_message"):
244 module.fail_json(err.get_message())
245 else:
246 module.fail_json(str(err))
247 result = await entry_point(module, session)
248 module.exit_json(**result)
249
250
251 # template: default_module.j2
252 def build_url(params):
253 return (
254 "https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/hardware/boot/device"
255 ).format(**params)
256
257
258 async def entry_point(module, session):
259
260 if module.params["state"] == "present":
261 if "_create" in globals():
262 operation = "create"
263 else:
264 operation = "update"
265 elif module.params["state"] == "absent":
266 operation = "delete"
267 else:
268 operation = module.params["state"]
269
270 func = globals()["_" + operation]
271
272 return await func(module.params, session)
273
274
275 async def _set(params, session):
276 _in_query_parameters = PAYLOAD_FORMAT["set"]["query"].keys()
277 payload = prepare_payload(params, PAYLOAD_FORMAT["set"])
278 subdevice_type = get_subdevice_type("/api/vcenter/vm/{vm}/hardware/boot/device")
279 if subdevice_type and not params[subdevice_type]:
280 _json = await exists(params, session, build_url(params))
281 if _json:
282 params[subdevice_type] = _json["id"]
283 _url = (
284 "https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/hardware/boot/device"
285 ).format(**params) + gen_args(params, _in_query_parameters)
286 async with session.get(_url, json=payload, **session_timeout(params)) as resp:
287 before = await resp.json()
288
289 async with session.put(_url, json=payload, **session_timeout(params)) as resp:
290 try:
291 if resp.headers["Content-Type"] == "application/json":
292 _json = await resp.json()
293 except KeyError:
294 _json = {}
295 if "value" not in _json: # 7.0.2
296 _json = {"value": _json}
297
298 # The PUT answer does not let us know if the resource has actually been
299 # modified
300 if resp.status < 300:
301 async with session.get(
302 _url, json=payload, **session_timeout(params)
303 ) as resp_get:
304 after = await resp_get.json()
305 if before == after:
306 return await update_changed_flag(after, resp_get.status, "get")
307 return await update_changed_flag(_json, resp.status, "set")
308
309
310 if __name__ == "__main__":
311 import asyncio
312
313 current_loop = asyncio.new_event_loop()
314 try:
315 asyncio.set_event_loop(current_loop)
316 current_loop.run_until_complete(main())
317 finally:
318 current_loop.close()