Debian Codegraph @

ansible_collections/community/vmware/plugins/modules/vmware_cluster_info.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_cluster_info
16 deprecated:
17 removed_in: 7.0.0
18 why: This module has been moved to the L(new vmware.vmware collection,https://forum.ansible.com/t/5880)
19 alternative: Use M(vmware.vmware.cluster_info) instead.
20 short_description: Gather info about clusters available in given vCenter
21 description:
22 - This module can be used to gather information about clusters in VMWare infrastructure.
23 author:
24 - Abhijeet Kasurde (@Akasurde)
25 - Christian Neugum (@digifuchsi)
26 options:
27 datacenter:
28 description:
29 - Datacenter to search for cluster/s.
30 - This parameter is required, if O(cluster_name) is not supplied.
31 required: false
32 type: str
33 cluster_name:
34 description:
35 - Name of the cluster.
36 - If set, information of this cluster will be returned.
37 - This parameter is required, if O(datacenter) is not supplied.
38 required: false
39 type: str
40 show_tag:
41 description:
42 - Tags related to cluster are shown if set to V(true).
43 default: false
44 type: bool
45 schema:
46 description:
47 - Specify the output schema desired.
48 - The V(summary) output schema is the legacy output from the module.
49 - The V(vsphere) output schema is the vSphere API class definition.
50 choices: ['summary', 'vsphere']
51 default: 'summary'
52 type: str
53 properties:
54 description:
55 - Specify the properties to retrieve.
56 - 'Example:'
57 - ' properties: ['
58 - ' "name",'
59 - ' "configuration.dasConfig.enabled",'
60 - ' "summary.totalCpu"'
61 - ' ]'
62 - Only valid when O(schema=vsphere).
63 type: list
64 elements: str
65 extends_documentation_fragment:
66 - vmware.vmware.base_options
67
68 '''
69
70 EXAMPLES = r'''
71 - name: Gather cluster info from given datacenter
72 community.vmware.vmware_cluster_info:
73 hostname: '{{ vcenter_hostname }}'
74 username: '{{ vcenter_username }}'
75 password: '{{ vcenter_password }}'
76 datacenter: ha-datacenter
77 delegate_to: localhost
78 register: cluster_info
79
80 - name: Gather info from datacenter about specific cluster
81 community.vmware.vmware_cluster_info:
82 hostname: '{{ vcenter_hostname }}'
83 username: '{{ vcenter_username }}'
84 password: '{{ vcenter_password }}'
85 cluster_name: DC0_C0
86 delegate_to: localhost
87 register: cluster_info
88
89 - name: Gather info from datacenter about specific cluster with tags
90 community.vmware.vmware_cluster_info:
91 hostname: '{{ vcenter_hostname }}'
92 username: '{{ vcenter_username }}'
93 password: '{{ vcenter_password }}'
94 cluster_name: DC0_C0
95 show_tag: true
96 delegate_to: localhost
97 register: cluster_info
98
99 - name: Gather some info from a cluster using the vSphere API output schema
100 vmware_cluster_info:
101 hostname: '{{ vcenter_hostname }}'
102 username: '{{ vcenter_username }}'
103 password: '{{ vcenter_password }}'
104 cluster_name: DC0_C0
105 schema: vsphere
106 properties:
107 - name
108 - configuration.dasConfig.enabled
109 - summary.totalCpu
110 delegate_to: localhost
111 register: cluster_info
112 '''
113
114 RETURN = r'''
115 clusters:
116 description:
117 - metadata about the available clusters
118 returned: always
119 type: dict
120 sample: {
121 "DC0_C0": {
122 "datacenter": "DC0",
123 "moid": "domain-c9",
124 "drs_default_vm_behavior": null,
125 "drs_enable_vm_behavior_overrides": null,
126 "drs_vmotion_rate": null,
127 "enable_ha": null,
128 "enabled_drs": true,
129 "enabled_vsan": false,
130 "ha_admission_control_enabled": null,
131 "ha_failover_level": null,
132 "ha_host_monitoring": null,
133 "ha_restart_priority": null,
134 "ha_vm_failure_interval": null,
135 "ha_vm_max_failure_window": null,
136 "ha_vm_max_failures": null,
137 "ha_vm_min_up_time": null,
138 "ha_vm_monitoring": null,
139 "ha_vm_tools_monitoring": null,
140 "vsan_auto_claim_storage": false,
141 "hosts": [
142 {
143 "name": "esxi01.vsphere.local",
144 "folder": "/DC0/host/DC0_C0",
145 },
146 {
147 "name": "esxi02.vsphere.local",
148 "folder": "/DC0/host/DC0_C0",
149 },
150 {
151 "name": "esxi03.vsphere.local",
152 "folder": "/DC0/host/DC0_C0",
153 },
154 {
155 "name": "esxi04.vsphere.local",
156 "folder": "/DC0/host/DC0_C0",
157 },
158 ],
159 "resource_summary": {
160 "cpuCapacityMHz": 4224,
161 "cpuUsedMHz": 87,
162 "memCapacityMB": 6139,
163 "memUsedMB": 1254,
164 "pMemAvailableMB": 0,
165 "pMemCapacityMB": 0,
166 "storageCapacityMB": 33280,
167 "storageUsedMB": 19953
168 },
169 "tags": [
170 {
171 "category_id": "urn:vmomi:InventoryServiceCategory:9fbf83de-7903-442e-8004-70fd3940297c:GLOBAL",
172 "category_name": "sample_cluster_cat_0001",
173 "description": "",
174 "id": "urn:vmomi:InventoryServiceTag:93d680db-b3a6-4834-85ad-3e9516e8fee8:GLOBAL",
175 "name": "sample_cluster_tag_0001"
176 }
177 ],
178 },
179 }
180 '''
181
182 try:
183 from pyVmomi import vim
184 except ImportError:
185 pass
186
187 from ansible.module_utils.basic import AnsibleModule
188 from urllib.parse import unquote
189 from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi, find_datacenter_by_name, find_cluster_by_name, get_parent_datacenter
190 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
191 from ansible_collections.community.vmware.plugins.module_utils.vmware_rest_client import VmwareRestClient
192
193
194 class VmwreClusterInfoManager(PyVmomi):
195 def __init__(self, module):
196 super(VmwreClusterInfoManager, self).__init__(module)
197 datacenter = self.params.get('datacenter')
198 cluster_name = self.params.get('cluster_name')
199 self.schema = self.params.get('schema')
200 self.properties = self.params.get('properties')
201 self.cluster_objs = []
202 if datacenter:
203 datacenter_obj = find_datacenter_by_name(self.content, datacenter_name=datacenter)
204 if datacenter_obj is None:
205 self.module.fail_json(msg="Failed to find datacenter '%s'" % datacenter)
206 self.cluster_objs = self.get_all_cluster_objs(parent=datacenter_obj)
207 elif cluster_name:
208 cluster_obj = find_cluster_by_name(self.content, cluster_name=cluster_name)
209 if cluster_obj is None:
210 self.module.fail_json(msg="Failed to find cluster '%s'" % cluster_name)
211
212 self.cluster_objs = [cluster_obj]
213
214 def get_all_cluster_objs(self, parent):
215 """
216 Get all cluster managed objects from given parent object
217 Args:
218 parent: Managed objected of datacenter or host folder
219
220 Returns: List of host managed objects
221
222 """
223 cluster_objs = []
224 if isinstance(parent, vim.Datacenter):
225 folder = parent.hostFolder
226 else:
227 folder = parent
228
229 for child in folder.childEntity:
230 if isinstance(child, vim.Folder):
231 cluster_objs = cluster_objs + self.get_all_cluster_objs(child)
232 if isinstance(child, vim.ClusterComputeResource):
233 cluster_objs.append(child)
234 return cluster_objs
235
236 def gather_cluster_info(self):
237 """
238 Gather information about cluster
239 """
240 results = dict(changed=False, clusters=dict())
241
242 if self.schema == 'summary':
243 for cluster in self.cluster_objs:
244 # Default values
245 ha_failover_level = None
246 ha_restart_priority = None
247 ha_vm_tools_monitoring = None
248 ha_vm_min_up_time = None
249 ha_vm_max_failures = None
250 ha_vm_max_failure_window = None
251 ha_vm_failure_interval = None
252 enabled_vsan = False
253 vsan_auto_claim_storage = False
254 hosts = []
255
256 # Hosts
257 for host in cluster.host:
258 hosts.append({
259 'name': host.name,
260 'folder': self.get_vm_path(self.content, host),
261 })
262
263 # HA
264 das_config = cluster.configurationEx.dasConfig
265 if das_config.admissionControlPolicy:
266 ha_failover_level = das_config.admissionControlPolicy.failoverLevel
267 if das_config.defaultVmSettings:
268 ha_restart_priority = das_config.defaultVmSettings.restartPriority
269 ha_vm_tools_monitoring = das_config.defaultVmSettings.vmToolsMonitoringSettings.vmMonitoring
270 ha_vm_min_up_time = das_config.defaultVmSettings.vmToolsMonitoringSettings.minUpTime
271 ha_vm_max_failures = das_config.defaultVmSettings.vmToolsMonitoringSettings.maxFailures
272 ha_vm_max_failure_window = das_config.defaultVmSettings.vmToolsMonitoringSettings.maxFailureWindow
273 ha_vm_failure_interval = das_config.defaultVmSettings.vmToolsMonitoringSettings.failureInterval
274
275 # DRS
276 drs_config = cluster.configurationEx.drsConfig
277
278 # VSAN
279 if hasattr(cluster.configurationEx, 'vsanConfigInfo'):
280 vsan_config = cluster.configurationEx.vsanConfigInfo
281 enabled_vsan = vsan_config.enabled
282 vsan_auto_claim_storage = vsan_config.defaultConfig.autoClaimStorage
283
284 tag_info = []
285 if self.params.get('show_tag'):
286 vmware_client = VmwareRestClient(self.module)
287 tag_info = vmware_client.get_tags_for_cluster(cluster_mid=cluster._moId)
288
289 resource_summary = self.to_json(cluster.GetResourceUsage())
290 if '_vimtype' in resource_summary:
291 del resource_summary['_vimtype']
292
293 results['clusters'][unquote(cluster.name)] = dict(
294 hosts=hosts,
295 enable_ha=das_config.enabled,
296 ha_failover_level=ha_failover_level,
297 ha_vm_monitoring=das_config.vmMonitoring,
298 ha_host_monitoring=das_config.hostMonitoring,
299 ha_admission_control_enabled=das_config.admissionControlEnabled,
300 ha_restart_priority=ha_restart_priority,
301 ha_vm_tools_monitoring=ha_vm_tools_monitoring,
302 ha_vm_min_up_time=ha_vm_min_up_time,
303 ha_vm_max_failures=ha_vm_max_failures,
304 ha_vm_max_failure_window=ha_vm_max_failure_window,
305 ha_vm_failure_interval=ha_vm_failure_interval,
306 enabled_drs=drs_config.enabled,
307 drs_enable_vm_behavior_overrides=drs_config.enableVmBehaviorOverrides,
308 drs_default_vm_behavior=drs_config.defaultVmBehavior,
309 drs_vmotion_rate=drs_config.vmotionRate,
310 enabled_vsan=enabled_vsan,
311 vsan_auto_claim_storage=vsan_auto_claim_storage,
312 tags=tag_info,
313 resource_summary=resource_summary,
314 moid=cluster._moId,
315 datacenter=get_parent_datacenter(cluster).name
316 )
317 else:
318 for cluster in self.cluster_objs:
319 results['clusters'][unquote(cluster.name)] = self.to_json(cluster, self.properties)
320
321 self.module.exit_json(**results)
322
323
324 def main():
325 argument_spec = base_argument_spec()
326 argument_spec.update(
327 datacenter=dict(type='str'),
328 cluster_name=dict(type='str'),
329 show_tag=dict(type='bool', default=False),
330 schema=dict(type='str', choices=['summary', 'vsphere'], default='summary'),
331 properties=dict(type='list', elements='str')
332 )
333 module = AnsibleModule(
334 argument_spec=argument_spec,
335 required_one_of=[
336 ['cluster_name', 'datacenter'],
337 ],
338 supports_check_mode=True,
339 )
340
341 pyv = VmwreClusterInfoManager(module)
342 pyv.gather_cluster_info()
343
344
345 if __name__ == '__main__':
346 main()