Debian Codegraph @

ansible_collections/community/vmware/plugins/modules/vmware_guest_boot_manager.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Ansible Project
5 # Copyright: (c) 2018, Abhijeet Kasurde <[email protected]>
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import absolute_import, division, print_function
10 __metaclass__ = type
11
12
13 DOCUMENTATION = r'''
14 ---
15 module: vmware_guest_boot_manager
16 short_description: Manage boot options for the given virtual machine
17 description:
18 - This module can be used to manage boot options for the given virtual machine.
19 author:
20 - Abhijeet Kasurde (@Akasurde) <[email protected]>
21 options:
22 name:
23 description:
24 - Name of the VM to work with.
25 - This is required if O(uuid) or O(moid) parameter is not supplied.
26 type: str
27 uuid:
28 description:
29 - UUID of the instance to manage if known, this is VMware's BIOS UUID by default.
30 - This is required if O(name) or O(moid) parameter is not supplied.
31 type: str
32 moid:
33 description:
34 - Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance.
35 - This is required if O(name) or O(uuid) is not supplied.
36 type: str
37 use_instance_uuid:
38 description:
39 - Whether to use the VMware instance UUID rather than the BIOS UUID.
40 default: false
41 type: bool
42 name_match:
43 description:
44 - If multiple virtual machines matching the name, use the first or last found.
45 default: 'first'
46 choices: ['first', 'last']
47 type: str
48 boot_order:
49 description:
50 - List of the boot devices.
51 default: []
52 type: list
53 elements: str
54 boot_hdd_name:
55 description:
56 - This parameter is optional, if not set, will use the first virtual disk found in VM device list.
57 type: str
58 version_added: '3.2.0'
59 boot_delay:
60 description:
61 - Delay in milliseconds before starting the boot sequence.
62 type: int
63 enter_bios_setup:
64 description:
65 - If set to V(true), the virtual machine automatically enters BIOS setup the next time it boots.
66 - The virtual machine resets this flag, so that the machine boots proceeds normally.
67 type: 'bool'
68 boot_retry_enabled:
69 description:
70 - If set to V(true), the virtual machine that fails to boot, will try to boot again after O(boot_retry_delay) is expired.
71 - If set to V(false), the virtual machine waits indefinitely for user intervention.
72 type: 'bool'
73 boot_retry_delay:
74 description:
75 - Specify the time in milliseconds between virtual machine boot failure and subsequent attempt to boot again.
76 - If set, will automatically set O(boot_retry_enabled=true) as this parameter is required.
77 type: int
78 boot_firmware:
79 description:
80 - Choose which firmware should be used to boot the virtual machine.
81 choices: ["bios", "efi"]
82 type: str
83 secure_boot_enabled:
84 description:
85 - Choose if EFI secure boot should be enabled. EFI secure boot can only be enabled with boot_firmware = efi
86 type: 'bool'
87 extends_documentation_fragment:
88 - vmware.vmware.base_options
89
90 '''
91
92 EXAMPLES = r'''
93 - name: Change virtual machine's boot order and related parameters
94 community.vmware.vmware_guest_boot_manager:
95 hostname: "{{ vcenter_hostname }}"
96 username: "{{ vcenter_username }}"
97 password: "{{ vcenter_password }}"
98 name: testvm
99 boot_delay: 2000
100 enter_bios_setup: true
101 boot_retry_enabled: true
102 boot_retry_delay: 22300
103 boot_firmware: bios
104 secure_boot_enabled: false
105 boot_order:
106 - floppy
107 - cdrom
108 - ethernet
109 - disk
110 delegate_to: localhost
111 register: vm_boot_order
112
113 - name: Change virtual machine's boot order using Virtual Machine MoID
114 community.vmware.vmware_guest_boot_manager:
115 hostname: "{{ vcenter_hostname }}"
116 username: "{{ vcenter_username }}"
117 password: "{{ vcenter_password }}"
118 moid: vm-42
119 boot_delay: 2000
120 enter_bios_setup: true
121 boot_retry_enabled: true
122 boot_retry_delay: 22300
123 boot_firmware: bios
124 secure_boot_enabled: false
125 boot_order:
126 - floppy
127 - cdrom
128 - ethernet
129 - disk
130 delegate_to: localhost
131 register: vm_boot_order
132 '''
133
134 RETURN = r'''
135 vm_boot_status:
136 description: metadata about boot order of virtual machine
137 returned: always
138 type: dict
139 sample: {
140 "current_boot_order": [
141 "floppy",
142 "disk",
143 "ethernet",
144 "cdrom"
145 ],
146 "current_boot_delay": 2000,
147 "current_boot_retry_delay": 22300,
148 "current_boot_retry_enabled": true,
149 "current_enter_bios_setup": true,
150 "current_boot_firmware": "bios",
151 "current_secure_boot_enabled": false,
152 "previous_boot_delay": 10,
153 "previous_boot_retry_delay": 10000,
154 "previous_boot_retry_enabled": true,
155 "previous_enter_bios_setup": false,
156 "previous_boot_firmware": "efi",
157 "previous_secure_boot_enabled": true,
158 "previous_boot_order": [
159 "ethernet",
160 "cdrom",
161 "floppy",
162 "disk"
163 ],
164 }
165 '''
166
167
168 from ansible.module_utils.basic import AnsibleModule
169 from ansible.module_utils.common.text.converters import to_native
170 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi, find_vm_by_id, wait_for_task, TaskError
171 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
172
173 try:
174 from pyVmomi import vim, VmomiJSONEncoder
175 except ImportError:
176 pass
177
178
179 class VmBootManager(PyVmomi):
180 def __init__(self, module):
181 super(VmBootManager, self).__init__(module)
182 self.name = self.params['name']
183 self.uuid = self.params['uuid']
184 self.moid = self.params['moid']
185 self.use_instance_uuid = self.params['use_instance_uuid']
186 self.vm = None
187
188 def _get_vm(self):
189 vms = []
190
191 if self.uuid:
192 if self.use_instance_uuid:
193 vm_obj = find_vm_by_id(self.content, vm_id=self.uuid, vm_id_type="instance_uuid")
194 else:
195 vm_obj = find_vm_by_id(self.content, vm_id=self.uuid, vm_id_type="uuid")
196 if vm_obj is None:
197 self.module.fail_json(msg="Failed to find the virtual machine with UUID : %s" % self.uuid)
198 vms = [vm_obj]
199
200 elif self.name:
201 objects = self.get_managed_objects_properties(vim_type=vim.VirtualMachine, properties=['name'])
202 for temp_vm_object in objects:
203 if temp_vm_object.obj.name == self.name:
204 vms.append(temp_vm_object.obj)
205
206 elif self.moid:
207 vm_obj = VmomiJSONEncoder.templateOf('VirtualMachine')(self.module.params['moid'], self.si._stub)
208 if vm_obj:
209 vms.append(vm_obj)
210
211 if vms:
212 if self.params.get('name_match') == 'first':
213 self.vm = vms[0]
214 elif self.params.get('name_match') == 'last':
215 self.vm = vms[-1]
216 else:
217 self.module.fail_json(msg="Failed to find virtual machine using %s" % (self.name or self.uuid))
218
219 @staticmethod
220 def humanize_boot_order(boot_order):
221 results = []
222 for device in boot_order:
223 if isinstance(device, vim.vm.BootOptions.BootableCdromDevice):
224 results.append('cdrom')
225 elif isinstance(device, vim.vm.BootOptions.BootableDiskDevice):
226 results.append('disk')
227 elif isinstance(device, vim.vm.BootOptions.BootableEthernetDevice):
228 results.append('ethernet')
229 elif isinstance(device, vim.vm.BootOptions.BootableFloppyDevice):
230 results.append('floppy')
231 return results
232
233 def ensure(self):
234 boot_order_list = []
235 change_needed = False
236 kwargs = dict()
237 previous_boot_disk = None
238 valid_device_strings = ['cdrom', 'disk', 'ethernet', 'floppy']
239
240 self._get_vm()
241
242 for device_order in self.params.get('boot_order'):
243 if device_order not in valid_device_strings:
244 self.module.fail_json(msg="Invalid device found [%s], please specify device from ['%s']" % (device_order,
245 "', '".join(valid_device_strings)))
246 if device_order == 'cdrom':
247 first_cdrom = [device for device in self.vm.config.hardware.device if isinstance(device, vim.vm.device.VirtualCdrom)]
248 if first_cdrom:
249 boot_order_list.append(vim.vm.BootOptions.BootableCdromDevice())
250 elif device_order == 'disk':
251 if not self.params.get('boot_hdd_name'):
252 first_hdd = [device for device in self.vm.config.hardware.device if isinstance(device, vim.vm.device.VirtualDisk)]
253 else:
254 first_hdd = [device for device in self.vm.config.hardware.device if isinstance(device, vim.vm.device.VirtualDisk)
255 and device.deviceInfo.label == self.params.get('boot_hdd_name')]
256 if not first_hdd:
257 self.module.fail_json(msg="Not found virtual disk with disk label '%s'" % (self.params.get('boot_hdd_name')))
258 if first_hdd:
259 boot_order_list.append(vim.vm.BootOptions.BootableDiskDevice(deviceKey=first_hdd[0].key))
260 elif device_order == 'ethernet':
261 first_ether = [device for device in self.vm.config.hardware.device if isinstance(device, vim.vm.device.VirtualEthernetCard)]
262 if first_ether:
263 boot_order_list.append(vim.vm.BootOptions.BootableEthernetDevice(deviceKey=first_ether[0].key))
264 elif device_order == 'floppy':
265 first_floppy = [device for device in self.vm.config.hardware.device if isinstance(device, vim.vm.device.VirtualFloppy)]
266 if first_floppy:
267 boot_order_list.append(vim.vm.BootOptions.BootableFloppyDevice())
268
269 # Get previous boot disk name when boot_hdd_name is set
270 if self.params.get('boot_hdd_name'):
271 for i in range(0, len(self.vm.config.bootOptions.bootOrder)):
272 if isinstance(self.vm.config.bootOptions.bootOrder[i], vim.vm.BootOptions.BootableDiskDevice):
273 if self.vm.config.bootOptions.bootOrder[i].deviceKey:
274 for dev in self.vm.config.hardware.device:
275 if isinstance(dev, vim.vm.device.VirtualDisk) and \
276 dev.key == self.vm.config.bootOptions.bootOrder[i].deviceKey:
277 previous_boot_disk = dev.deviceInfo.label
278
279 if len(boot_order_list) != len(self.vm.config.bootOptions.bootOrder):
280 kwargs.update({'bootOrder': boot_order_list})
281 change_needed = True
282 else:
283 for i in range(0, len(boot_order_list)):
284 boot_device_type = type(boot_order_list[i])
285 vm_boot_device_type = type(self.vm.config.bootOptions.bootOrder[i])
286 if boot_device_type != vm_boot_device_type:
287 kwargs.update({'bootOrder': boot_order_list})
288 change_needed = True
289 else:
290 if vm_boot_device_type is vim.vm.BootOptions.BootableDiskDevice and \
291 boot_order_list[i].deviceKey != self.vm.config.bootOptions.bootOrder[i].deviceKey:
292 kwargs.update({'bootOrder': boot_order_list})
293 change_needed = True
294
295 if self.params.get('boot_delay') is not None and \
296 self.vm.config.bootOptions.bootDelay != self.params.get('boot_delay'):
297 kwargs.update({'bootDelay': self.params.get('boot_delay')})
298 change_needed = True
299
300 if self.params.get('enter_bios_setup') is not None and \
301 self.vm.config.bootOptions.enterBIOSSetup != self.params.get('enter_bios_setup'):
302 kwargs.update({'enterBIOSSetup': self.params.get('enter_bios_setup')})
303 change_needed = True
304
305 if self.params.get('boot_retry_enabled') is not None and \
306 self.vm.config.bootOptions.bootRetryEnabled != self.params.get('boot_retry_enabled'):
307 kwargs.update({'bootRetryEnabled': self.params.get('boot_retry_enabled')})
308 change_needed = True
309
310 if self.params.get('boot_retry_delay') is not None and \
311 self.vm.config.bootOptions.bootRetryDelay != self.params.get('boot_retry_delay'):
312 if not self.vm.config.bootOptions.bootRetryEnabled:
313 kwargs.update({'bootRetryEnabled': True})
314 kwargs.update({'bootRetryDelay': self.params.get('boot_retry_delay')})
315 change_needed = True
316
317 boot_firmware_required = False
318 if self.params.get('boot_firmware') is not None and self.vm.config.firmware != self.params.get('boot_firmware'):
319 change_needed = True
320 boot_firmware_required = True
321
322 if self.params.get('secure_boot_enabled') is not None:
323 if self.params.get('secure_boot_enabled') and self.params.get('boot_firmware') == "bios":
324 self.module.fail_json(msg="Secure boot cannot be enabled when boot_firmware = bios")
325 elif self.params.get('secure_boot_enabled') and \
326 self.params.get('boot_firmware') != 'efi' and \
327 self.vm.config.firmware == 'bios':
328 self.module.fail_json(msg="Secure boot cannot be enabled since the VM's boot firmware is currently set to bios")
329 elif self.vm.config.bootOptions.efiSecureBootEnabled != self.params.get('secure_boot_enabled'):
330 kwargs.update({'efiSecureBootEnabled': self.params.get('secure_boot_enabled')})
331 change_needed = True
332
333 changed = False
334 results = dict(
335 previous_boot_order=self.humanize_boot_order(self.vm.config.bootOptions.bootOrder),
336 previous_boot_delay=self.vm.config.bootOptions.bootDelay,
337 previous_enter_bios_setup=self.vm.config.bootOptions.enterBIOSSetup,
338 previous_boot_retry_enabled=self.vm.config.bootOptions.bootRetryEnabled,
339 previous_boot_retry_delay=self.vm.config.bootOptions.bootRetryDelay,
340 previous_boot_firmware=self.vm.config.firmware,
341 previous_secure_boot_enabled=self.vm.config.bootOptions.efiSecureBootEnabled,
342 current_boot_order=[]
343 )
344 if previous_boot_disk:
345 results.update({'previous_boot_disk': previous_boot_disk})
346
347 if change_needed:
348 vm_conf = vim.vm.ConfigSpec()
349 vm_conf.bootOptions = vim.vm.BootOptions(**kwargs)
350 if boot_firmware_required:
351 vm_conf.firmware = self.params.get('boot_firmware')
352 task = self.vm.ReconfigVM_Task(vm_conf)
353
354 try:
355 changed, result = wait_for_task(task)
356 except TaskError as e:
357 self.module.fail_json(msg="Failed to perform reconfigure virtual"
358 " machine %s for boot order due to: %s" % (self.name or self.uuid,
359 to_native(e)))
360
361 results.update(
362 {
363 'current_boot_order': self.humanize_boot_order(self.vm.config.bootOptions.bootOrder),
364 'current_boot_delay': self.vm.config.bootOptions.bootDelay,
365 'current_enter_bios_setup': self.vm.config.bootOptions.enterBIOSSetup,
366 'current_boot_retry_enabled': self.vm.config.bootOptions.bootRetryEnabled,
367 'current_boot_retry_delay': self.vm.config.bootOptions.bootRetryDelay,
368 'current_boot_firmware': self.vm.config.firmware,
369 'current_secure_boot_enabled': self.vm.config.bootOptions.efiSecureBootEnabled
370 }
371 )
372 if self.params.get('boot_hdd_name'):
373 results.update({'current_boot_disk': self.params.get('boot_hdd_name')})
374
375 self.module.exit_json(changed=changed, vm_boot_status=results)
376
377
378 def main():
379 argument_spec = base_argument_spec()
380 argument_spec.update(
381 name=dict(type='str'),
382 uuid=dict(type='str'),
383 moid=dict(type='str'),
384 use_instance_uuid=dict(type='bool', default=False),
385 name_match=dict(
386 choices=['first', 'last'],
387 default='first'
388 ),
389 boot_order=dict(
390 type='list',
391 default=[],
392 elements='str'
393 ),
394 boot_hdd_name=dict(type='str'),
395 boot_delay=dict(type='int'),
396 enter_bios_setup=dict(type='bool'),
397 boot_retry_enabled=dict(type='bool'),
398 boot_retry_delay=dict(type='int'),
399 secure_boot_enabled=dict(type='bool'),
400 boot_firmware=dict(
401 type='str',
402 choices=['efi', 'bios']
403 )
404 )
405
406 module = AnsibleModule(
407 argument_spec=argument_spec,
408 required_one_of=[
409 ['name', 'uuid', 'moid']
410 ],
411 mutually_exclusive=[
412 ['name', 'uuid', 'moid']
413 ],
414 )
415
416 pyv = VmBootManager(module)
417 pyv.ensure()
418
419
420 if __name__ == '__main__':
421 main()