Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Karsten Kaj Jakobsen <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import absolute_import, division, print_function
9
10 __metaclass__ = type
11
12
13 DOCUMENTATION = r'''
14 ---
15 author:
16 - "Karsten Kaj Jakobsen (@karstenjakobsen)"
17 description:
18 - "This module can be used to create VM/Host groups in a given cluster. Creates a vm group if O(vms) is set. Creates a host group if O(hosts) is set."
19 extends_documentation_fragment:
20 - vmware.vmware.base_options
21
22 module: vmware_drs_group
23 options:
24 cluster_name:
25 description:
26 - "Cluster to create vm/host group."
27 required: true
28 type: str
29 datacenter:
30 aliases:
31 - datacenter_name
32 description:
33 - "Datacenter to search for given cluster. If not set, we use first cluster we encounter with O(cluster_name)."
34 required: false
35 type: str
36 group_name:
37 description:
38 - "The name of the group to create or remove."
39 required: true
40 type: str
41 hosts:
42 description:
43 - "List of hosts to create in group."
44 - "Required if O(vms) is not set."
45 - "O(hosts) and O(vms) are mutually exclusive parameters."
46 required: false
47 type: list
48 elements: str
49 state:
50 choices:
51 - present
52 - absent
53 default: present
54 description:
55 - "If set to V(present) and the group doesn't exists then the group will be created."
56 - "If set to V(absent) and the group exists then the group will be deleted."
57 type: str
58 vms:
59 description:
60 - "List of vms to create in group."
61 - "Required if O(hosts) is not set."
62 - "O(hosts) and O(vms) are mutually exclusive parameters."
63 required: false
64 type: list
65 elements: str
66 short_description: "Creates vm/host group in a given cluster."
67 '''
68
69 EXAMPLES = r'''
70 ---
71 - name: "Create DRS VM group"
72 delegate_to: localhost
73 community.vmware.vmware_drs_group:
74 hostname: "{{ vcenter_hostname }}"
75 password: "{{ vcenter_password }}"
76 username: "{{ vcenter_username }}"
77 cluster_name: DC0_C0
78 datacenter_name: DC0
79 group_name: TEST_VM_01
80 vms:
81 - DC0_C0_RP0_VM0
82 - DC0_C0_RP0_VM1
83 state: present
84
85 - name: "Create DRS Host group"
86 delegate_to: localhost
87 community.vmware.vmware_drs_group:
88 hostname: "{{ vcenter_hostname }}"
89 password: "{{ vcenter_password }}"
90 username: "{{ vcenter_username }}"
91 cluster_name: DC0_C0
92 datacenter_name: DC0
93 group_name: TEST_HOST_01
94 hosts:
95 - DC0_C0_H0
96 - DC0_C0_H1
97 - DC0_C0_H2
98 state: present
99
100 - name: "Delete DRS Host group"
101 delegate_to: localhost
102 community.vmware.vmware_drs_group:
103 hostname: "{{ vcenter_hostname }}"
104 password: "{{ vcenter_password }}"
105 username: "{{ vcenter_username }}"
106 cluster_name: DC0_C0
107 datacenter_name: DC0
108 group_name: TEST_HOST_01
109 state: absent
110 '''
111
112 RETURN = r'''
113 drs_group_facts:
114 description: Metadata about DRS group created
115 returned: always
116 type: dict
117 sample:
118 "drs_group_facts": {
119 "changed": true,
120 "failed": false,
121 "msg": "Created host group TEST_HOST_01 successfully",
122 "result": {
123 "DC0_C0": [
124 {
125 "group_name": "TEST_HOST_01",
126 "hosts": [
127 "DC0_C0_H0",
128 "DC0_C0_H1",
129 "DC0_C0_H2"
130 ],
131 "type": "host"
132 }
133 ]
134 }
135 }
136 '''
137
138 try:
139 from pyVmomi import vim
140 except ImportError:
141 pass
142
143 from ansible.module_utils.basic import AnsibleModule
144 from ansible_collections.community.vmware.plugins.module_utils.vmware import (
145 PyVmomi,
146 wait_for_task,
147 find_cluster_by_name,
148 find_vm_by_id,
149 find_datacenter_by_name)
150 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
151
152
153 class VmwareDrsGroupManager(PyVmomi):
154 """
155 Class to manage DRS groups
156 """
157
158 def __init__(self, module, cluster_name, group_name, state,
159 datacenter_name=None, vm_list=None, host_list=None):
160 """
161 Init
162 """
163
164 super(VmwareDrsGroupManager, self).__init__(module)
165
166 self.__datacenter_name = datacenter_name
167 self.__datacenter_obj = None
168 self.__cluster_name = cluster_name
169 self.__cluster_obj = None
170 self.__group_name = group_name
171 self.__group_obj = None
172 self.__operation = None
173 self.__vm_list = vm_list
174 self.__vm_obj_list = []
175 self.__host_list = host_list
176 self.__host_obj_list = []
177 self.__msg = 'Nothing to see here...'
178 self.__result = dict()
179 self.__changed = False
180 self.__state = state
181
182 if datacenter_name is not None:
183
184 self.__datacenter_obj = find_datacenter_by_name(self.content, self.__datacenter_name)
185
186 if self.__datacenter_obj is None:
187 raise Exception("Datacenter '%s' not found" % self.__datacenter_name)
188
189 self.__cluster_obj = find_cluster_by_name(content=self.content,
190 cluster_name=self.__cluster_name,
191 datacenter=self.__datacenter_obj)
192
193 # Throw error if cluster does not exist
194 if self.__cluster_obj is None:
195 if not module.check_mode:
196 raise Exception("Cluster '%s' not found" % self.__cluster_name)
197 else:
198 # get group
199 self.__group_obj = self.__get_group_by_name()
200 # Set result here. If nothing is to be updated, result is already set
201 self.__set_result(self.__group_obj)
202
203 # Do not populate lists if we are deleting group
204 if self.__state == 'present':
205
206 if self.__group_obj:
207 self.__operation = 'edit'
208 else:
209 self.__operation = 'add'
210
211 if self.__vm_list is not None:
212 self.__set_vm_obj_list(vm_list=self.__vm_list)
213
214 if self.__host_list is not None:
215 self.__set_host_obj_list(host_list=self.__host_list)
216 else:
217 self.__operation = 'remove'
218
219 def get_msg(self):
220 """
221 Returns message for Ansible result
222 Args: none
223
224 Returns: string
225 """
226 return self.__msg
227
228 def get_result(self):
229 """
230 Returns result for Ansible
231 Args: none
232
233 Returns: dict
234 """
235 return self.__result
236
237 def __set_result(self, group_obj):
238 """
239 Creates result for successful run
240 Args:
241 group_obj: group object
242
243 Returns: None
244
245 """
246 self.__result = dict()
247
248 if (self.__cluster_obj is not None) and (group_obj is not None):
249 self.__result[self.__cluster_obj.name] = []
250 self.__result[self.__cluster_obj.name].append(self.__normalize_group_data(group_obj))
251
252 def get_changed(self):
253 """
254 Returns if anything changed
255 Args: none
256
257 Returns: boolean
258 """
259 return self.__changed
260
261 def __set_vm_obj_list(self, vm_list=None, cluster_obj=None):
262 """
263 Function populate vm object list from list of vms
264 Args:
265 vm_list: List of vm names
266
267 Returns: None
268
269 """
270
271 if vm_list is None:
272 vm_list = self.__vm_list
273
274 if cluster_obj is None:
275 cluster_obj = self.__cluster_obj
276
277 if vm_list is not None:
278 for vm in vm_list:
279 if not self.module.check_mode:
280 # Get host data
281 vm_obj = find_vm_by_id(content=self.content, vm_id=vm,
282 vm_id_type='vm_name', cluster=cluster_obj)
283 if vm_obj is None:
284 raise Exception("VM %s does not exist in cluster %s" % (vm,
285 self.__cluster_name))
286 self.__vm_obj_list.append(vm_obj)
287
288 def __set_host_obj_list(self, host_list=None):
289 """
290 Function populate host object list from list of hostnames
291 Args:
292 host_list: List of host names
293
294 Returns: None
295
296 """
297
298 if host_list is None:
299 host_list = self.__host_list
300
301 if host_list is not None:
302 for host in host_list:
303 if not self.module.check_mode:
304 # Get host data
305 host_obj = self.find_hostsystem_by_name(host)
306 if host_obj is None:
307 raise Exception("ESXi host %s does not exist in cluster %s" % (host, self.__cluster_name))
308 self.__host_obj_list.append(host_obj)
309
310 def __get_group_by_name(self, group_name=None, cluster_obj=None):
311 """
312 Function to get group by name
313 Args:
314 group_name: Name of group
315 cluster_obj: vim Cluster object
316
317 Returns: Group Object if found or None
318
319 """
320
321 if group_name is None:
322 group_name = self.__group_name
323
324 if cluster_obj is None:
325 cluster_obj = self.__cluster_obj
326
327 # Allow for group check even if dry run
328 if self.module.check_mode and cluster_obj is None:
329 return None
330
331 for group in cluster_obj.configurationEx.group:
332 if group.name == group_name:
333 return group
334
335 # No group found
336 return None
337
338 def __populate_vm_host_list(self, group_name=None, cluster_obj=None, host_group=False):
339 """
340 Return all VM/Host names using given group name
341 Args:
342 group_name: group name
343 cluster_obj: Cluster managed object
344 host_group: True if we want only host name from group
345
346 Returns: List of VM/Host names belonging to given group object
347
348 """
349 obj_name_list = []
350
351 if group_name is None:
352 group_name = self.__group_name
353
354 if cluster_obj is None:
355 cluster_obj = self.__cluster_obj
356
357 if not all([group_name, cluster_obj]):
358 return obj_name_list
359
360 group = self.__group_obj
361
362 if not host_group and isinstance(group, vim.cluster.VmGroup):
363 obj_name_list = [vm.name for vm in group.vm]
364
365 elif host_group and isinstance(group, vim.cluster.HostGroup):
366 obj_name_list = [host.name for host in group.host]
367
368 return obj_name_list
369
370 def __check_if_vms_hosts_changed(self, group_name=None, cluster_obj=None, host_group=False):
371 """
372 Function to check if VMs/Hosts changed
373 Args:
374 group_name: Name of group
375 cluster_obj: vim Cluster object
376 host_group: True if we want to check hosts, else check vms
377
378 Returns: Bool
379
380 """
381
382 if group_name is None:
383 group_name = self.__group_name
384
385 if cluster_obj is None:
386 cluster_obj = self.__cluster_obj
387
388 list_a = self.__host_list if host_group else self.__vm_list
389 list_b = self.__populate_vm_host_list(host_group=host_group)
390
391 # By casting lists as a set, you remove duplicates and order doesn't count. Comparing sets is also much faster and more efficient than comparing lists.
392 if set(list_a) == set(list_b):
393 return False
394 return True
395
396 def __create_host_group(self):
397
398 # Check if anything has changed when editing
399 if self.__operation == 'add' or (self.__operation == 'edit' and self.__check_if_vms_hosts_changed(host_group=True)):
400
401 group = vim.cluster.HostGroup()
402 group.name = self.__group_name
403 group.host = self.__host_obj_list
404
405 group_spec = vim.cluster.GroupSpec(info=group, operation=self.__operation)
406 config_spec = vim.cluster.ConfigSpecEx(groupSpec=[group_spec])
407
408 changed = True
409 if not self.module.check_mode:
410 task = self.__cluster_obj.ReconfigureEx(config_spec, modify=True)
411 changed, result = wait_for_task(task)
412
413 # Set new result since something changed
414 self.__set_result(group)
415 self.__changed = changed
416
417 if self.__operation == 'edit':
418 self.__msg = "Updated host group %s successfully" % (self.__group_name)
419 else:
420 self.__msg = "Created host group %s successfully" % (self.__group_name)
421
422 def __create_vm_group(self):
423
424 # Check if anything has changed when editing
425 if self.__operation == 'add' or (self.__operation == 'edit' and self.__check_if_vms_hosts_changed()):
426
427 group = vim.cluster.VmGroup()
428 group.name = self.__group_name
429 group.vm = self.__vm_obj_list
430
431 group_spec = vim.cluster.GroupSpec(info=group, operation=self.__operation)
432 config_spec = vim.cluster.ConfigSpecEx(groupSpec=[group_spec])
433
434 # Check if dry run
435 changed = True
436 if not self.module.check_mode:
437 task = self.__cluster_obj.ReconfigureEx(config_spec, modify=True)
438 changed, result = wait_for_task(task)
439
440 self.__set_result(group)
441 self.__changed = changed
442
443 if self.__operation == 'edit':
444 self.__msg = "Updated vm group %s successfully" % (self.__group_name)
445 else:
446 self.__msg = "Created vm group %s successfully" % (self.__group_name)
447
448 def __normalize_group_data(self, group_obj):
449 """
450 Return human readable group spec
451 Args:
452 group_obj: Group object
453
454 Returns: DRS group object fact
455
456 """
457 if not all([group_obj]):
458 return {}
459
460 # Check if group is a host group
461 if hasattr(group_obj, 'host'):
462 return dict(
463 group_name=group_obj.name,
464 hosts=self.__host_list,
465 type="host"
466 )
467 return dict(
468 group_name=group_obj.name,
469 vms=self.__vm_list,
470 type="vm"
471 )
472
473 def create_drs_group(self):
474 """
475 Function to create a DRS host/vm group
476 """
477
478 if self.__vm_list is None:
479 self.__create_host_group()
480 elif self.__host_list is None:
481 self.__create_vm_group()
482 else:
483 raise Exception('Failed, no hosts or vms defined')
484
485 def delete_drs_group(self):
486 """
487 Function to delete a DRS host/vm group
488 """
489
490 if self.__group_obj is not None:
491
492 self.__changed = True
493
494 # Check if dry run
495 if not self.module.check_mode:
496
497 group_spec = vim.cluster.GroupSpec(removeKey=self.__group_name, operation=self.__operation)
498 config_spec = vim.cluster.ConfigSpecEx(groupSpec=[group_spec])
499
500 task = self.__cluster_obj.ReconfigureEx(config_spec, modify=True)
501 wait_for_task(task)
502
503 # Do not throw error if group does not exist. Simply set changed = False
504 if self.__changed:
505 self.__msg = "Deleted group `%s` successfully" % (self.__group_name)
506 else:
507 self.__msg = "DRS group `%s` does not exists or already deleted" % (self.__group_name)
508
509
510 def main():
511 """
512 Main function
513 """
514
515 argument_spec = base_argument_spec()
516
517 argument_spec.update(
518 state=dict(type='str', default='present', choices=['present', 'absent']),
519 datacenter=dict(type='str', required=False, aliases=['datacenter_name']),
520 cluster_name=dict(type='str', required=True),
521 group_name=dict(type='str', required=True),
522 vms=dict(type='list', elements='str'),
523 hosts=dict(type='list', elements='str'),
524 )
525
526 required_if = [
527 ['state', 'absent', ['group_name']]
528 ]
529
530 module = AnsibleModule(
531 argument_spec=argument_spec,
532 required_if=required_if,
533 supports_check_mode=True,
534 mutually_exclusive=[['vms', 'hosts']],
535 required_one_of=[['vms', 'hosts']]
536 )
537
538 try:
539 # Create instance of VmwareDrsGroupManager
540 vmware_drs_group = VmwareDrsGroupManager(module=module,
541 datacenter_name=module.params.get('datacenter', None),
542 cluster_name=module.params['cluster_name'],
543 group_name=module.params['group_name'],
544 vm_list=module.params['vms'],
545 host_list=module.params['hosts'],
546 state=module.params['state'])
547
548 if module.params['state'] == 'present':
549 # Add DRS group
550 vmware_drs_group.create_drs_group()
551 elif module.params['state'] == 'absent':
552 # Delete DRS group
553 vmware_drs_group.delete_drs_group()
554
555 # Set results
556 results = dict(msg=vmware_drs_group.get_msg(),
557 failed=False,
558 changed=vmware_drs_group.get_changed(),
559 result=vmware_drs_group.get_result())
560
561 except Exception as error:
562 results = dict(failed=True, msg="Error: %s" % error)
563
564 if results['failed']:
565 module.fail_json(**results)
566 else:
567 module.exit_json(**results)
568
569
570 if __name__ == "__main__":
571 main()