Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2017, Wei Gao <[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 DOCUMENTATION = r'''
13 ---
14 module: vmware_host_facts
15 short_description: Gathers facts about remote ESXi hostsystem
16 description:
17 - This module can be used to gathers facts like CPU, memory, datastore, network and system etc. about ESXi host system.
18 - Please specify hostname or IP address of ESXi host system as O(hostname).
19 - If hostname or IP address of vCenter is provided as O(hostname) and O(esxi_hostname) is not specified, then the
20 module will throw an error.
21 - Please note that when ESXi host connection state is not C(connected), facts returned from vCenter might be stale.
22 Users are recommended to check connection state value and take appropriate decision in the playbook.
23 author:
24 - Wei Gao (@woshihaoren)
25 options:
26 esxi_hostname:
27 description:
28 - ESXi hostname.
29 - Host facts about the specified ESXi server will be returned.
30 - By specifying this option, you can select which ESXi hostsystem is returned if connecting to a vCenter.
31 type: str
32 show_tag:
33 description:
34 - Tags related to Host are shown if set to V(true).
35 default: false
36 type: bool
37 required: false
38 show_datacenter:
39 version_added: 4.2.0
40 description:
41 - Return the related Datacenter if set to V(true).
42 default: false
43 type: bool
44 required: false
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 - If not specified, all properties are retrieved (deeply).
57 - Results are returned in a structure identical to the vsphere API.
58 - 'Example:'
59 - ' properties: ['
60 - ' "hardware.memorySize",'
61 - ' "hardware.cpuInfo.numCpuCores",'
62 - ' "config.product.apiVersion",'
63 - ' "overallStatus"'
64 - ' ]'
65 - Only valid when O(schema=vsphere).
66 type: list
67 elements: str
68 required: false
69 extends_documentation_fragment:
70 - vmware.vmware.base_options
71
72 '''
73
74 EXAMPLES = r'''
75 - name: Gather vmware host facts
76 community.vmware.vmware_host_facts:
77 hostname: "{{ esxi_server }}"
78 username: "{{ esxi_username }}"
79 password: "{{ esxi_password }}"
80 register: host_facts
81 delegate_to: localhost
82
83 - name: Gather vmware host facts from vCenter
84 community.vmware.vmware_host_facts:
85 hostname: "{{ vcenter_hostname }}"
86 username: "{{ vcenter_username }}"
87 password: "{{ vcenter_password }}"
88 esxi_hostname: "{{ esxi_hostname }}"
89 register: host_facts
90 delegate_to: localhost
91
92 - name: Gather vmware host facts from vCenter with tag information
93 community.vmware.vmware_host_facts:
94 hostname: "{{ vcenter_hostname }}"
95 username: "{{ vcenter_username }}"
96 password: "{{ vcenter_password }}"
97 esxi_hostname: "{{ esxi_hostname }}"
98 show_tag: true
99 register: host_facts_tag
100 delegate_to: localhost
101
102 - name: Get VSAN Cluster UUID from host facts
103 community.vmware.vmware_host_facts:
104 hostname: "{{ esxi_server }}"
105 username: "{{ esxi_username }}"
106 password: "{{ esxi_password }}"
107 register: host_facts
108 - set_fact:
109 cluster_uuid: "{{ host_facts['ansible_facts']['vsan_cluster_uuid'] }}"
110
111 - name: Gather some info from a host using the vSphere API output schema
112 community.vmware.vmware_host_facts:
113 hostname: "{{ vcenter_hostname }}"
114 username: "{{ vcenter_username }}"
115 password: "{{ vcenter_password }}"
116 esxi_hostname: "{{ esxi_hostname }}"
117 schema: vsphere
118 properties:
119 - hardware.memorySize
120 - hardware.cpuInfo.numCpuCores
121 - config.product.apiVersion
122 - overallStatus
123 register: host_facts
124
125 - name: Gather information about powerstate and connection state
126 community.vmware.vmware_host_facts:
127 hostname: "{{ vcenter_hostname }}"
128 username: "{{ vcenter_username }}"
129 password: "{{ vcenter_password }}"
130 esxi_hostname: "{{ esxi_hostname }}"
131 schema: vsphere
132 properties:
133 - runtime.connectionState
134 - runtime.powerState
135
136 - name: How to retrieve Product, Version, Build, Update info for ESXi from vCenter
137 block:
138 - name: Gather product version info for ESXi from vCenter
139 community.vmware.vmware_host_facts:
140 hostname: "{{ vcenter_hostname }}"
141 username: "{{ vcenter_username }}"
142 password: "{{ vcenter_password }}"
143 esxi_hostname: "{{ esxi_hostname }}"
144 schema: vsphere
145 properties:
146 - config.product
147 - config.option
148 register: gather_host_facts_result
149
150 - name: Extract update level info from option properties
151 set_fact:
152 update_level_info: "{{ item.value }}"
153 loop: "{{ gather_host_facts_result.ansible_facts.config.option }}"
154 when:
155 - item.key == 'Misc.HostAgentUpdateLevel'
156
157 - name: The output of Product, Version, Build, Update info for ESXi
158 debug:
159 msg:
160 - "Product : {{ gather_host_facts_result.ansible_facts.config.product.name }}"
161 - "Version : {{ gather_host_facts_result.ansible_facts.config.product.version }}"
162 - "Build : {{ gather_host_facts_result.ansible_facts.config.product.build }}"
163 - "Update : {{ update_level_info }}"
164 '''
165
166 RETURN = r'''
167 ansible_facts:
168 description: system info about the host machine
169 returned: always
170 type: dict
171 sample:
172 {
173 "ansible_all_ipv4_addresses": [
174 "10.76.33.200"
175 ],
176 "ansible_bios_date": "2011-01-01T00:00:00+00:00",
177 "ansible_bios_version": "0.5.1",
178 "ansible_datastore": [
179 {
180 "free": "11.63 GB",
181 "name": "datastore1",
182 "total": "12.50 GB"
183 }
184 ],
185 "ansible_distribution": "VMware ESXi",
186 "ansible_distribution_build": "4887370",
187 "ansible_distribution_version": "6.5.0",
188 "ansible_hostname": "10.76.33.100",
189 "ansible_in_maintenance_mode": true,
190 "ansible_interfaces": [
191 "vmk0"
192 ],
193 "ansible_memfree_mb": 2702,
194 "ansible_memtotal_mb": 4095,
195 "ansible_os_type": "vmnix-x86",
196 "ansible_processor": "Intel Xeon E312xx (Sandy Bridge)",
197 "ansible_processor_cores": 2,
198 "ansible_processor_count": 2,
199 "ansible_processor_vcpus": 2,
200 "ansible_product_name": "KVM",
201 "ansible_product_serial": "NA",
202 "ansible_system_vendor": "Red Hat",
203 "ansible_uptime": 1791680,
204 "ansible_uuid": "4c4c4544-0052-3410-804c-b2c04f4e3632",
205 "ansible_vmk0": {
206 "device": "vmk0",
207 "ipv4": {
208 "address": "10.76.33.100",
209 "netmask": "255.255.255.0"
210 },
211 "macaddress": "52:54:00:56:7d:59",
212 "mtu": 1500
213 },
214 "vsan_cluster_uuid": null,
215 "vsan_node_uuid": null,
216 "vsan_health": "unknown",
217 "tags": [
218 {
219 "category_id": "urn:vmomi:InventoryServiceCategory:8eb81431-b20d-49f5-af7b-126853aa1189:GLOBAL",
220 "category_name": "host_category_0001",
221 "description": "",
222 "id": "urn:vmomi:InventoryServiceTag:e9398232-46fd-461a-bf84-06128e182a4a:GLOBAL",
223 "name": "host_tag_0001"
224 }
225 ],
226 }
227 '''
228
229 from ansible.module_utils.basic import AnsibleModule
230 from ansible.module_utils.common.text.converters import to_native
231 from ansible.module_utils.common.text.formatters import bytes_to_human
232 from ansible_collections.community.vmware.plugins.module_utils.vmware import (
233 PyVmomi,
234 find_obj,
235 ansible_date_time_facts
236 )
237 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
238
239 try:
240 from pyVmomi import vim, vmodl
241 except ImportError:
242 pass
243
244 from ansible_collections.community.vmware.plugins.module_utils.vmware_rest_client import VmwareRestClient
245
246
247 class VMwareHostFactManager(PyVmomi):
248 def __init__(self, module):
249 super(VMwareHostFactManager, self).__init__(module)
250 esxi_host_name = self.params.get('esxi_hostname', None)
251 if self.is_vcenter():
252 if esxi_host_name is None:
253 self.module.fail_json(msg="Connected to a vCenter system without specifying esxi_hostname")
254 self.host = self.get_all_host_objs(esxi_host_name=esxi_host_name)
255 if len(self.host) > 1:
256 self.module.fail_json(msg="esxi_hostname matched multiple hosts")
257 self.host = self.host[0]
258 self.esxi_time = None
259 else:
260 self.host = find_obj(self.content, [vim.HostSystem], None)
261 self.esxi_time = self.si.CurrentTime()
262
263 if self.host is None:
264 self.module.fail_json(msg="Failed to find host system.")
265
266 def all_facts(self):
267 ansible_facts = {}
268 ansible_facts.update(self.get_cpu_facts())
269 ansible_facts.update(self.get_memory_facts())
270 ansible_facts.update(self.get_datastore_facts())
271 ansible_facts.update(self.get_network_facts())
272 ansible_facts.update(self.get_system_facts())
273 ansible_facts.update(self.get_vsan_facts())
274 ansible_facts.update(self.get_cluster_facts())
275 ansible_facts.update({'host_date_time': ansible_date_time_facts(self.esxi_time)})
276 if self.params.get('show_datacenter'):
277 ansible_facts.update(self.get_datacenter_facts())
278 if self.params.get('show_tag'):
279 vmware_client = VmwareRestClient(self.module)
280 tag_info = {
281 'tags': vmware_client.get_tags_for_hostsystem(hostsystem_mid=self.host._moId)
282 }
283 ansible_facts.update(tag_info)
284
285 self.module.exit_json(changed=False, ansible_facts=ansible_facts)
286
287 def get_cluster_facts(self):
288 cluster_facts = {'cluster': None}
289 if self.host.parent and isinstance(self.host.parent, vim.ClusterComputeResource):
290 cluster_facts.update(cluster=self.host.parent.name)
291 return cluster_facts
292
293 def get_datacenter_facts(self):
294 datatacenter_facts = {'datacenter': None}
295
296 parent = self.host.parent
297 while parent:
298 if isinstance(parent, vim.Datacenter):
299 datatacenter_facts.update(datacenter=parent.name)
300 break
301 parent = parent.parent
302
303 return datatacenter_facts
304
305 def get_vsan_facts(self):
306 config_mgr = self.host.configManager.vsanSystem
307 ret = {
308 'vsan_cluster_uuid': None,
309 'vsan_node_uuid': None,
310 'vsan_health': "unknown",
311 }
312
313 if config_mgr is None:
314 return ret
315
316 try:
317 status = config_mgr.QueryHostStatus()
318 except (vmodl.fault.HostNotConnected, vmodl.fault.HostNotReachable):
319 return {
320 'vsan_cluster_uuid': 'NA',
321 'vsan_node_uuid': 'NA',
322 'vsan_health': 'NA',
323 }
324 except Exception as err:
325 self.module.fail_json(msg="Unable to query VSAN status due to %s" % to_native(err))
326
327 return {
328 'vsan_cluster_uuid': status.uuid,
329 'vsan_node_uuid': status.nodeUuid,
330 'vsan_health': status.health,
331 }
332
333 def get_cpu_facts(self):
334 return {
335 'ansible_processor': self.host.summary.hardware.cpuModel,
336 'ansible_processor_cores': self.host.summary.hardware.numCpuCores,
337 'ansible_processor_count': self.host.summary.hardware.numCpuPkgs,
338 'ansible_processor_vcpus': self.host.summary.hardware.numCpuThreads,
339 }
340
341 def get_memory_facts(self):
342 memory_size = self.host.hardware.memorySize
343 overall_memory = 0
344 if self.host.summary.quickStats.overallMemoryUsage:
345 overall_memory = self.host.summary.quickStats.overallMemoryUsage
346 memory_total = memory_size // 1024 // 1024
347 return {
348 'ansible_memfree_mb': memory_total - overall_memory,
349 'ansible_memtotal_mb': memory_total,
350 }
351
352 def get_datastore_facts(self):
353 facts = dict()
354 facts['ansible_datastore'] = []
355 for store in self.host.datastore:
356 _tmp = {
357 'name': store.summary.name,
358 'total': bytes_to_human(store.summary.capacity),
359 'free': bytes_to_human(store.summary.freeSpace),
360 }
361 facts['ansible_datastore'].append(_tmp)
362 return facts
363
364 def get_network_facts(self):
365 facts = dict()
366 facts['ansible_interfaces'] = []
367 facts['ansible_all_ipv4_addresses'] = []
368 for nic in self.host.config.network.vnic:
369 device = nic.device
370 facts['ansible_interfaces'].append(device)
371 facts['ansible_all_ipv4_addresses'].append(nic.spec.ip.ipAddress)
372 _tmp = {
373 'device': device,
374 'ipv4': {
375 'address': nic.spec.ip.ipAddress,
376 'netmask': nic.spec.ip.subnetMask,
377 },
378 'macaddress': nic.spec.mac,
379 'mtu': nic.spec.mtu,
380 }
381 facts['ansible_' + device] = _tmp
382 return facts
383
384 def get_system_facts(self):
385 sn = 'NA'
386 for info in self.host.hardware.systemInfo.otherIdentifyingInfo:
387 if info.identifierType.key == 'ServiceTag':
388 sn = info.identifierValue
389 facts = {
390 'ansible_host_connection_state': self.host.runtime.connectionState,
391 'ansible_distribution': self.host.config.product.name,
392 'ansible_distribution_version': self.host.config.product.version,
393 'ansible_distribution_build': self.host.config.product.build,
394 'ansible_os_type': self.host.config.product.osType,
395 'ansible_system_vendor': self.host.hardware.systemInfo.vendor,
396 'ansible_hostname': self.host.summary.config.name,
397 'ansible_product_name': self.host.hardware.systemInfo.model,
398 'ansible_product_serial': sn,
399 'ansible_bios_date': self.host.hardware.biosInfo.releaseDate,
400 'ansible_bios_version': self.host.hardware.biosInfo.biosVersion,
401 'ansible_uptime': self.host.summary.quickStats.uptime,
402 'ansible_in_maintenance_mode': self.host.runtime.inMaintenanceMode,
403 'ansible_uuid': self.host.hardware.systemInfo.uuid,
404 }
405 return facts
406
407 def properties_facts(self):
408 ansible_facts = self.to_json(self.host, self.params.get('properties'))
409 if self.params.get('show_tag'):
410 vmware_client = VmwareRestClient(self.module)
411 tag_info = {
412 'tags': vmware_client.get_tags_for_hostsystem(hostsystem_mid=self.host._moId)
413 }
414 ansible_facts.update(tag_info)
415
416 self.module.exit_json(changed=False, ansible_facts=ansible_facts)
417
418
419 def main():
420 argument_spec = base_argument_spec()
421 argument_spec.update(
422 esxi_hostname=dict(type='str', required=False),
423 show_tag=dict(type='bool', default=False),
424 show_datacenter=dict(type='bool', default=False),
425 schema=dict(type='str', choices=['summary', 'vsphere'], default='summary'),
426 properties=dict(type='list', elements='str')
427 )
428 module = AnsibleModule(argument_spec=argument_spec,
429 supports_check_mode=True)
430
431 vm_host_manager = VMwareHostFactManager(module)
432
433 if module.params['schema'] == 'summary':
434 vm_host_manager.all_facts()
435 else:
436 vm_host_manager.properties_facts()
437
438
439 if __name__ == '__main__':
440 main()