Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2017, Tim Rightnour <[email protected]>
5 # Copyright: (c) 2018, Ansible Project
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_datastore_info
16 short_description: Gather info about datastores available in given vCenter
17 description:
18 - This module can be used to gather information about datastores in VMWare infrastructure.
19 author:
20 - Tim Rightnour (@garbled1)
21 options:
22 name:
23 description:
24 - Name of the datastore to match.
25 - If set, information of specific datastores are returned.
26 required: false
27 type: str
28 datacenter:
29 description:
30 - Datacenter to search for datastores.
31 - This parameter is required, if O(cluster) is not supplied.
32 required: false
33 aliases: ['datacenter_name']
34 type: str
35 cluster:
36 description:
37 - Cluster to search for datastores.
38 - If set, information of datastores belonging this clusters will be returned.
39 - This parameter is required, if O(datacenter) is not supplied.
40 required: false
41 type: str
42 gather_nfs_mount_info:
43 description:
44 - Gather mount information of NFS datastores.
45 - Disabled per default because this slows down the execution if you have a lot of datastores.
46 - Only valid when O(schema=summary).
47 type: bool
48 default: false
49 gather_vmfs_mount_info:
50 description:
51 - Gather mount information of VMFS datastores.
52 - Disabled per default because this slows down the execution if you have a lot of datastores.
53 - Only valid when O(schema=summary).
54 type: bool
55 default: false
56 schema:
57 description:
58 - Specify the output schema desired.
59 - The 'summary' output schema is the legacy output from the module
60 - The 'vsphere' output schema is the vSphere API class definition
61 choices: ['summary', 'vsphere']
62 default: 'summary'
63 type: str
64 show_tag:
65 description:
66 - Tags related to Datastore are shown if set to V(true).
67 default: false
68 type: bool
69 properties:
70 description:
71 - Specify the properties to retrieve.
72 - If not specified, all properties are retrieved (deeply).
73 - Results are returned in a structure identical to the vsphere API.
74 - 'Example:'
75 - ' properties: ['
76 - ' "name",'
77 - ' "info.vmfs.ssd",'
78 - ' "capability.vsanSparseSupported",'
79 - ' "overallStatus"'
80 - ' ]'
81 - Only valid when O(schema=vsphere).
82 type: list
83 required: false
84 elements: str
85 extends_documentation_fragment:
86 - vmware.vmware.base_options
87
88 '''
89
90 EXAMPLES = r'''
91 - name: Gather info from standalone ESXi server having datacenter as 'ha-datacenter'
92 community.vmware.vmware_datastore_info:
93 hostname: '{{ esxi_hostname }}'
94 username: '{{ esxi_username }}'
95 password: '{{ esxi_password }}'
96 datacenter_name: "ha-datacenter"
97 delegate_to: localhost
98 register: info
99
100 - name: Gather info from datacenter about specific datastore
101 community.vmware.vmware_datastore_info:
102 hostname: '{{ vcenter_hostname }}'
103 username: '{{ vcenter_username }}'
104 password: '{{ vcenter_password }}'
105 datacenter_name: '{{ datacenter_name }}'
106 name: datastore1
107 delegate_to: localhost
108 register: info
109
110 - name: Gather some info from a datastore using the vSphere API output schema
111 community.vmware.vmware_datastore_info:
112 hostname: '{{ vcenter_hostname }}'
113 username: '{{ vcenter_username }}'
114 password: '{{ vcenter_password }}'
115 datacenter_name: '{{ datacenter_name }}'
116 schema: vsphere
117 properties:
118 - name
119 - info.vmfs.ssd
120 - capability.vsanSparseSupported
121 - overallStatus
122 delegate_to: localhost
123 register: info
124 '''
125
126 RETURN = r'''
127 datastores:
128 description: metadata about the available datastores
129 returned: always
130 type: list
131 sample: [
132 {
133 "accessible": false,
134 "capacity": 42681237504,
135 "datastore_cluster": "datacluster0",
136 "freeSpace": 39638269952,
137 "maintenanceMode": "normal",
138 "multipleHostAccess": false,
139 "name": "datastore2",
140 "provisioned": 12289211488,
141 "type": "VMFS",
142 "uncommitted": 9246243936,
143 "url": "ds:///vmfs/volumes/5a69b18a-c03cd88c-36ae-5254001249ce/",
144 "vmfs_blockSize": 1024,
145 "vmfs_uuid": "5a69b18a-c03cd88c-36ae-5254001249ce",
146 "vmfs_version": "6.81"
147 },
148 {
149 "accessible": true,
150 "capacity": 5497558138880,
151 "datastore_cluster": "datacluster0",
152 "freeSpace": 4279000641536,
153 "maintenanceMode": "normal",
154 "multipleHostAccess": true,
155 "name": "datastore3",
156 "nfs_path": "/vol/datastore3",
157 "nfs_server": "nfs_server1",
158 "provisioned": 1708109410304,
159 "type": "NFS",
160 "uncommitted": 489551912960,
161 "url": "ds:///vmfs/volumes/420b3e73-67070776/"
162 },
163 ]
164 '''
165
166 try:
167 from pyVmomi import vim
168 except ImportError:
169 pass
170
171 from ansible.module_utils.basic import AnsibleModule
172 from ansible_collections.community.vmware.plugins.module_utils.vmware import (
173 PyVmomi,
174 get_all_objs,
175 find_cluster_by_name,
176 get_parent_datacenter)
177 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
178 from ansible_collections.community.vmware.plugins.module_utils.vmware_rest_client import VmwareRestClient
179
180
181 class VMwareHostDatastore(PyVmomi):
182 """ This class populates the datastore list """
183
184 def __init__(self, module):
185 super(VMwareHostDatastore, self).__init__(module)
186 self.gather_nfs_mount_info = self.module.params['gather_nfs_mount_info']
187 self.gather_vmfs_mount_info = self.module.params['gather_vmfs_mount_info']
188 self.schema = self.module.params['schema']
189 self.properties = self.module.params['properties']
190 if self.module.params['show_tag']:
191 self.vmware_client = VmwareRestClient(self.module)
192
193 def check_datastore_host(self, esxi_host, datastore):
194 """ Get all datastores of specified ESXi host """
195 esxi = self.find_hostsystem_by_name(esxi_host)
196 if esxi is None:
197 self.module.fail_json(msg="Failed to find ESXi hostname %s " % esxi_host)
198 storage_system = esxi.configManager.storageSystem
199 host_file_sys_vol_mount_info = storage_system.fileSystemVolumeInfo.mountInfo
200 for host_mount_info in host_file_sys_vol_mount_info:
201 if host_mount_info.volume.name == datastore:
202 return host_mount_info
203 return None
204
205 def build_datastore_list(self, datastore_list):
206 """ Build list with datastores """
207 datastores = list()
208 for datastore in datastore_list:
209 if self.schema == 'summary':
210 summary = datastore.summary
211 datastore_summary = dict()
212 datastore_summary['accessible'] = summary.accessible
213 datastore_summary['capacity'] = summary.capacity
214 datastore_summary['name'] = summary.name
215 datastore_summary['freeSpace'] = summary.freeSpace
216 datastore_summary['maintenanceMode'] = summary.maintenanceMode
217 datastore_summary['multipleHostAccess'] = summary.multipleHostAccess
218 datastore_summary['type'] = summary.type
219 if self.gather_nfs_mount_info or self.gather_vmfs_mount_info:
220 if self.gather_nfs_mount_info and summary.type.startswith("NFS"):
221 # get mount info from the first ESXi host attached to this NFS datastore
222 host_mount_info = self.check_datastore_host(summary.datastore.host[0].key.name, summary.name)
223 datastore_summary['nfs_server'] = host_mount_info.volume.remoteHost
224 datastore_summary['nfs_path'] = host_mount_info.volume.remotePath
225 if self.gather_vmfs_mount_info and summary.type == "VMFS":
226 # get mount info from the first ESXi host attached to this VMFS datastore
227 host_mount_info = self.check_datastore_host(summary.datastore.host[0].key.name, summary.name)
228 datastore_summary['vmfs_blockSize'] = host_mount_info.volume.blockSize
229 datastore_summary['vmfs_version'] = host_mount_info.volume.version
230 datastore_summary['vmfs_uuid'] = host_mount_info.volume.uuid
231 # uncommitted is optional / not always set
232 if not summary.uncommitted:
233 summary.uncommitted = 0
234 datastore_summary['uncommitted'] = summary.uncommitted
235 datastore_summary['url'] = summary.url
236 # Calculated values
237 datastore_summary['provisioned'] = summary.capacity - summary.freeSpace + summary.uncommitted
238 datastore_summary['datastore_cluster'] = 'N/A'
239 if isinstance(datastore.parent, vim.StoragePod):
240 datastore_summary['datastore_cluster'] = datastore.parent.name
241
242 if self.module.params['show_tag']:
243 datastore_summary['tags'] = self.vmware_client.get_tags_for_datastore(datastore._moId)
244
245 if self.module.params['name']:
246 if datastore_summary['name'] == self.module.params['name']:
247 datastores.extend([datastore_summary])
248 else:
249 datastores.extend([datastore_summary])
250 else:
251 temp_ds = self.to_json(datastore, self.properties)
252 if self.module.params['show_tag']:
253 temp_ds.update({'tags': self.vmware_client.get_tags_for_datastore(datastore._moId)})
254 if self.module.params['name']:
255 if datastore.name == self.module.params['name']:
256 datastores.extend(([temp_ds]))
257 else:
258 datastores.extend(([temp_ds]))
259
260 return datastores
261
262
263 class PyVmomiCache(object):
264 """ This class caches references to objects which are requested multiples times but not modified """
265
266 def __init__(self, content, dc_name=None):
267 self.content = content
268 self.dc_name = dc_name
269 self.clusters = {}
270 self.parent_datacenters = {}
271
272 def get_all_objs(self, content, types, confine_to_datacenter=True):
273 """ Wrapper around get_all_objs to set datacenter context """
274 objects = get_all_objs(content, types)
275 if confine_to_datacenter:
276 if hasattr(objects, 'items'):
277 # resource pools come back as a dictionary
278 for k, v in tuple(objects.items()):
279 parent_dc = get_parent_datacenter(k)
280 if parent_dc.name != self.dc_name:
281 del objects[k]
282 else:
283 # everything else should be a list
284 objects = [x for x in objects if get_parent_datacenter(x).name == self.dc_name]
285
286 return objects
287
288
289 class PyVmomiHelper(PyVmomi):
290 """ This class gets datastores """
291
292 def __init__(self, module):
293 super(PyVmomiHelper, self).__init__(module)
294 self.cache = PyVmomiCache(self.content, dc_name=self.params['datacenter'])
295
296 def lookup_datastore(self, confine_to_datacenter):
297 """ Get datastore(s) per ESXi host or vCenter server """
298 datastores = self.cache.get_all_objs(self.content, [vim.Datastore], confine_to_datacenter)
299 return datastores
300
301 def lookup_datastore_by_cluster(self):
302 """ Get datastore(s) per cluster """
303 cluster = find_cluster_by_name(self.content, self.params['cluster'])
304 if not cluster:
305 self.module.fail_json(msg='Failed to find cluster "%(cluster)s"' % self.params)
306 c_dc = cluster.datastore
307 return c_dc
308
309
310 def main():
311 """ Main """
312 argument_spec = base_argument_spec()
313 argument_spec.update(
314 name=dict(type='str'),
315 datacenter=dict(type='str', aliases=['datacenter_name']),
316 cluster=dict(type='str'),
317 gather_nfs_mount_info=dict(type='bool', default=False),
318 gather_vmfs_mount_info=dict(type='bool', default=False),
319 schema=dict(type='str', choices=['summary', 'vsphere'], default='summary'),
320 properties=dict(type='list', elements='str'),
321 show_tag=dict(type='bool', default=False),
322 )
323 module = AnsibleModule(argument_spec=argument_spec,
324 supports_check_mode=True
325 )
326
327 result = dict(changed=False)
328
329 pyv = PyVmomiHelper(module)
330
331 if module.params['cluster']:
332 dxs = pyv.lookup_datastore_by_cluster()
333 elif module.params['datacenter']:
334 dxs = pyv.lookup_datastore(confine_to_datacenter=True)
335 else:
336 dxs = pyv.lookup_datastore(confine_to_datacenter=False)
337
338 vmware_host_datastore = VMwareHostDatastore(module)
339 datastores = vmware_host_datastore.build_datastore_list(dxs)
340
341 result['datastores'] = datastores
342
343 module.exit_json(**result)
344
345
346 if __name__ == '__main__':
347 main()