Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2021, Tyler Gates <[email protected]>
5 #
6 # Special thanks to:
7 # * Vadim Aleksandrov <[email protected]>: Original author of python script
8 # `set_vm_storage_policy.py` from
9 # which most methods were derived.
10 # * William Lam (https://github.com/lamw): Author of script
11 # `list_vm_storage_policy.py` whose
12 # ideas were inspiration for
13 # Vadim's script.
14 # * Abhijeet Kasurde <[email protected]>: Ansible modulization loosely
15 # modeled after
16 # `vmware_guest_disk.py'.
17 #
18 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
19 # SPDX-License-Identifier: GPL-3.0-or-later
20
21 from __future__ import (absolute_import, division, print_function)
22 __metaclass__ = type
23
24
25 DOCUMENTATION = r'''
26 ---
27 module: vmware_guest_storage_policy
28 short_description: Set VM Home and disk(s) storage policy profiles.
29 description:
30 - This module can be used to enforce storage policy profiles per disk and/or VM Home on a virtual machine.
31 author:
32 - Tyler Gates (@tgates81)
33 options:
34 name:
35 description:
36 - Name of the virtual machine.
37 - One of O(name), O(uuid), or O(moid) are required to define the virtual machine.
38 type: str
39 required: false
40 uuid:
41 description:
42 - UUID of the virtual machine.
43 - One of O(name), O(uuid), or O(moid) are required to define the virtual machine.
44 type: str
45 required: false
46 moid:
47 description:
48 - Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance.
49 - One of O(name), O(uuid), or O(moid) are required to define the virtual machine.
50 type: str
51 required: false
52 folder:
53 description:
54 - Destination folder, absolute or relative path to find an existing guest.
55 - This is a required parameter if multiple VMs are found with same name.
56 - The folder should include the datacenter. ESX's datacenter is ha-datacenter.
57 - 'Examples:'
58 - ' folder: /ha-datacenter/vm'
59 - ' folder: ha-datacenter/vm'
60 - ' folder: /datacenter1/vm'
61 - ' folder: datacenter1/vm'
62 - ' folder: /datacenter1/vm/folder1'
63 - ' folder: datacenter1/vm/folder1'
64 - ' folder: /folder1/datacenter1/vm'
65 - ' folder: folder1/datacenter1/vm'
66 - ' folder: /folder1/datacenter1/vm/folder2'
67 type: str
68 required: false
69 vm_home:
70 description:
71 - A storage profile policy to set on VM Home.
72 - At least one of O(disk) or O(vm_home) are required parameters.
73 required: false
74 type: str
75 disk:
76 description:
77 - A list of disks with storage profile policies to enforce.
78 - At least one of O(disk) and O(vm_home) are required parameters.
79 required: false
80 type: list
81 elements: dict
82 suboptions:
83 unit_number:
84 description:
85 - Disk Unit Number.
86 - Valid values range from 0 to 15.
87 type: int
88 required: true
89 controller_number:
90 description:
91 - SCSI controller number.
92 - Valid values range from 0 to 3.
93 type: int
94 default: 0
95 policy:
96 description:
97 - Name of the storage profile policy to enforce for the disk.
98 type: str
99 required: true
100 extends_documentation_fragment:
101 - vmware.vmware.base_options
102 '''
103
104 EXAMPLES = r'''
105 - name: Enforce storepol1 policy for disk 0 and 1 on SCSI controller 0 using UUID
106 community.vmware.vmware_guest_storage_policy:
107 hostname: "{{ vcenter_hostname }}"
108 username: "{{ vcenter_username }}"
109 password: "{{ vcenter_password }}"
110 validate_certs: false
111 uuid: cefd316c-fc19-45f3-a539-2cd03427a78d
112 disk:
113 - unit_number: 0
114 controller_number: 0
115 policy: storepol1
116 - unit_number: 1
117 controller_number: 0
118 policy: storepol1
119 delegate_to: localhost
120 register: policy_status
121
122 - name: Enforce storepol1 policy for VM Home using name
123 community.vmware.vmware_guest_storage_policy:
124 hostname: "{{ vcenter_hostname }}"
125 username: "{{ vcenter_username }}"
126 password: "{{ vcenter_password }}"
127 validate_certs: false
128 name: hostname1
129 vm_home: storepol1
130 delegate_to: localhost
131 '''
132
133 RETURN = r'''
134 msg:
135 description: Informational message on the job result.
136 type: str
137 returned: always
138 sample: "Policies successfully set."
139 changed_policies:
140 description: Dictionary containing the changed policies of disk (list of dictionaries) and vm_home.
141 type: dict
142 returned: always
143 sample: {
144 "disk": [
145 {
146 "policy": "storepol1",
147 "unit_number": 0
148 }
149 ],
150 "vm_home": "storepol1"
151 }
152 '''
153
154 PYVMOMI_IMP_ERR = None
155 try:
156 from pyVmomi import pbm, vim
157 except ImportError:
158 pass
159 from ansible.module_utils.basic import AnsibleModule
160 from ansible.module_utils.common.text.converters import to_native
161 from ansible_collections.community.vmware.plugins.module_utils.vmware import wait_for_task
162 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
163 from ansible_collections.community.vmware.plugins.module_utils.vmware_spbm import SPBM
164
165
166 class SPBM_helper(SPBM):
167 def __init__(self, module):
168 super().__init__(module)
169
170 def SearchStorageProfileByName(self, profileManager, name):
171 """
172 Search VMware storage policy profile by name.
173
174 :param profileManager: A VMware Storage Policy Service manager object.
175 :type profileManager: pbm.profile.ProfileManager
176 :param name: A VMware Storage Policy profile name.
177 :type name: str
178 :returns: A VMware Storage Policy profile object.
179 :rtype: pbm.profile.Profile
180 """
181
182 profileIds = profileManager.PbmQueryProfile(
183 resourceType=pbm.profile.ResourceType(resourceType="STORAGE"),
184 profileCategory="REQUIREMENT"
185 )
186 if len(profileIds) > 0:
187 storageProfiles = profileManager.PbmRetrieveContent(
188 profileIds=profileIds)
189 else:
190 return None
191
192 for storageProfile in storageProfiles:
193 if storageProfile.name == name:
194 return storageProfile
195
196 def CheckAssociatedStorageProfile(self, profileManager, ref, name):
197 """
198 Check the associated storage policy profile.
199
200 :param profileManager: A VMware Storage Policy Service manager object.
201 :type profileManager: pbm.profile.ProfileManager
202 :param ref: A server object ref to a virtual machine, virtual disk,
203 or datastore.
204 :type ref: pbm.ServerObjectRef
205 :param name: A VMware storage policy profile name.
206 :type name: str
207 :returns: True if storage policy profile by name is associated to ref.
208 :rtype: bool
209 """
210
211 profileIds = profileManager.PbmQueryAssociatedProfile(ref)
212 if len(profileIds) > 0:
213 profiles = profileManager.PbmRetrieveContent(profileIds=profileIds)
214 for profile in profiles:
215 if profile.name == name:
216 return True
217 return False
218
219 def SetVMHomeStorageProfile(self, vm, profile):
220 """
221 Set VM Home storage policy profile.
222
223 :param vm: A virtual machine object.
224 :type vm: VirtualMachine
225 :param profile: A VMware Storage Policy profile.
226 :type profile: pbm.profile.Profile
227 :returns: VMware task object.
228 :rtype: Task
229 """
230
231 spec = vim.vm.ConfigSpec()
232 profileSpec = vim.vm.DefinedProfileSpec()
233 profileSpec.profileId = profile.profileId.uniqueId
234 spec.vmProfile = [profileSpec]
235 return vm.ReconfigVM_Task(spec)
236
237 def GetVirtualDiskObj(self, vm, unit_number, controller_number):
238 """
239 Get a virtual disk object.
240
241 :param vm: A virtual machine object.
242 :type vm: VirtualMachine
243 :param unit_number: virtual machine's disk unit number.
244 :type unit_number: int
245 :param controller_number: virtual machine's controller number.
246 :type controller_number: int
247 :returns: VirtualDisk object if exists, else None.
248 :rtype: VirtualDisk, None
249 """
250 controllerKey = None
251 for device in vm.config.hardware.device:
252 if isinstance(device, vim.vm.device.VirtualSCSIController):
253 if device.busNumber == controller_number:
254 controllerKey = device.key
255 break
256
257 if controllerKey is not None: # if controller was found check disk
258 for device in vm.config.hardware.device:
259 if not isinstance(device, vim.vm.device.VirtualDisk):
260 continue
261 if int(device.unitNumber) == int(unit_number) and \
262 int(device.controllerKey) == controllerKey:
263 return device
264
265 return None
266
267 def SetVMDiskStorageProfile(self, vm, unit_number, controller_number, profile):
268 """
269 Set VM's disk storage policy profile.
270
271 :param vm: A virtual machine object
272 :type vm: VirtualMachine
273 :param unit_number: virtual machine's disk unit number.
274 :type unit_number: int
275 :param controller_number: virtual machine's controller number.
276 :type controller_number: int
277 :param profile: A VMware Storage Policy profile
278 :type profile: pbm.profile.Profile
279 :returns: VMware task object.
280 :rtype: Task
281 """
282
283 spec = vim.vm.ConfigSpec()
284 profileSpec = vim.vm.DefinedProfileSpec()
285 profileSpec.profileId = profile.profileId.uniqueId
286
287 deviceSpec = vim.vm.device.VirtualDeviceSpec()
288 deviceSpec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
289 disk_obj = self.GetVirtualDiskObj(vm, unit_number, controller_number)
290 deviceSpec.device = disk_obj
291 deviceSpec.profile = [profileSpec]
292 spec.deviceChange = [deviceSpec]
293 return vm.ReconfigVM_Task(spec)
294
295 def ensure_storage_policies(self, vm_obj):
296 """
297 Ensure VM storage profile policies.
298
299 :param vm_obj: VMware VM object.
300 :type vm_obj: VirtualMachine
301 :exits: self.module.exit_json on success, else self.module.fail_json.
302 """
303
304 disks = self.module.params.get('disk')
305 vm_home = self.module.params.get('vm_home')
306 success_msg = "Policies successfully set."
307 result = dict(
308 changed=False,
309 msg="",
310 changed_policies=dict(disk=[],
311 vm_home="",
312 ),
313 )
314
315 # Connect into vcenter and get the profile manager for the VM.
316 self.get_spbm_connection()
317 pm = self.spbm_content.profileManager
318
319 #
320 # VM HOME
321 #
322 if vm_home:
323 policy = vm_home
324 pmObjectType = pbm.ServerObjectRef.ObjectType("virtualMachine")
325 pmRef = pbm.ServerObjectRef(key=vm_obj._moId,
326 objectType=pmObjectType)
327 pol_obj = self.SearchStorageProfileByName(pm, policy)
328
329 if not pol_obj:
330 result['msg'] = "Unable to find storage policy `%s' for vm_home" % policy
331 self.module.fail_json(**result)
332
333 if not self.CheckAssociatedStorageProfile(pm, pmRef, policy):
334 # Existing policy is different than requested. Set, wait for
335 # task success, and exit.
336 if not self.module.check_mode:
337 task = self.SetVMHomeStorageProfile(vm_obj, pol_obj)
338 wait_for_task(task) # will raise an Exception on failure
339 result['changed'] = True
340 result['changed_policies']['vm_home'] = policy
341
342 #
343 # DISKS
344 #
345 if disks is None:
346 disks = list()
347 # Check the requested disks[] information is sane or fail by looking up
348 # and storing the object(s) in a new dict.
349 disks_objs = dict() # {unit_number: {disk: <obj>, policy: <obj>}}
350 for disk in disks:
351 policy = str(disk['policy'])
352 unit_number = int(disk['unit_number'])
353 controller_number = int(disk['controller_number'])
354 disk_obj = self.GetVirtualDiskObj(vm_obj, unit_number, controller_number)
355 pol_obj = self.SearchStorageProfileByName(pm, policy)
356 if not pol_obj:
357 result['msg'] = "Unable to find storage policy `%s' for disk %s." % (policy, disk)
358 self.module.fail_json(**result)
359 if not disk_obj:
360 errmsg = "Unable to find disk for controller_number '%s' unit_number '%s'. 7 is reserved for SCSI adapters."
361 result['msg'] = errmsg % (controller_number, unit_number)
362 self.module.fail_json(**result)
363 disks_objs[unit_number] = dict(disk=disk_obj, policy=pol_obj)
364
365 # All requested profiles are valid. Iterate through each disk and set
366 # accordingly.
367 for disk in disks:
368 policy = str(disk['policy'])
369 unit_number = int(disk['unit_number'])
370 controller_number = int(disk['controller_number'])
371 disk_obj = disks_objs[unit_number]['disk']
372 pol_obj = disks_objs[unit_number]['policy']
373 pmObjectType = pbm.ServerObjectRef.ObjectType("virtualDiskId")
374 pmRef = pbm.ServerObjectRef(key="%s:%s"
375 % (vm_obj._moId, disk_obj.key),
376 objectType=pmObjectType)
377
378 if not self.CheckAssociatedStorageProfile(pm, pmRef, policy):
379 # Existing policy is different than requested. Set, wait for
380 # task success, and exit.
381 if not self.module.check_mode:
382 task = self.SetVMDiskStorageProfile(vm_obj, unit_number,
383 controller_number,
384 pol_obj)
385 wait_for_task(task)
386 result['changed'] = True
387 result['changed_policies']['disk'].append(disk)
388
389 #
390 # END
391 #
392 # Check our results and exit.
393 if result['changed']:
394 result['msg'] = success_msg
395 self.module.exit_json(**result)
396
397
398 def run_module():
399 argument_spec = base_argument_spec()
400 argument_spec.update(
401 name=dict(type='str'),
402 uuid=dict(type='str'),
403 moid=dict(type='str'),
404 folder=dict(type='str'),
405 disk=dict(type='list',
406 required=False,
407 elements='dict',
408 options=dict(
409 unit_number=dict(type='int', required=True),
410 controller_number=dict(type='int', default=0),
411 policy=dict(type='str', required=True)
412 )),
413 vm_home=dict(type='str'),
414 )
415 module = AnsibleModule(
416 supports_check_mode=True,
417 argument_spec=argument_spec,
418 required_one_of=[
419 ['name', 'uuid', 'moid'],
420 ['disk', 'vm_home'],
421 ],
422 )
423
424 if module.params['folder']:
425 # FindByInventoryPath() does not require an absolute path
426 # so we should leave the input folder path unmodified
427 module.params['folder'] = module.params['folder'].rstrip('/')
428
429 spbm_h = SPBM_helper(module)
430 # Check if the VM exists before continuing
431 vm = spbm_h.get_vm()
432 if not vm:
433 module.fail_json(msg="Unable to find virtual machine `%s'" %
434 (module.params.get('name')
435 or module.params.get('uuid')
436 or module.params.get('moid')))
437
438 try:
439 spbm_h.ensure_storage_policies(vm)
440 except Exception as e:
441 module.fail_json(msg="Failed to set storage policies for virtual"
442 "machine '%s' with exception: %s"
443 % (vm.name, to_native(e)))
444
445
446 def main():
447 run_module()
448
449
450 if __name__ == "__main__":
451 main()