VMWare - Rename _facts to _info (#57474)

Deprecate vmware's _facts modules and add new modules.

Fixes: #57278
This commit is contained in:
pratikgadiya12 2019-08-27 00:15:34 +05:30 committed by Gonéri Le Bouder
parent 47c2ff4c26
commit 8ee7d9f598
147 changed files with 7366 additions and 281 deletions

View file

@ -0,0 +1,34 @@
minor_changes:
- The ``vcenter_extension_facts`` module has been deprecated. Use ``vcenter_extension_info`` instead.
- The ``vmware_about_facts`` module has been deprecated. Use ``vmware_about_info`` instead.
- The ``vmware_category_facts`` module has been deprecated. Use ``vmware_category_info`` instead.
- The ``vmware_cluster_facts`` module has been renamed to ``vmware_cluster_info``.
- The ``vmware_datastore_facts`` module has been renamed to ``vmware_datastore_info``.
- The ``vmware_drs_group_facts`` module has been deprecated. Use ``vmware_drs_group_info`` instead.
- The ``vmware_drs_rule_facts`` module has been deprecated. Use ``vmware_drs_rule_info`` instead.
- The ``vmware_dvs_portgroup_facts`` module has been deprecated. Use ``vmware_dvs_portgroup_info`` instead.
- The ``vmware_guest_boot_facts`` module has been deprecated. Use ``vmware_guest_boot_info`` instead.
- The ``vmware_guest_customization_facts`` module has been deprecated. Use ``vmware_guest_customization_info`` instead.
- The ``vmware_guest_disk_facts`` module has been deprecated. Use ``vmware_guest_disk_info`` instead.
- The ``vmware_guest_facts`` module has been renamed to ``vmware_guest_info``.
- The ``vmware_guest_snapshot_facts`` module has been renamed to ``vmware_guest_snapshot_info``.
- The ``vmware_host_capability_facts`` module has been deprecated. Use ``vmware_host_capability_info`` instead.
- The ``vmware_host_config_facts`` module has been deprecated. Use ``vmware_host_config_info`` instead.
- The ``vmware_host_dns_facts`` module has been deprecated. Use ``vmware_host_dns_info`` instead.
- The ``vmware_host_feature_facts`` module has been deprecated. Use ``vmware_host_feature_info`` instead.
- The ``vmware_host_firewall_facts`` module has been deprecated. Use ``vmware_host_firewall_info`` instead.
- The ``vmware_host_ntp_facts`` module has been deprecated. Use ``vmware_host_ntp_info`` instead.
- The ``vmware_host_package_facts`` module has been deprecated. Use ``vmware_host_package_info`` instead.
- The ``vmware_host_service_facts`` module has been deprecated. Use ``vmware_host_service_info`` instead.
- The ``vmware_host_ssl_facts`` module has been deprecated. Use ``vmware_host_ssl_info`` instead.
- The ``vmware_host_vmhba_facts`` module has been deprecated. Use ``vmware_host_vmhba_info`` instead.
- The ``vmware_host_vmnic_facts`` module has been deprecated. Use ``vmware_host_vmnic_info`` instead.
- The ``vmware_local_role_facts`` module has been deprecated. Use ``vmware_local_role_info`` instead.
- The ``vmware_local_user_facts`` module has been deprecated. Use ``vmware_local_user_info`` instead.
- The ``vmware_portgroup_facts`` module has been deprecated. Use ``vmware_portgroup_info`` instead.
- The ``vmware_resource_pool_facts`` module has been deprecated. Use ``vmware_resource_pool_info`` instead.
- The ``vmware_tag_facts`` module has been renamed to ``vmware_tag_info``.
- The ``vmware_target_canonical_facts`` module has been deprecated. Use ``vmware_target_canonical_info`` instead.
- The ``vmware_vm_facts`` module has been renamed to ``vmware_vm_info``.
- The ``vmware_vmkernel_facts`` module has been deprecated. Use ``vmware_vmkernel_info`` instead.
- The ``vmware_vswitch_facts`` module has been deprecated. Use ``vmware_vswitch_info`` instead.

View file

@ -120,6 +120,60 @@ The following modules will be removed in Ansible 2.13. Please update update your
* purefb_facts use :ref:`purefb_info <purefb_info_module>` instead.
* vcenter_extension_facts use :ref:`vcenter_extension_info <vcenter_extension_info_module>` instead.
* vmware_about_facts use :ref:`vmware_about_info <vmware_about_info_module>` instead.
* vmware_category_facts use :ref:`vmware_category_info <vmware_category_info_module>` instead.
* vmware_drs_group_facts use :ref:`vmware_drs_group_info <vmware_drs_group_info_module>` instead.
* vmware_drs_rule_facts use :ref:`vmware_drs_rule_info <vmware_drs_rule_info_module>` instead.
* vmware_dvs_portgroup_facts use :ref:`vmware_dvs_portgroup_info <vmware_dvs_portgroup_info_module>` instead.
* vmware_guest_boot_facts use :ref:`vmware_guest_boot_info <vmware_guest_boot_info_module>` instead.
* vmware_guest_customization_facts use :ref:`vmware_guest_customization_info <vmware_guest_customization_info_module>` instead.
* vmware_guest_disk_facts use :ref:`vmware_guest_disk_info <vmware_guest_disk_info_module>` instead.
* vmware_host_capability_facts use :ref:`vmware_host_capability_info <vmware_host_capability_info_module>` instead.
* vmware_host_config_facts use :ref:`vmware_host_config_info <vmware_host_config_info_module>` instead.
* vmware_host_dns_facts use :ref:`vmware_host_dns_info <vmware_host_dns_info_module>` instead.
* vmware_host_feature_facts use :ref:`vmware_host_feature_info <vmware_host_feature_info_module>` instead.
* vmware_host_firewall_facts use :ref:`vmware_host_firewall_info <vmware_host_firewall_info_module>` instead.
* vmware_host_ntp_facts use :ref:`vmware_host_ntp_info <vmware_host_ntp_info_module>` instead.
* vmware_host_package_facts use :ref:`vmware_host_package_info <vmware_host_package_info_module>` instead.
* vmware_host_service_facts use :ref:`vmware_host_service_info <vmware_host_service_info_module>` instead.
* vmware_host_ssl_facts use :ref:`vmware_host_ssl_info <vmware_host_ssl_info_module>` instead.
* vmware_host_vmhba_facts use :ref:`vmware_host_vmhba_info <vmware_host_vmhba_info_module>` instead.
* vmware_host_vmnic_facts use :ref:`vmware_host_vmnic_info <vmware_host_vmnic_info_module>` instead.
* vmware_local_role_facts use :ref:`vmware_local_role_info <vmware_local_role_info_module>` instead.
* vmware_local_user_facts use :ref:`vmware_local_user_info <vmware_local_user_info_module>` instead.
* vmware_portgroup_facts use :ref:`vmware_portgroup_info <vmware_portgroup_info_module>` instead.
* vmware_resource_pool_facts use :ref:`vmware_resource_pool_info <vmware_resource_pool_info_module>` instead.
* vmware_target_canonical_facts use :ref:`vmware_target_canonical_info <vmware_target_canonical_info_module>` instead.
* vmware_vmkernel_facts use :ref:`vmware_vmkernel_info <vmware_vmkernel_info_module>` instead.
* vmware_vswitch_facts use :ref:`vmware_vswitch_info <vmware_vswitch_info_module>` instead.
* vultr_dns_domain_facts use :ref:`vultr_dns_domain_info <vultr_dns_domain_info_module>` instead.
* vultr_firewall_group_facts use :ref:`vultr_firewall_group_info <vultr_firewall_group_info_module>` instead.
@ -354,6 +408,12 @@ be removed in Ansible 2.13. Please update update your playbooks accordingly.
To access return values, :ref:`register a variable <registered_variables>`.
* The ``redshift_facts`` module was renamed to :ref:`redshift_info <redshift_info_module>`.
* The ``route53_facts`` module was renamed to :ref:`route53_info <route53_info_module>`.
* The ``vmware_cluster_facts`` module was renamed to :ref:`vmware_cluster_info <vmware_cluster_info_module>`.
* The ``vmware_datastore_facts`` module was renamed to :ref:`vmware_datastore_info <vmware_datastore_info_module>`.
* The ``vmware_guest_facts`` module was renamed to :ref:`vmware_guest_info <vmware_guest_info_module>`.
* The ``vmware_guest_snapshot_facts`` module was renamed to :ref:`vmware_guest_snapshot_info <vmware_guest_snapshot_info_module>`.
* The ``vmware_tag_facts`` module was renamed to :ref:`vmware_tag_info <vmware_tag_info_module>`.
* The ``vmware_vm_facts`` module was renamed to :ref:`vmware_vm_info <vmware_vm_info_module>`.
* The ``xenserver_guest_facts`` module was renamed to :ref:`xenserver_guest_info <xenserver_guest_info_module>`.
* The ``zabbix_group_facts`` module was renamed to :ref:`zabbix_group_info <zabbix_group_info_module>`.
* The ``zabbix_host_facts`` module was renamed to :ref:`zabbix_host_info <zabbix_host_info_module>`.

View file

@ -9,13 +9,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vcenter_extension_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vcenter_extension_info) instead.
short_description: Gather facts vCenter extensions
description:
- This module can be used to gather facts about vCenter extension.

View file

@ -10,13 +10,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_about_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_about_info) instead.
short_description: Provides information about VMware server to which user is connecting to
description:
- This module can be used to gather information about VMware server to which user is trying to connect.

View file

@ -11,13 +11,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_category_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_category_info) instead.
short_description: Gather facts about VMware tag categories
description:
- This module can be used to gather facts about VMware tag categories.

View file

@ -0,0 +1 @@
vmware_cluster_info.py

View file

@ -0,0 +1 @@
vmware_datastore_info.py

View file

@ -10,12 +10,16 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_drs_group_info) instead.
author:
- "Karsten Kaj Jakobsen (@karstenjakobsen)"
description:

View file

@ -10,13 +10,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_drs_rule_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_drs_rule_info) instead.
short_description: Gathers facts about DRS rule on the given cluster
description:
- 'This module can be used to gather facts about DRS VM-VM and VM-HOST rules from the given cluster.'

View file

@ -11,13 +11,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_dvs_portgroup_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_dvs_portgroup_info) instead.
short_description: Gathers facts DVS portgroup configurations
description:
- This module can be used to gather facts about DVS portgroup configurations.

View file

@ -11,13 +11,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: vmware_guest_boot_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_guest_boot_info) instead.
short_description: Gather facts about boot options for the given virtual machine
description:
- Gather facts about boot options for the given virtual machine.

View file

@ -10,13 +10,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: vmware_guest_customization_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_guest_customization_info) instead.
short_description: Gather facts about VM customization specifications
description:
- This module can be used to gather facts about customization specifications.

View file

@ -11,13 +11,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: vmware_guest_disk_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_guest_disk_info) instead.
short_description: Gather facts about disks of given virtual machine
description:
- This module can be used to gather facts about disks belonging to given virtual machine.

View file

@ -0,0 +1 @@
vmware_guest_info.py

View file

@ -0,0 +1 @@
vmware_guest_snapshot_info.py

View file

@ -9,13 +9,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_capability_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_host_capability_info) instead.
short_description: Gathers facts about an ESXi host's capability information
description:
- This module can be used to gather facts about an ESXi host's capability information when ESXi hostname or Cluster name is given.

View file

@ -9,13 +9,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_config_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_host_config_info) instead.
short_description: Gathers facts about an ESXi host's advance configuration information
description:
- This module can be used to gather facts about an ESXi host's advance configuration information when ESXi hostname or Cluster name is given.

View file

@ -10,13 +10,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_dns_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_host_dns_info) instead.
short_description: Gathers facts about an ESXi host's DNS configuration information
description:
- This module can be used to gather facts about an ESXi host's DNS configuration information when ESXi hostname or Cluster name is given.

View file

@ -8,13 +8,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_feature_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_host_feature_info) instead.
short_description: Gathers facts about an ESXi host's feature capability information
description:
- This module can be used to gather facts about an ESXi host's feature capability information when ESXi hostname or Cluster name is given.

View file

@ -9,13 +9,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_firewall_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_host_firewall_info) instead.
short_description: Gathers facts about an ESXi host's firewall configuration information
description:
- This module can be used to gather facts about an ESXi host's firewall configuration information when ESXi hostname or Cluster name is given.

View file

@ -9,13 +9,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_ntp_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_host_ntp_info) instead.
short_description: Gathers facts about NTP configuration on an ESXi host
description:
- This module can be used to gather facts about NTP configurations on an ESXi host.

View file

@ -9,13 +9,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_package_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_host_package_info) instead.
short_description: Gathers facts about available packages on an ESXi host
description:
- This module can be used to gather facts about available packages and their status on an ESXi host.

View file

@ -9,13 +9,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_service_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_host_service_info) instead.
short_description: Gathers facts about an ESXi host's services
description:
- This module can be used to gather facts about an ESXi host's services.

View file

@ -10,13 +10,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_ssl_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_host_ssl_info) instead.
short_description: Gather facts of ESXi host system about SSL
description:
- This module can be used to gather facts of the SSL thumbprint information for a host.

View file

@ -10,13 +10,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_vmhba_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_host_vmhba_info) instead.
short_description: Gathers facts about vmhbas available on the given ESXi host
description:
- This module can be used to gather facts about vmhbas available on the given ESXi host.

View file

@ -11,13 +11,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_vmnic_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_host_vmnic_info) instead.
short_description: Gathers facts about vmnics available on the given ESXi host
description:
- This module can be used to gather facts about vmnics available on the given ESXi host.

View file

@ -10,7 +10,7 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
@ -18,6 +18,10 @@ ANSIBLE_METADATA = {
DOCUMENTATION = '''
---
module: vmware_local_role_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_local_role_info) instead.
short_description: Gather facts about local roles on an ESXi host
description:
- This module can be used to gather facts about local role facts on an ESXi host

View file

@ -10,7 +10,7 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
@ -18,6 +18,10 @@ ANSIBLE_METADATA = {
DOCUMENTATION = '''
---
module: vmware_local_user_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_local_user_info) instead.
short_description: Gather facts about users on the given ESXi host
description:
- This module can be used to gather facts about users present on the given ESXi host system in VMware infrastructure.

View file

@ -10,13 +10,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_portgroup_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_portgroup_info) instead.
short_description: Gathers facts about an ESXi host's Port Group configuration
description:
- This module can be used to gather facts about an ESXi host's Port Group configuration when ESXi hostname or Cluster name is given.

View file

@ -8,13 +8,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_resource_pool_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_resource_pool_info) instead.
short_description: Gathers facts about resource pool information
description:
- This module can be used to gather facts about all resource configuration information.

View file

@ -0,0 +1 @@
vmware_tag_info.py

View file

@ -9,13 +9,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: vmware_target_canonical_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_target_canonical_info) instead.
short_description: Return canonical (NAA) from an ESXi host system
description:
- This module can be used to gather facts about canonical (NAA) from an ESXi host based on SCSI target ID.

View file

@ -0,0 +1 @@
vmware_vm_info.py

View file

@ -9,13 +9,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_vmkernel_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_vmkernel_info) instead.
short_description: Gathers VMKernel facts about an ESXi host
description:
- This module can be used to gather VMKernel facts about an ESXi host from given ESXi hostname or cluster name.

View file

@ -8,13 +8,17 @@ __metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'status': ['deprecated'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_vswitch_facts
deprecated:
removed_in: '2.13'
why: Deprecated in favour of C(_info) module.
alternative: Use M(vmware_vswitch_info) instead.
short_description: Gathers facts about an ESXi host's vswitch configurations
description:
- This module can be used to gather facts about an ESXi host's vswitch configurations when ESXi hostname or Cluster name is given.

View file

@ -0,0 +1,115 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vcenter_extension_info
short_description: Gather info vCenter extensions
description:
- This module can be used to gather information about vCenter extension.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather info about vCenter Extensions
vcenter_extension_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
register: ext_info
delegate_to: localhost
'''
RETURN = r'''
extension_info:
description: List of extensions
returned: success
type: list
sample: [
{
"extension_company": "VMware, Inc.",
"extension_key": "com.vmware.vim.ls",
"extension_label": "License Services",
"extension_last_heartbeat_time": "2018-09-03T09:36:18.003768+00:00",
"extension_subject_name": "",
"extension_summary": "Provides various license services",
"extension_type": "",
"extension_version": "5.0"
},
{
"extension_company": "VMware Inc.",
"extension_key": "com.vmware.vim.sms",
"extension_label": "VMware vCenter Storage Monitoring Service",
"extension_last_heartbeat_time": "2018-09-03T09:36:18.005730+00:00",
"extension_subject_name": "",
"extension_summary": "Storage Monitoring and Reporting",
"extension_type": "",
"extension_version": "5.5"
}
]
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi
class VmwareExtManager(PyVmomi):
def __init__(self, module):
super(VmwareExtManager, self).__init__(module)
def gather_plugin_info(self):
result = dict(changed=False, extension_info=[])
ext_manager = self.content.extensionManager
if not ext_manager:
self.module.exit_json(**result)
for ext in ext_manager.extensionList:
ext_info = dict(
extension_label=ext.description.label,
extension_summary=ext.description.summary,
extension_key=ext.key,
extension_company=ext.company,
extension_version=ext.version,
extension_type=ext.type if ext.type else '',
extension_subject_name=ext.subjectName if ext.subjectName else '',
extension_last_heartbeat_time=ext.lastHeartbeatTime,
)
result['extension_info'].append(ext_info)
self.module.exit_json(**result)
def main():
argument_spec = vmware_argument_spec()
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
)
vcenter_extension_info_mgr = VmwareExtManager(module)
vcenter_extension_info_mgr.gather_plugin_info()
if __name__ == "__main__":
main()

View file

@ -0,0 +1,126 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_about_info
short_description: Provides information about VMware server to which user is connecting to
description:
- This module can be used to gather information about VMware server to which user is trying to connect.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Provide information about vCenter
vmware_about_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
delegate_to: localhost
register: vcenter_about_info
- name: Provide information about a standalone ESXi server
vmware_about_info:
hostname: '{{ esxi_hostname }}'
username: '{{ esxi_username }}'
password: '{{ esxi_password }}'
delegate_to: localhost
register: esxi_about_info
'''
RETURN = r'''
about_info:
description:
- dict about VMware server
returned: success
type: str
sample:
{
"api_type": "VirtualCenter",
"api_version": "6.5",
"build": "5973321",
"instance_uuid": "dbed6e0c-bd88-4ef6-b594-21283e1c677f",
"license_product_name": "VMware VirtualCenter Server",
"license_product_version": "6.0",
"locale_build": "000",
"locale_version": "INTL",
"os_type": "darwin-amd64",
"product_full_name": "VMware vCenter Server 6.5.0 build-5973321",
"product_line_id": "vpx",
"product_name": "VMware vCenter Server (govmomi simulator)",
"vendor": "VMware, Inc.",
"version": "6.5.0"
}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi
class VmwareAboutManager(PyVmomi):
def __init__(self, module):
super(VmwareAboutManager, self).__init__(module)
def gather_about_info(self):
if not self.content:
self.module.exit_json(changed=False, about_info=dict())
about = self.content.about
self.module.exit_json(
changed=False,
about_info=dict(
product_name=about.name,
product_full_name=about.fullName,
vendor=about.vendor,
version=about.version,
build=about.build,
locale_version=about.localeVersion,
locale_build=about.localeBuild,
os_type=about.osType,
product_line_id=about.productLineId,
api_type=about.apiType,
api_version=about.apiVersion,
instance_uuid=about.instanceUuid,
license_product_name=about.licenseProductName,
license_product_version=about.licenseProductVersion,
)
)
def main():
argument_spec = vmware_argument_spec()
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
)
vmware_about_info_mgr = VmwareAboutManager(module)
vmware_about_info_mgr.gather_about_info()
if __name__ == "__main__":
main()

View file

@ -0,0 +1,128 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_category_info
short_description: Gather info about VMware tag categories
description:
- This module can be used to gather information about VMware tag categories.
- Tag feature is introduced in vSphere 6 version, so this module is not supported in earlier versions of vSphere.
- All variables and VMware object names are case sensitive.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
- vSphere Automation SDK
extends_documentation_fragment: vmware_rest_client.documentation
'''
EXAMPLES = r'''
- name: Gather info about tag categories
vmware_category_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
delegate_to: localhost
register: all_tag_category_info
- name: Gather category id from given tag category
vmware_category_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
delegate_to: localhost
register: tag_category_results
- set_fact:
category_id: "{{ item.category_id }}"
loop: "{{ tag_category_results.tag_category_info|json_query(query) }}"
vars:
query: "[?category_name==`Category0001`]"
- debug: var=category_id
'''
RETURN = r'''
tag_category_info:
description: metadata of tag categories
returned: always
type: list
sample: [
{
"category_associable_types": [],
"category_cardinality": "MULTIPLE",
"category_description": "awesome description",
"category_id": "urn:vmomi:InventoryServiceCategory:e785088d-6981-4b1c-9fb8-1100c3e1f742:GLOBAL",
"category_name": "Category0001",
"category_used_by": []
},
{
"category_associable_types": [
"VirtualMachine"
],
"category_cardinality": "SINGLE",
"category_description": "another awesome description",
"category_id": "urn:vmomi:InventoryServiceCategory:ae5b7c6c-e622-4671-9b96-76e93adb70f2:GLOBAL",
"category_name": "template_tag",
"category_used_by": []
}
]
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware_rest_client import VmwareRestClient
class VmwareCategoryInfoManager(VmwareRestClient):
def __init__(self, module):
super(VmwareCategoryInfoManager, self).__init__(module)
self.category_service = self.api_client.tagging.Category
def get_all_tag_categories(self):
"""Retrieve all tag category information."""
global_tag_categories = []
for category in self.category_service.list():
category_obj = self.category_service.get(category)
global_tag_categories.append(
dict(
category_description=category_obj.description,
category_used_by=category_obj.used_by,
category_cardinality=str(category_obj.cardinality),
category_associable_types=category_obj.associable_types,
category_id=category_obj.id,
category_name=category_obj.name,
)
)
self.module.exit_json(changed=False, tag_category_info=global_tag_categories)
def main():
argument_spec = VmwareRestClient.vmware_client_argument_spec()
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
vmware_category_info = VmwareCategoryInfoManager(module)
vmware_category_info.get_all_tag_categories()
if __name__ == '__main__':
main()

View file

@ -15,11 +15,12 @@ ANSIBLE_METADATA = {
DOCUMENTATION = '''
---
module: vmware_cluster_facts
short_description: Gather facts about clusters available in given vCenter
module: vmware_cluster_info
short_description: Gather info about clusters available in given vCenter
description:
- This module can be used to gather facts about clusters in VMware infrastructure.
- This module can be used to gather information about clusters in VMWare infrastructure.
- All values and VMware object names are case sensitive.
- This module was called C(vmware_cluster_facts) before Ansible 2.9. The usage did not change.
version_added: '2.6'
author:
- Abhijeet Kasurde (@Akasurde)
@ -38,7 +39,7 @@ options:
cluster_name:
description:
- Name of the cluster.
- If set, facts of this cluster will be returned.
- If set, information of this cluster will be returned.
- This parameter is required, if C(datacenter) is not supplied.
required: False
type: str
@ -52,34 +53,34 @@ extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
- name: Gather cluster facts from given datacenter
vmware_cluster_facts:
- name: Gather cluster info from given datacenter
vmware_cluster_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
datacenter: ha-datacenter
validate_certs: no
delegate_to: localhost
register: cluster_facts
register: cluster_info
- name: Gather facts from datacenter about specific cluster
vmware_cluster_facts:
- name: Gather info from datacenter about specific cluster
vmware_cluster_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: DC0_C0
delegate_to: localhost
register: cluster_facts
register: cluster_info
- name: Gather facts from datacenter about specific cluster with tags
vmware_cluster_facts:
- name: Gather info from datacenter about specific cluster with tags
vmware_cluster_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: DC0_C0
show_tag: True
delegate_to: localhost
register: cluster_facts
register: cluster_info
'''
RETURN = """
@ -129,9 +130,9 @@ from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec, find_data
from ansible.module_utils.vmware_rest_client import VmwareRestClient
class VmwreClusterFactsManager(PyVmomi):
class VmwreClusterInfoManager(PyVmomi):
def __init__(self, module):
super(VmwreClusterFactsManager, self).__init__(module)
super(VmwreClusterInfoManager, self).__init__(module)
datacenter = self.params.get('datacenter')
cluster_name = self.params.get('cluster_name')
self.cluster_objs = []
@ -169,10 +170,9 @@ class VmwreClusterFactsManager(PyVmomi):
cluster_objs.append(child)
return cluster_objs
def gather_cluster_facts(self):
def gather_cluster_info(self):
"""
Gather facts about cluster
Gather information about cluster
"""
results = dict(changed=False, clusters=dict())
for cluster in self.cluster_objs:
@ -251,8 +251,11 @@ def main():
],
supports_check_mode=True,
)
pyv = VmwreClusterFactsManager(module)
pyv.gather_cluster_facts()
if module._name == 'vmware_cluster_facts':
module.deprecate("The 'vmware_cluster_facts' module has been renamed to 'vmware_cluster_info'", version='2.13')
pyv = VmwreClusterInfoManager(module)
pyv.gather_cluster_info()
if __name__ == '__main__':

View file

@ -95,12 +95,12 @@ from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware_rest_client import VmwareRestClient
class VmwareContentLibFacts(VmwareRestClient):
class VmwareContentLibInfo(VmwareRestClient):
def __init__(self, module):
"""Constructor."""
super(VmwareContentLibFacts, self).__init__(module)
super(VmwareContentLibInfo, self).__init__(module)
self.content_service = self.api_client
self.library_facts = []
self.library_info = []
def get_all_content_libs(self):
"""Method to retrieve List of content libraries."""
@ -119,7 +119,7 @@ class VmwareContentLibFacts(VmwareRestClient):
published=lib_details.publish_info.published,
user_name=lib_details.publish_info.user_name
)
self.library_facts.append(
self.library_info.append(
dict(
library_name=lib_details.name,
library_description=lib_details.description,
@ -132,7 +132,7 @@ class VmwareContentLibFacts(VmwareRestClient):
)
)
self.module.exit_json(exists=False, changed=False, content_lib_details=self.library_facts)
self.module.exit_json(exists=False, changed=False, content_lib_details=self.library_info)
def main():
@ -143,11 +143,11 @@ def main():
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True)
vmware_contentlib_facts = VmwareContentLibFacts(module)
vmware_contentlib_info = VmwareContentLibInfo(module)
if module.params.get('library_id'):
vmware_contentlib_facts.get_content_lib_details(module.params['library_id'])
vmware_contentlib_info.get_content_lib_details(module.params['library_id'])
else:
vmware_contentlib_facts.get_all_content_libs()
vmware_contentlib_info.get_all_content_libs()
if __name__ == '__main__':

View file

@ -16,11 +16,12 @@ ANSIBLE_METADATA = {
DOCUMENTATION = '''
---
module: vmware_datastore_facts
short_description: Gather facts about datastores available in given vCenter
module: vmware_datastore_info
short_description: Gather info about datastores available in given vCenter
description:
- This module can be used to gather facts about datastores in VMware infrastructure.
- This module can be used to gather information about datastores in VMWare infrastructure.
- All values and VMware object names are case sensitive.
- This module was called C(vmware_datastore_facts) before Ansible 2.9. The usage did not change.
version_added: 2.5
author:
- Tim Rightnour (@garbled1)
@ -33,7 +34,7 @@ options:
name:
description:
- Name of the datastore to match.
- If set, facts of specific datastores are returned.
- If set, information of specific datastores are returned.
required: False
type: str
datacenter:
@ -46,7 +47,7 @@ options:
cluster:
description:
- Cluster to search for datastores.
- If set, facts of datastores belonging this clusters will be returned.
- If set, information of datastores belonging this clusters will be returned.
- This parameter is required, if C(datacenter) is not supplied.
required: False
type: str
@ -68,25 +69,25 @@ extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
- name: Gather facts from standalone ESXi server having datacenter as 'ha-datacenter'
vmware_datastore_facts:
- name: Gather info from standalone ESXi server having datacenter as 'ha-datacenter'
vmware_datastore_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
datacenter_name: '{{ datacenter_name }}'
validate_certs: no
delegate_to: localhost
register: facts
register: info
- name: Gather facts from datacenter about specific datastore
vmware_datastore_facts:
- name: Gather info from datacenter about specific datastore
vmware_datastore_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
datacenter_name: '{{ datacenter_name }}'
name: datastore1
delegate_to: localhost
register: facts
register: info
'''
RETURN = """
@ -261,6 +262,9 @@ def main():
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True
)
if module._name == 'vmware_datastore_facts':
module.deprecate("The 'vmware_datastore_facts' module has been renamed to 'vmware_datastore_info'", version='2.13')
result = dict(changed=False)
pyv = PyVmomiHelper(module)

View file

@ -0,0 +1,282 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Karsten Kaj Jakobsen <kj@patientsky.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
author:
- "Karsten Kaj Jakobsen (@karstenjakobsen)"
description:
- "This module can be used to gather information about DRS VM/HOST groups from the given cluster."
extends_documentation_fragment: vmware.documentation
module: vmware_drs_group_info
notes:
- "Tested on vSphere 6.5 and 6.7"
options:
cluster_name:
description:
- "Cluster to search for VM/Host groups."
- "If set, information of DRS groups belonging this cluster will be returned."
- "Not needed if C(datacenter) is set."
required: false
type: str
datacenter:
aliases:
- datacenter_name
description:
- "Datacenter to search for DRS VM/Host groups."
required: true
type: str
requirements:
- "python >= 2.6"
- PyVmomi
short_description: "Gathers info about DRS VM/Host groups on the given cluster"
version_added: "2.9"
'''
EXAMPLES = r'''
---
- name: "Gather DRS info about given Cluster"
register: cluster_drs_group_info
vmware_drs_group_info:
hostname: "{{ vcenter_hostname }}"
password: "{{ vcenter_password }}"
username: "{{ vcenter_username }}"
cluster_name: "{{ cluster_name }}"
datacenter: "{{ datacenter }}"
delegate_to: localhost
- name: "Gather DRS group info about all clusters in given datacenter"
register: cluster_drs_group_info
vmware_drs_group_info:
hostname: "{{ vcenter_hostname }}"
password: "{{ vcenter_password }}"
username: "{{ vcenter_username }}"
datacenter: "{{ datacenter }}"
delegate_to: localhost
'''
RETURN = r'''
drs_group_info:
description: Metadata about DRS group from given cluster / datacenter
returned: always
type: dict
sample:
"drs_group_info": {
"DC0_C0": [
{
"group_name": "GROUP_HOST_S01",
"hosts": [
"vm-01.zone",
"vm-02.zone"
],
"type": "host"
},
{
"group_name": "GROUP_HOST_S02",
"hosts": [
"vm-03.zone",
"vm-04.zone"
],
"type": "host"
},
{
"group_name": "GROUP_VM_S01",
"type": "vm",
"vms": [
"test-node01"
]
},
{
"group_name": "GROUP_VM_S02",
"type": "vm",
"vms": [
"test-node02"
]
}
],
"DC0_C1": []
}
'''
try:
from pyVmomi import vim
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi, find_datacenter_by_name, get_all_objs
class VmwareDrsGroupInfoManager(PyVmomi):
def __init__(self, module, datacenter_name, cluster_name=None):
"""
Doctring: Init
"""
super(VmwareDrsGroupInfoManager, self).__init__(module)
self.__datacenter_name = datacenter_name
self.__datacenter_obj = None
self.__cluster_name = cluster_name
self.__cluster_obj = None
self.__msg = 'Nothing to see here...'
self.__result = dict()
self.__changed = False
if datacenter_name:
datacenter_obj = find_datacenter_by_name(self.content, datacenter_name=datacenter_name)
self.cluster_obj_list = []
if datacenter_obj:
folder = datacenter_obj.hostFolder
self.cluster_obj_list = get_all_objs(self.content, [vim.ClusterComputeResource], folder)
else:
raise Exception("Datacenter '%s' not found" % self.__datacenter_name)
if cluster_name:
cluster_obj = self.find_cluster_by_name(cluster_name=self.__cluster_name)
if cluster_obj is None:
raise Exception("Cluster '%s' not found" % self.__cluster_name)
else:
self.cluster_obj_list = [cluster_obj]
def get_result(self):
"""
Docstring
"""
return self.__result
def __set_result(self, result):
"""
Sets result
Args:
result: drs group result list
Returns: None
"""
self.__result = result
def __get_all_from_group(self, group_obj, host_group=False):
"""
Return all VM / Host names using given group
Args:
group_obj: Group object
host_group: True if we want only host name from group
Returns: List of VM / Host names belonging to given group object
"""
obj_name_list = []
if not all([group_obj]):
return obj_name_list
if not host_group and isinstance(group_obj, vim.cluster.VmGroup):
obj_name_list = [vm.name for vm in group_obj.vm]
elif host_group and isinstance(group_obj, vim.cluster.HostGroup):
obj_name_list = [host.name for host in group_obj.host]
return obj_name_list
def __normalize_group_data(self, group_obj):
"""
Return human readable group spec
Args:
group_obj: Group object
Returns: Dictionary with DRS groups
"""
if not all([group_obj]):
return {}
# Check if group is a host group
if hasattr(group_obj, 'host'):
return dict(
group_name=group_obj.name,
hosts=self.__get_all_from_group(group_obj=group_obj, host_group=True),
type="host"
)
else:
return dict(
group_name=group_obj.name,
vms=self.__get_all_from_group(group_obj=group_obj),
type="vm"
)
def gather_info(self):
"""
Gather DRS group information about given cluster
Returns: Dictionary of clusters with DRS groups
"""
cluster_group_info = dict()
for cluster_obj in self.cluster_obj_list:
cluster_group_info[cluster_obj.name] = []
for drs_group in cluster_obj.configurationEx.group:
cluster_group_info[cluster_obj.name].append(self.__normalize_group_data(drs_group))
self.__set_result(cluster_group_info)
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
datacenter=dict(type='str', required=False, aliases=['datacenter_name']),
cluster_name=dict(type='str', required=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
required_one_of=[['cluster_name', 'datacenter']],
mutually_exclusive=[['cluster_name', 'datacenter']],
)
try:
# Create instance of VmwareDrsGroupManager
vmware_drs_group_info = VmwareDrsGroupInfoManager(
module=module,
datacenter_name=module.params.get('datacenter'),
cluster_name=module.params.get('cluster_name', None))
vmware_drs_group_info.gather_info()
# Set results
results = dict(failed=False,
drs_group_info=vmware_drs_group_info.get_result())
except Exception as error:
results = dict(failed=True, msg="Error: %s" % error)
if results['failed']:
module.fail_json(**results)
else:
module.exit_json(**results)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,262 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_drs_rule_info
short_description: Gathers info about DRS rule on the given cluster
description:
- 'This module can be used to gather information about DRS VM-VM and VM-HOST rules from the given cluster.'
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
options:
cluster_name:
description:
- Name of the cluster.
- DRS information for the given cluster will be returned.
- This is required parameter if C(datacenter) parameter is not provided.
type: str
datacenter:
description:
- Name of the datacenter.
- DRS information for all the clusters from the given datacenter will be returned.
- This is required parameter if C(cluster_name) parameter is not provided.
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather DRS info about given Cluster
vmware_drs_rule_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: '{{ cluster_name }}'
delegate_to: localhost
register: cluster_drs_info
- name: Gather DRS info about all Clusters in given datacenter
vmware_drs_rule_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
datacenter: '{{ datacenter_name }}'
delegate_to: localhost
register: datacenter_drs_info
'''
RETURN = r'''
drs_rule_info:
description: metadata about DRS rule from given cluster / datacenter
returned: always
type: dict
sample: {
"DC0_C0": [
{
"rule_affinity": false,
"rule_enabled": true,
"rule_key": 1,
"rule_mandatory": true,
"rule_name": "drs_rule_0001",
"rule_type": "vm_vm_rule",
"rule_uuid": "52be5061-665a-68dc-3d25-85cd2d37e114",
"rule_vms": [
"VM_65",
"VM_146"
]
},
],
"DC1_C1": [
{
"rule_affine_host_group_name": "host_group_1",
"rule_affine_hosts": [
"10.76.33.204"
],
"rule_anti_affine_host_group_name": null,
"rule_anti_affine_hosts": [],
"rule_enabled": true,
"rule_key": 1,
"rule_mandatory": false,
"rule_name": "vm_host_rule_0001",
"rule_type": "vm_host_rule",
"rule_uuid": "52687108-4d3a-76f2-d29c-b708c40dbe40",
"rule_vm_group_name": "test_vm_group_1",
"rule_vms": [
"VM_8916",
"VM_4010"
]
}
],
}
'''
try:
from pyVmomi import vim
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi, find_datacenter_by_name, get_all_objs
class VmwareDrsInfoManager(PyVmomi):
def __init__(self, module):
super(VmwareDrsInfoManager, self).__init__(module)
datacenter_name = self.params.get('datacenter', None)
if datacenter_name:
datacenter_obj = find_datacenter_by_name(self.content, datacenter_name=datacenter_name)
self.cluster_obj_list = []
if datacenter_obj:
folder = datacenter_obj.hostFolder
self.cluster_obj_list = get_all_objs(self.content, [vim.ClusterComputeResource], folder)
else:
self.module.fail_json(changed=False, msg="Datacenter '%s' not found" % datacenter_name)
cluster_name = self.params.get('cluster_name', None)
if cluster_name:
cluster_obj = self.find_cluster_by_name(cluster_name=cluster_name)
if cluster_obj is None:
self.module.fail_json(changed=False, msg="Cluster '%s' not found" % cluster_name)
else:
self.cluster_obj_list = [cluster_obj]
def get_all_from_group(self, group_name=None, cluster_obj=None, hostgroup=False):
"""
Return all VM / Host names using given group name
Args:
group_name: Rule name
cluster_obj: Cluster managed object
hostgroup: True if we want only host name from group
Returns: List of VM / Host names belonging to given group object
"""
obj_name_list = []
if not all([group_name, cluster_obj]):
return obj_name_list
for group in cluster_obj.configurationEx.group:
if group.name == group_name:
if not hostgroup and isinstance(group, vim.cluster.VmGroup):
obj_name_list = [vm.name for vm in group.vm]
break
elif hostgroup and isinstance(group, vim.cluster.HostGroup):
obj_name_list = [host.name for host in group.host]
break
return obj_name_list
@staticmethod
def normalize_vm_vm_rule_spec(rule_obj=None):
"""
Return human readable rule spec
Args:
rule_obj: Rule managed object
Returns: Dictionary with DRS VM VM Rule info
"""
if rule_obj is None:
return {}
return dict(rule_key=rule_obj.key,
rule_enabled=rule_obj.enabled,
rule_name=rule_obj.name,
rule_mandatory=rule_obj.mandatory,
rule_uuid=rule_obj.ruleUuid,
rule_vms=[vm.name for vm in rule_obj.vm],
rule_type="vm_vm_rule",
rule_affinity=True if isinstance(rule_obj, vim.cluster.AffinityRuleSpec) else False,
)
def normalize_vm_host_rule_spec(self, rule_obj=None, cluster_obj=None):
"""
Return human readable rule spec
Args:
rule_obj: Rule managed object
cluster_obj: Cluster managed object
Returns: Dictionary with DRS VM HOST Rule info
"""
if not all([rule_obj, cluster_obj]):
return {}
return dict(rule_key=rule_obj.key,
rule_enabled=rule_obj.enabled,
rule_name=rule_obj.name,
rule_mandatory=rule_obj.mandatory,
rule_uuid=rule_obj.ruleUuid,
rule_vm_group_name=rule_obj.vmGroupName,
rule_affine_host_group_name=rule_obj.affineHostGroupName,
rule_anti_affine_host_group_name=rule_obj.antiAffineHostGroupName,
rule_vms=self.get_all_from_group(group_name=rule_obj.vmGroupName,
cluster_obj=cluster_obj),
rule_affine_hosts=self.get_all_from_group(group_name=rule_obj.affineHostGroupName,
cluster_obj=cluster_obj,
hostgroup=True),
rule_anti_affine_hosts=self.get_all_from_group(group_name=rule_obj.antiAffineHostGroupName,
cluster_obj=cluster_obj,
hostgroup=True),
rule_type="vm_host_rule",
)
def gather_drs_rule_info(self):
"""
Gather DRS rule information about given cluster
Returns: Dictionary of clusters with DRS information
"""
cluster_rule_info = dict()
for cluster_obj in self.cluster_obj_list:
cluster_rule_info[cluster_obj.name] = []
for drs_rule in cluster_obj.configuration.rule:
if isinstance(drs_rule, vim.cluster.VmHostRuleInfo):
cluster_rule_info[cluster_obj.name].append(self.normalize_vm_host_rule_spec(
rule_obj=drs_rule,
cluster_obj=cluster_obj))
else:
cluster_rule_info[cluster_obj.name].append(self.normalize_vm_vm_rule_spec(rule_obj=drs_rule))
return cluster_rule_info
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
datacenter=dict(type='str', required=False),
cluster_name=dict(type='str', required=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'datacenter'],
],
supports_check_mode=True,
)
vmware_drs_info = VmwareDrsInfoManager(module)
module.exit_json(changed=False, drs_rule_info=vmware_drs_info.gather_drs_rule_info())
if __name__ == "__main__":
main()

View file

@ -0,0 +1,275 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_dvs_portgroup_info
short_description: Gathers info DVS portgroup configurations
description:
- This module can be used to gather information about DVS portgroup configurations.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
options:
datacenter:
description:
- Name of the datacenter.
required: true
type: str
dvswitch:
description:
- Name of a dvswitch to look for.
required: false
type: str
version_added: "2.9"
show_network_policy:
description:
- Show or hide network policies of DVS portgroup.
type: bool
default: True
show_port_policy:
description:
- Show or hide port policies of DVS portgroup.
type: bool
default: True
show_teaming_policy:
description:
- Show or hide teaming policies of DVS portgroup.
type: bool
default: True
show_vlan_info:
description:
- Show or hide vlan information of the DVS portgroup.
type: bool
default: False
version_added: "2.9"
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Get info about DVPG
vmware_dvs_portgroup_info:
hostname: "{{ vcenter_server }}"
username: "{{ vcenter_user }}"
password: "{{ vcenter_pass }}"
validate_certs: no
datacenter: "{{ datacenter_name }}"
register: dvpg_info
- name: Get number of ports for portgroup 'dvpg_001' in 'dvs_001'
debug:
msg: "{{ item.num_ports }}"
with_items:
- "{{ dvpg_info.dvs_portgroup_info['dvs_001'] | json_query(query) }}"
vars:
query: "[?portgroup_name=='dvpg_001']"
'''
RETURN = r'''
dvs_portgroup_info:
description: metadata about DVS portgroup configuration
returned: on success
type: dict
sample: {
"dvs_0":[
{
"description": null,
"dvswitch_name": "dvs_001",
"network_policy": {
"forged_transmits": false,
"mac_changes": false,
"promiscuous": false
},
"num_ports": 8,
"port_policy": {
"block_override": true,
"ipfix_override": false,
"live_port_move": false,
"network_rp_override": false,
"port_config_reset_at_disconnect": true,
"security_override": false,
"shaping_override": false,
"traffic_filter_override": false,
"uplink_teaming_override": false,
"vendor_config_override": false,
"vlan_override": false
},
"portgroup_name": "dvpg_001",
"teaming_policy": {
"inbound_policy": true,
"notify_switches": true,
"policy": "loadbalance_srcid",
"rolling_order": false
},
"vlan_info": {
"trunk": false,
"pvlan": false,
"vlan_id": 0
},
"type": "earlyBinding"
},
]
}
'''
try:
from pyVmomi import vim
except ImportError as e:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi, get_all_objs, find_dvs_by_name
class DVSPortgroupInfoManager(PyVmomi):
def __init__(self, module):
super(DVSPortgroupInfoManager, self).__init__(module)
self.dc_name = self.params['datacenter']
self.dvs_name = self.params['dvswitch']
datacenter = self.find_datacenter_by_name(self.dc_name)
if datacenter is None:
self.module.fail_json(msg="Failed to find the datacenter %s" % self.dc_name)
if self.dvs_name:
# User specified specific dvswitch name to gather information
dvsn = find_dvs_by_name(self.content, self.dvs_name)
if dvsn is None:
self.module.fail_json(msg="Failed to find the dvswitch %s" % self.dvs_name)
self.dvsls = [dvsn]
else:
# default behaviour, gather information about all dvswitches
self.dvsls = get_all_objs(self.content, [vim.DistributedVirtualSwitch], folder=datacenter.networkFolder)
def get_vlan_info(self, vlan_obj=None):
"""
Return vlan information from given object
Args:
vlan_obj: vlan managed object
Returns: Dict of vlan details of the specific object
"""
vdret = dict()
if not vlan_obj:
return vdret
if isinstance(vlan_obj, vim.dvs.VmwareDistributedVirtualSwitch.TrunkVlanSpec):
vlan_id_list = []
for vli in vlan_obj.vlanId:
if vli.start == vli.end:
vlan_id_list.append(str(vli.start))
else:
vlan_id_list.append(str(vli.start) + "-" + str(vli.end))
vdret = dict(trunk=True, pvlan=False, vlan_id=vlan_id_list)
elif isinstance(vlan_obj, vim.dvs.VmwareDistributedVirtualSwitch.PvlanSpec):
vdret = dict(trunk=False, pvlan=True, vlan_id=str(vlan_obj.pvlanId))
else:
vdret = dict(trunk=False, pvlan=False, vlan_id=str(vlan_obj.vlanId))
return vdret
def gather_dvs_portgroup_info(self):
dvs_lists = self.dvsls
result = dict()
for dvs in dvs_lists:
result[dvs.name] = list()
for dvs_pg in dvs.portgroup:
network_policy = dict()
teaming_policy = dict()
port_policy = dict()
vlan_info = dict()
if self.module.params['show_network_policy'] and dvs_pg.config.defaultPortConfig.securityPolicy:
network_policy = dict(
forged_transmits=dvs_pg.config.defaultPortConfig.securityPolicy.forgedTransmits.value,
promiscuous=dvs_pg.config.defaultPortConfig.securityPolicy.allowPromiscuous.value,
mac_changes=dvs_pg.config.defaultPortConfig.securityPolicy.macChanges.value
)
if self.module.params['show_teaming_policy']:
# govcsim does not have uplinkTeamingPolicy, remove this check once
# PR https://github.com/vmware/govmomi/pull/1524 merged.
if dvs_pg.config.defaultPortConfig.uplinkTeamingPolicy:
teaming_policy = dict(
policy=dvs_pg.config.defaultPortConfig.uplinkTeamingPolicy.policy.value,
inbound_policy=dvs_pg.config.defaultPortConfig.uplinkTeamingPolicy.reversePolicy.value,
notify_switches=dvs_pg.config.defaultPortConfig.uplinkTeamingPolicy.notifySwitches.value,
rolling_order=dvs_pg.config.defaultPortConfig.uplinkTeamingPolicy.rollingOrder.value,
)
if self.params['show_port_policy']:
# govcsim does not have port policy
if dvs_pg.config.policy:
port_policy = dict(
block_override=dvs_pg.config.policy.blockOverrideAllowed,
ipfix_override=dvs_pg.config.policy.ipfixOverrideAllowed,
live_port_move=dvs_pg.config.policy.livePortMovingAllowed,
network_rp_override=dvs_pg.config.policy.networkResourcePoolOverrideAllowed,
port_config_reset_at_disconnect=dvs_pg.config.policy.portConfigResetAtDisconnect,
security_override=dvs_pg.config.policy.securityPolicyOverrideAllowed,
shaping_override=dvs_pg.config.policy.shapingOverrideAllowed,
traffic_filter_override=dvs_pg.config.policy.trafficFilterOverrideAllowed,
uplink_teaming_override=dvs_pg.config.policy.uplinkTeamingOverrideAllowed,
vendor_config_override=dvs_pg.config.policy.vendorConfigOverrideAllowed,
vlan_override=dvs_pg.config.policy.vlanOverrideAllowed
)
if self.params['show_vlan_info']:
vlan_info = self.get_vlan_info(dvs_pg.config.defaultPortConfig.vlan)
dvpg_details = dict(
portgroup_name=dvs_pg.name,
num_ports=dvs_pg.config.numPorts,
dvswitch_name=dvs_pg.config.distributedVirtualSwitch.name,
description=dvs_pg.config.description,
type=dvs_pg.config.type,
teaming_policy=teaming_policy,
port_policy=port_policy,
network_policy=network_policy,
vlan_info=vlan_info,
)
result[dvs.name].append(dvpg_details)
return result
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
datacenter=dict(type='str', required=True),
show_network_policy=dict(type='bool', default=True),
show_teaming_policy=dict(type='bool', default=True),
show_port_policy=dict(type='bool', default=True),
dvswitch=dict(),
show_vlan_info=dict(type='bool', default=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
)
dvs_pg_mgr = DVSPortgroupInfoManager(module)
module.exit_json(changed=False,
dvs_portgroup_info=dvs_pg_mgr.gather_dvs_portgroup_info())
if __name__ == "__main__":
main()

View file

@ -0,0 +1,214 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: vmware_guest_boot_info
short_description: Gather info about boot options for the given virtual machine
description:
- Gather information about boot options for the given virtual machine.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- "python >= 2.6"
- PyVmomi
options:
name:
description:
- Name of the VM to work with.
- This is required if C(uuid) or C(moid) parameter is not supplied.
type: str
uuid:
description:
- UUID of the instance to manage if known, this is VMware's BIOS UUID by default.
- This is required if C(name) or C(moid) parameter is not supplied.
type: str
moid:
description:
- Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance.
- This is required if C(name) or C(uuid) is not supplied.
type: str
use_instance_uuid:
description:
- Whether to use the VMware instance UUID rather than the BIOS UUID.
default: no
type: bool
name_match:
description:
- If multiple virtual machines matching the name, use the first or last found.
default: 'first'
choices: ['first', 'last']
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather info about virtual machine's boot order and related parameters
vmware_guest_boot_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
name: "{{ vm_name }}"
register: vm_boot_order_info
- name: Gather information about virtual machine's boot order using MoID
vmware_guest_boot_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
moid: "vm-42"
register: vm_moid_boot_order_info
'''
RETURN = r"""
vm_boot_info:
description: metadata about boot order of virtual machine
returned: always
type: dict
sample: {
"current_boot_order": [
"floppy",
"disk",
"ethernet",
"cdrom"
],
"current_boot_delay": 2000,
"current_boot_retry_delay": 22300,
"current_boot_retry_enabled": true,
"current_enter_bios_setup": true,
"current_boot_firmware": "bios",
"current_secure_boot_enabled": false,
}
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec, find_vm_by_id
try:
from pyVmomi import vim, VmomiSupport
except ImportError:
pass
class VmBootInfoManager(PyVmomi):
def __init__(self, module):
super(VmBootInfoManager, self).__init__(module)
self.name = self.params['name']
self.uuid = self.params['uuid']
self.moid = self.params['moid']
self.use_instance_uuid = self.params['use_instance_uuid']
self.vm = None
def _get_vm(self):
vms = []
if self.uuid:
if self.use_instance_uuid:
vm_obj = find_vm_by_id(self.content, vm_id=self.uuid, vm_id_type="use_instance_uuid")
else:
vm_obj = find_vm_by_id(self.content, vm_id=self.uuid, vm_id_type="uuid")
if vm_obj is None:
self.module.fail_json(msg="Failed to find the virtual machine with UUID : %s" % self.uuid)
vms = [vm_obj]
elif self.name:
objects = self.get_managed_objects_properties(vim_type=vim.VirtualMachine, properties=['name'])
for temp_vm_object in objects:
if temp_vm_object.obj.name == self.name:
vms.append(temp_vm_object.obj)
elif self.moid:
vm_obj = VmomiSupport.templateOf('VirtualMachine')(self.module.params['moid'], self.si._stub)
if vm_obj:
vms.append(vm_obj)
if vms:
if self.params.get('name_match') == 'first':
self.vm = vms[0]
elif self.params.get('name_match') == 'last':
self.vm = vms[-1]
else:
self.module.fail_json(msg="Failed to find virtual machine using %s" % (self.name or self.uuid or self.moid))
@staticmethod
def humanize_boot_order(boot_order):
results = []
for device in boot_order:
if isinstance(device, vim.vm.BootOptions.BootableCdromDevice):
results.append('cdrom')
elif isinstance(device, vim.vm.BootOptions.BootableDiskDevice):
results.append('disk')
elif isinstance(device, vim.vm.BootOptions.BootableEthernetDevice):
results.append('ethernet')
elif isinstance(device, vim.vm.BootOptions.BootableFloppyDevice):
results.append('floppy')
return results
def ensure(self):
self._get_vm()
results = dict()
if self.vm and self.vm.config:
results = dict(
current_boot_order=self.humanize_boot_order(self.vm.config.bootOptions.bootOrder),
current_boot_delay=self.vm.config.bootOptions.bootDelay,
current_enter_bios_setup=self.vm.config.bootOptions.enterBIOSSetup,
current_boot_retry_enabled=self.vm.config.bootOptions.bootRetryEnabled,
current_boot_retry_delay=self.vm.config.bootOptions.bootRetryDelay,
current_boot_firmware=self.vm.config.firmware,
current_secure_boot_enabled=self.vm.config.bootOptions.efiSecureBootEnabled
)
self.module.exit_json(changed=False, vm_boot_info=results)
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
name=dict(type='str'),
uuid=dict(type='str'),
moid=dict(type='str'),
use_instance_uuid=dict(type='bool', default=False),
name_match=dict(
choices=['first', 'last'],
default='first'
),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['name', 'uuid', 'moid']
],
mutually_exclusive=[
['name', 'uuid', 'moid']
],
supports_check_mode=True,
)
pyv = VmBootInfoManager(module)
pyv.ensure()
if __name__ == '__main__':
main()

View file

@ -0,0 +1,193 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: vmware_guest_customization_info
short_description: Gather info about VM customization specifications
description:
- This module can be used to gather information about customization specifications.
- All parameters and VMware object names are case sensitive.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.0 and 6.5
requirements:
- "python >= 2.6"
- PyVmomi
options:
spec_name:
description:
- Name of customization specification to find.
required: False
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
- name: Gather info about all customization specification
vmware_guest_customization_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
delegate_to: localhost
register: all_custom_spec_info
- name: Gather info about customization specification with the given name
vmware_guest_customization_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
spec_name: custom_linux_spec
delegate_to: localhost
register: custom_spec_info
'''
RETURN = """
custom_spec_info:
description: metadata about the customization specification
returned: always
type: dict
sample: {
"assignip-eee0d684-44b7-457c-8c55-2585590b0d99": {
"change_version": "1523438001",
"description": "sample description",
"dns_server_list": [],
"dns_suffix_list": [],
"domain": "None",
"hostname": "sample1",
"hw_clock_utc": null,
"last_updated_time": "2018-04-11T09:13:21+00:00",
"name": "sample",
"nic_setting_map": [
{
"dns_domain": null,
"gateway": [],
"ip_address": "192.168.10.10",
"net_bios": null,
"nic_dns_server_list": [],
"primary_wins": null,
"secondry_wins": null,
"subnet_mask": "255.255.255.0"
}
],
"time_zone": null,
"type": "Linux"
},
}
"""
try:
from pyVmomi import vim
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_text
from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec
class VmwareCustomSpecManger(PyVmomi):
def __init__(self, module):
super(VmwareCustomSpecManger, self).__init__(module)
self.cc_mgr = self.content.customizationSpecManager
if self.cc_mgr is None:
self.module.fail_json(msg="Failed to get customization spec manager.")
def gather_custom_spec_info(self):
"""
Gather information about customization specifications
"""
spec_name = self.params.get('spec_name', None)
specs_list = []
if spec_name:
if self.cc_mgr.DoesCustomizationSpecExist(name=spec_name):
specs_list.append(spec_name)
else:
self.module.fail_json(msg="Unable to find customization specification named '%s'" % spec_name)
else:
available_specs = self.cc_mgr.info
for spec_info in available_specs:
specs_list.append(spec_info.name)
spec_info = dict()
for spec in specs_list:
current_spec = self.cc_mgr.GetCustomizationSpec(name=spec)
adapter_mapping_list = []
for nic in current_spec.spec.nicSettingMap:
temp_data = dict(
mac_address=nic.macAddress,
ip_address=nic.adapter.ip.ipAddress,
subnet_mask=nic.adapter.subnetMask,
gateway=[gw for gw in nic.adapter.gateway],
nic_dns_server_list=[ndsl for ndsl in nic.adapter.dnsServerList],
dns_domain=nic.adapter.dnsDomain,
primary_wins=nic.adapter.primaryWINS,
secondry_wins=nic.adapter.secondaryWINS,
net_bios=nic.adapter.netBIOS,
)
adapter_mapping_list.append(temp_data)
current_hostname = None
if isinstance(current_spec.spec.identity.hostName, vim.vm.customization.PrefixNameGenerator):
current_hostname = current_spec.spec.identity.hostName.base
elif isinstance(current_spec.spec.identity.hostName, vim.vm.customization.FixedName):
current_hostname = current_spec.spec.identity.hostName.name
spec_info[spec] = dict(
# Spec
name=current_spec.info.name,
description=current_spec.info.description,
type=current_spec.info.type,
last_updated_time=current_spec.info.lastUpdateTime,
change_version=current_spec.info.changeVersion,
# Identity
hostname=current_hostname,
domain=current_spec.spec.identity.domain,
time_zone=current_spec.spec.identity.timeZone,
hw_clock_utc=current_spec.spec.identity.hwClockUTC,
# global IP Settings
dns_suffix_list=[i for i in current_spec.spec.globalIPSettings.dnsSuffixList],
dns_server_list=[i for i in current_spec.spec.globalIPSettings.dnsServerList],
# NIC setting map
nic_setting_map=adapter_mapping_list,
)
return spec_info
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
spec_name=dict(type='str'),
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True
)
pyv = VmwareCustomSpecManger(module)
try:
module.exit_json(custom_spec_info=pyv.gather_custom_spec_info())
except Exception as exc:
module.fail_json(msg="Failed to gather information with exception : %s" % to_text(exc))
if __name__ == '__main__':
main()

View file

@ -0,0 +1,326 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, NAER William Leemans (@bushvin) <willie@elaba.net>
# Copyright: (c) 2018, Ansible Project
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: vmware_guest_disk_info
short_description: Gather info about disks of given virtual machine
description:
- This module can be used to gather information about disks belonging to given virtual machine.
- All parameters and VMware object names are case sensitive.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde) <akasurde@redhat.com>
notes:
- Tested on vSphere 6.0 and 6.5.
- Disk UUID information is added in version 2.8.
- Additional information about guest disk backings added in version 2.8.
requirements:
- "python >= 2.6"
- PyVmomi
options:
name:
description:
- Name of the virtual machine.
- This is required parameter, if parameter C(uuid) or C(moid) is not supplied.
type: str
uuid:
description:
- UUID of the instance to gather information if known, this is VMware's unique identifier.
- This is required parameter, if parameter C(name) or C(moid) is not supplied.
type: str
moid:
description:
- Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance.
- This is required if C(name) or C(uuid) is not supplied.
type: str
use_instance_uuid:
description:
- Whether to use the VMware instance UUID rather than the BIOS UUID.
default: no
type: bool
folder:
description:
- Destination folder, absolute or relative path to find an existing guest.
- This is required parameter, only if multiple VMs are found with same name.
- The folder should include the datacenter. ESX's datacenter is ha-datacenter
- 'Examples:'
- ' folder: /ha-datacenter/vm'
- ' folder: ha-datacenter/vm'
- ' folder: /datacenter1/vm'
- ' folder: datacenter1/vm'
- ' folder: /datacenter1/vm/folder1'
- ' folder: datacenter1/vm/folder1'
- ' folder: /folder1/datacenter1/vm'
- ' folder: folder1/datacenter1/vm'
- ' folder: /folder1/datacenter1/vm/folder2'
type: str
datacenter:
description:
- The datacenter name to which virtual machine belongs to.
required: True
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
- name: Gather disk info from virtual machine using UUID
vmware_guest_disk_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: ha-datacenter
validate_certs: no
uuid: 421e4592-c069-924d-ce20-7e7533fab926
delegate_to: localhost
register: disk_info
- name: Gather disk info from virtual machine using name
vmware_guest_disk_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: ha-datacenter
validate_certs: no
name: VM_225
delegate_to: localhost
register: disk_info
- name: Gather disk info from virtual machine using moid
vmware_guest_disk_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: ha-datacenter
validate_certs: no
moid: vm-42
delegate_to: localhost
register: disk_info
'''
RETURN = """
guest_disk_info:
description: metadata about the virtual machine's disks
returned: always
type: dict
sample: {
"0": {
"backing_datastore": "datastore2",
"backing_disk_mode": "persistent",
"backing_eagerlyscrub": false,
"backing_filename": "[datastore2] VM_225/VM_225.vmdk",
"backing_thinprovisioned": false,
"backing_type": "FlatVer2",
"backing_writethrough": false,
"backing_uuid": "200C3A00-f82a-97af-02ff-62a595f0020a",
"capacity_in_bytes": 10485760,
"capacity_in_kb": 10240,
"controller_bus_number": 0,
"controller_key": 1000,
"controller_type": "paravirtual",
"key": 2000,
"label": "Hard disk 1",
"summary": "10,240 KB",
"unit_number": 0
},
"1": {
"backing_datastore": "datastore3",
"backing_devicename": "vml.012345678901234567890123456789012345678901234567890123",
"backing_disk_mode": "independent_persistent",
"backing_filename": "[datastore3] VM_226/VM_226.vmdk",
"backing_lunuuid": "012345678901234567890123456789012345678901234567890123",
"backing_type": "RawDiskMappingVer1",
"backing_uuid": null,
"capacity_in_bytes": 15728640,
"capacity_in_kb": 15360,
"controller_bus_number": 0,
"controller_key": 1000,
"controller_type": "paravirtual",
"key": 2001,
"label": "Hard disk 3",
"summary": "15,360 KB",
"unit_number": 1
},
}
"""
try:
from pyVmomi import vim
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_text
from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec
class PyVmomiHelper(PyVmomi):
def __init__(self, module):
super(PyVmomiHelper, self).__init__(module)
def gather_disk_info(self, vm_obj):
"""
Gather information about VM's disks
Args:
vm_obj: Managed object of virtual machine
Returns: A list of dict containing disks information
"""
controller_info = dict()
disks_info = dict()
if vm_obj is None:
return disks_info
controller_types = {
vim.vm.device.VirtualLsiLogicController: 'lsilogic',
vim.vm.device.ParaVirtualSCSIController: 'paravirtual',
vim.vm.device.VirtualBusLogicController: 'buslogic',
vim.vm.device.VirtualLsiLogicSASController: 'lsilogicsas',
vim.vm.device.VirtualIDEController: 'ide'
}
controller_index = 0
for controller in vm_obj.config.hardware.device:
if isinstance(controller, tuple(controller_types.keys())):
controller_info[controller_index] = dict(
key=controller.key,
controller_type=controller_types[type(controller)],
bus_number=controller.busNumber,
devices=controller.device
)
controller_index += 1
disk_index = 0
for disk in vm_obj.config.hardware.device:
if isinstance(disk, vim.vm.device.VirtualDisk):
disks_info[disk_index] = dict(
key=disk.key,
label=disk.deviceInfo.label,
summary=disk.deviceInfo.summary,
backing_filename=disk.backing.fileName,
backing_datastore=disk.backing.datastore.name,
controller_key=disk.controllerKey,
unit_number=disk.unitNumber,
capacity_in_kb=disk.capacityInKB,
capacity_in_bytes=disk.capacityInBytes,
)
if isinstance(disk.backing, vim.vm.device.VirtualDisk.FlatVer1BackingInfo):
disks_info[disk_index]['backing_type'] = 'FlatVer1'
disks_info[disk_index]['backing_writethrough'] = disk.backing.writeThrough
elif isinstance(disk.backing, vim.vm.device.VirtualDisk.FlatVer2BackingInfo):
disks_info[disk_index]['backing_type'] = 'FlatVer2'
disks_info[disk_index]['backing_writethrough'] = bool(disk.backing.writeThrough)
disks_info[disk_index]['backing_thinprovisioned'] = bool(disk.backing.thinProvisioned)
disks_info[disk_index]['backing_eagerlyscrub'] = bool(disk.backing.eagerlyScrub)
disks_info[disk_index]['backing_uuid'] = disk.backing.uuid
elif isinstance(disk.backing, vim.vm.device.VirtualDisk.LocalPMemBackingInfo):
disks_info[disk_index]['backing_type'] = 'LocalPMem'
disks_info[disk_index]['backing_volumeuuid'] = disk.backing.volumeUUID
disks_info[disk_index]['backing_uuid'] = disk.backing.uuid
elif isinstance(disk.backing, vim.vm.device.VirtualDisk.PartitionedRawDiskVer2BackingInfo):
disks_info[disk_index]['backing_type'] = 'PartitionedRawDiskVer2'
disks_info[disk_index]['backing_descriptorfilename'] = disk.backing.descriptorFileName
disks_info[disk_index]['backing_uuid'] = disk.backing.uuid
elif isinstance(disk.backing, vim.vm.device.VirtualDisk.RawDiskMappingVer1BackingInfo):
disks_info[disk_index]['backing_type'] = 'RawDiskMappingVer1'
disks_info[disk_index]['backing_devicename'] = disk.backing.deviceName
disks_info[disk_index]['backing_diskmode'] = disk.backing.diskMode
disks_info[disk_index]['backing_lunuuid'] = disk.backing.lunUuid
disks_info[disk_index]['backing_uuid'] = disk.backing.uuid
elif isinstance(disk.backing, vim.vm.device.VirtualDisk.RawDiskVer2BackingInfo):
disks_info[disk_index]['backing_type'] = 'RawDiskVer2'
disks_info[disk_index]['backing_descriptorfilename'] = disk.backing.descriptorFileName
disks_info[disk_index]['backing_uuid'] = disk.backing.uuid
elif isinstance(disk.backing, vim.vm.device.VirtualDisk.SeSparseBackingInfo):
disks_info[disk_index]['backing_type'] = 'SeSparse'
disks_info[disk_index]['backing_diskmode'] = disk.backing.diskMode
disks_info[disk_index]['backing_writethrough'] = bool(disk.backing.writeThrough)
disks_info[disk_index]['backing_uuid'] = disk.backing.uuid
elif isinstance(disk.backing, vim.vm.device.VirtualDisk.SparseVer1BackingInfo):
disks_info[disk_index]['backing_type'] = 'SparseVer1'
disks_info[disk_index]['backing_diskmode'] = disk.backing.diskMode
disks_info[disk_index]['backing_spaceusedinkb'] = disk.backing.spaceUsedInKB
disks_info[disk_index]['backing_split'] = bool(disk.backing.split)
disks_info[disk_index]['backing_writethrough'] = bool(disk.backing.writeThrough)
elif isinstance(disk.backing, vim.vm.device.VirtualDisk.SparseVer2BackingInfo):
disks_info[disk_index]['backing_type'] = 'SparseVer2'
disks_info[disk_index]['backing_diskmode'] = disk.backing.diskMode
disks_info[disk_index]['backing_spaceusedinkb'] = disk.backing.spaceUsedInKB
disks_info[disk_index]['backing_split'] = bool(disk.backing.split)
disks_info[disk_index]['backing_writethrough'] = bool(disk.backing.writeThrough)
disks_info[disk_index]['backing_uuid'] = disk.backing.uuid
for controller_index in range(len(controller_info)):
if controller_info[controller_index]['key'] == disks_info[disk_index]['controller_key']:
disks_info[disk_index]['controller_bus_number'] = controller_info[controller_index]['bus_number']
disks_info[disk_index]['controller_type'] = controller_info[controller_index]['controller_type']
disk_index += 1
return disks_info
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
name=dict(type='str'),
uuid=dict(type='str'),
moid=dict(type='str'),
use_instance_uuid=dict(type='bool', default=False),
folder=dict(type='str'),
datacenter=dict(type='str', required=True),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['name', 'uuid', 'moid']
],
supports_check_mode=True,
)
if module.params['folder']:
# FindByInventoryPath() does not require an absolute path
# so we should leave the input folder path unmodified
module.params['folder'] = module.params['folder'].rstrip('/')
pyv = PyVmomiHelper(module)
# Check if the VM exists before continuing
vm = pyv.get_vm()
if vm:
# VM exists
try:
module.exit_json(guest_disk_info=pyv.gather_disk_info(vm))
except Exception as exc:
module.fail_json(msg="Failed to gather information with exception : %s" % to_text(exc))
else:
# We unable to find the virtual machine user specified
# Bail out
vm_id = (module.params.get('uuid') or module.params.get('moid') or module.params.get('name'))
module.fail_json(msg="Unable to gather disk information for non-existing VM %s" % vm_id)
if __name__ == '__main__':
main()

View file

@ -18,10 +18,11 @@ ANSIBLE_METADATA = {
DOCUMENTATION = '''
---
module: vmware_guest_facts
short_description: Gather facts about a single VM
module: vmware_guest_info
short_description: Gather info about a single VM
description:
- Gather facts about a single VM on a VMware ESX cluster.
- Gather information about a single VM on a VMware ESX cluster.
- This module was called C(vmware_guest_facts) before Ansible 2.9. The usage did not change.
version_added: 2.3
author:
- Loic Blot (@nerzhul) <loic.blot@unix-experience.fr>
@ -83,8 +84,8 @@ options:
tags:
description:
- Whether to show tags or not.
- If set C(True), shows tag facts.
- If set C(False), hides tags facts.
- If set C(True), shows tag information.
- If set C(False), hides tags information.
- vSphere Automation SDK and vCloud Suite SDK is required.
default: 'no'
type: bool
@ -119,8 +120,8 @@ extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
- name: Gather facts from standalone ESXi server having datacenter as 'ha-datacenter'
vmware_guest_facts:
- name: Gather info from standalone ESXi server having datacenter as 'ha-datacenter'
vmware_guest_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
@ -128,10 +129,10 @@ EXAMPLES = '''
validate_certs: no
uuid: 421e4592-c069-924d-ce20-7e7533fab926
delegate_to: localhost
register: facts
register: info
- name: Gather some facts from a guest using the vSphere API output schema
vmware_guest_facts:
- name: Gather some info from a guest using the vSphere API output schema
vmware_guest_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
@ -141,9 +142,9 @@ EXAMPLES = '''
schema: "vsphere"
properties: ["config.hardware.memoryMB", "guest.disk", "overallStatus"]
delegate_to: localhost
register: facts
register: info
- name: Gather some facts from a guest using MoID
- name: Gather some information about a guest using MoID
vmware_guest_facts:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
@ -154,10 +155,10 @@ EXAMPLES = '''
schema: "vsphere"
properties: ["config.hardware.memoryMB", "guest.disk", "overallStatus"]
delegate_to: localhost
register: vm_moid_facts
register: vm_moid_info
- name: Gather Managed object ID (moid) from a guest using the vSphere API output schema for REST Calls
vmware_guest_facts:
vmware_guest_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
@ -168,7 +169,7 @@ EXAMPLES = '''
properties:
- _moId
delegate_to: localhost
register: moid_facts
register: moid_info
'''
RETURN = """
@ -269,6 +270,8 @@ def main():
module = AnsibleModule(argument_spec=argument_spec,
required_one_of=[['name', 'uuid', 'moid']],
supports_check_mode=True)
if module._name == 'vmware_guest_facts':
module.deprecate("The 'vmware_guest_facts' module has been renamed to 'vmware_guest_info'", version='2.13')
if module.params.get('folder'):
# FindByInventoryPath() does not require an absolute path
@ -303,10 +306,10 @@ def main():
)
module.exit_json(instance=instance)
except Exception as exc:
module.fail_json(msg="Fact gather failed with exception %s" % to_text(exc))
module.fail_json(msg="Information gathering failed with exception %s" % to_text(exc))
else:
vm_id = (module.params.get('uuid') or module.params.get('name') or module.params.get('moid'))
module.fail_json(msg="Unable to gather facts for non-existing VM %s" % vm_id)
module.fail_json(msg="Unable to gather information for non-existing VM %s" % vm_id)
if __name__ == '__main__':

View file

@ -36,7 +36,7 @@ options:
type: str
uuid:
description:
- UUID of the instance to gather facts if known, this is VMware's unique identifier.
- UUID of the instance to gather info if known, this is VMware's unique identifier.
- This is a required parameter, if parameter C(name) or C(moid) is not supplied.
type: str
moid:
@ -77,12 +77,13 @@ options:
description:
- The datacenter name to which virtual machine belongs to.
type: str
gather_network_facts:
gather_network_info:
description:
- If set to C(True), return settings of all network adapters, other parameters are ignored.
- If set to C(False), will add, reconfigure or remove network adapters according to the parameters in C(networks).
type: bool
default: False
aliases: [ gather_network_facts ]
networks:
type: list
description:
@ -124,7 +125,7 @@ EXAMPLES = '''
datacenter: "{{ datacenter_name }}"
validate_certs: no
name: test-vm
gather_network_facts: false
gather_network_info: false
networks:
- name: "VM Network"
state: new
@ -138,7 +139,7 @@ EXAMPLES = '''
- state: absent
mac: "00:50:56:44:55:77"
delegate_to: localhost
register: network_facts
register: network_info
- name: Change network adapter settings of virtual machine using MoID
vmware_guest_network:
@ -148,7 +149,7 @@ EXAMPLES = '''
datacenter: "{{ datacenter_name }}"
validate_certs: no
moid: vm-42
gather_network_facts: false
gather_network_info: false
networks:
- state: absent
mac: "00:50:56:44:55:77"
@ -270,10 +271,10 @@ class PyVmomiHelper(PyVmomi):
return nic
def get_network_facts(self, vm_obj):
network_facts = dict()
def get_network_info(self, vm_obj):
network_info = dict()
if vm_obj is None:
return network_facts
return network_info
nic_index = 0
for nic in vm_obj.config.hardware.device:
@ -291,7 +292,7 @@ class PyVmomiHelper(PyVmomi):
elif isinstance(nic, vim.vm.device.VirtualSriovEthernetCard):
nic_type = 'SriovEthernetCard'
if nic_type is not None:
network_facts[nic_index] = dict(
network_info[nic_index] = dict(
device_type=nic_type,
label=nic.deviceInfo.label,
name=nic.deviceInfo.summary,
@ -304,7 +305,7 @@ class PyVmomiHelper(PyVmomi):
)
nic_index += 1
return network_facts
return network_info
def sanitize_network_params(self):
network_list = []
@ -422,10 +423,10 @@ class PyVmomiHelper(PyVmomi):
def reconfigure_vm_network(self, vm_obj):
network_list = self.sanitize_network_params()
# gather network adapter facts only
if (self.params['gather_network_facts'] is not None and self.params['gather_network_facts']) or len(network_list) == 0:
results = {'changed': False, 'failed': False, 'network_data': self.get_network_facts(vm_obj)}
# do reconfigure then gather facts
# gather network adapter info only
if (self.params['gather_network_info'] is not None and self.params['gather_network_info']) or len(network_list) == 0:
results = {'changed': False, 'failed': False, 'network_data': self.get_network_info(vm_obj)}
# do reconfigure then gather info
else:
self.get_network_config_spec(vm_obj, network_list)
try:
@ -441,8 +442,8 @@ class PyVmomiHelper(PyVmomi):
if task.info.state == 'error':
results = {'changed': self.change_detected, 'failed': True, 'msg': task.info.error.msg}
else:
network_facts = self.get_network_facts(vm_obj)
results = {'changed': self.change_detected, 'failed': False, 'network_data': network_facts}
network_info = self.get_network_info(vm_obj)
results = {'changed': self.change_detected, 'failed': False, 'network_data': network_info}
return results
@ -457,7 +458,7 @@ def main():
datacenter=dict(type='str', default='ha-datacenter'),
esxi_hostname=dict(type='str'),
cluster=dict(type='str'),
gather_network_facts=dict(type='bool', default=False),
gather_network_info=dict(type='bool', default=False, aliases=['gather_network_facts']),
networks=dict(type='list', default=[])
)

View file

@ -16,10 +16,11 @@ ANSIBLE_METADATA = {
DOCUMENTATION = '''
---
module: vmware_guest_snapshot_facts
short_description: Gather facts about virtual machine's snapshots in vCenter
module: vmware_guest_snapshot_info
short_description: Gather info about virtual machine's snapshots in vCenter
description:
- This module can be used to gather facts about virtual machine's snapshots.
- This module can be used to gather information about virtual machine's snapshots.
- This module was called C(vmware_guest_snapshot_facts) before Ansible 2.9. The usage did not change.
version_added: 2.6
author:
- Abhijeet Kasurde (@Akasurde)
@ -77,30 +78,30 @@ extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
- name: Gather snapshot facts about the virtual machine in the given vCenter
vmware_guest_snapshot_facts:
- name: Gather snapshot information about the virtual machine in the given vCenter
vmware_guest_snapshot_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ datacenter_name }}"
name: "{{ guest_name }}"
delegate_to: localhost
register: snapshot_facts
register: snapshot_info
- name: Gather snapshot facts about the virtual machine using MoID
vmware_guest_snapshot_facts:
- name: Gather snapshot information about the virtual machine using MoID
vmware_guest_snapshot_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ datacenter_name }}"
moid: vm-42
delegate_to: localhost
register: snapshot_facts
register: snapshot_info
'''
RETURN = """
guest_snapshots:
description: metadata about the snapshot facts
description: metadata about the snapshot information
returned: always
type: dict
sample: {
@ -132,13 +133,13 @@ class PyVmomiHelper(PyVmomi):
super(PyVmomiHelper, self).__init__(module)
@staticmethod
def gather_guest_snapshot_facts(vm_obj=None):
def gather_guest_snapshot_info(vm_obj=None):
"""
Return snapshot related facts about given virtual machine
Return snapshot related information about given virtual machine
Args:
vm_obj: Virtual Machine Managed object
Returns: Dictionary containing snapshot facts
Returns: Dictionary containing snapshot information
"""
if vm_obj is None:
@ -166,6 +167,8 @@ def main():
],
supports_check_mode=True,
)
if module._name == 'vmware_guest_snapshot_facts':
module.deprecate("The 'vmware_guest_snapshot_facts' module has been renamed to 'vmware_guest_snapshot_info'", version='2.13')
if module.params['folder']:
# FindByInventoryPath() does not require an absolute path
@ -179,10 +182,10 @@ def main():
if not vm:
# If UUID is set, get_vm select UUID, show error message accordingly.
vm_id = (module.params.get('uuid') or module.params.get('name') or module.params.get('moid'))
module.fail_json(msg="Unable to gather facts about snapshots for"
module.fail_json(msg="Unable to gather information about snapshots for"
" non-existing VM ['%s']" % vm_id)
results = dict(changed=False, guest_snapshots=pyv.gather_guest_snapshot_facts(vm_obj=vm))
results = dict(changed=False, guest_snapshots=pyv.gather_guest_snapshot_info(vm_obj=vm))
module.exit_json(**results)

View file

@ -0,0 +1,222 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_capability_info
short_description: Gathers info about an ESXi host's capability information
description:
- This module can be used to gather information about an ESXi host's capability information when ESXi hostname or Cluster name is given.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
options:
cluster_name:
description:
- Name of the cluster from all host systems to be used for information gathering.
- If C(esxi_hostname) is not given, this parameter is required.
type: str
esxi_hostname:
description:
- ESXi hostname to gather information from.
- If C(cluster_name) is not given, this parameter is required.
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather capability info about all ESXi Host in given Cluster
vmware_host_capability_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: cluster_name
delegate_to: localhost
register: all_cluster_hosts_info
- name: Gather capability info about ESXi Host
vmware_host_capability_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
esxi_hostname: '{{ esxi_hostname }}'
delegate_to: localhost
register: hosts_info
'''
RETURN = r'''
hosts_capability_info:
description: metadata about host's capability info
returned: always
type: dict
sample: {
"esxi_hostname_0001": {
"accel3dSupported": false,
"backgroundSnapshotsSupported": false,
"checkpointFtCompatibilityIssues": [],
"checkpointFtSupported": false,
"cloneFromSnapshotSupported": true,
"cpuHwMmuSupported": true,
}
}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi
class CapabilityInfoManager(PyVmomi):
def __init__(self, module):
super(CapabilityInfoManager, self).__init__(module)
cluster_name = self.params.get('cluster_name', None)
esxi_host_name = self.params.get('esxi_hostname', None)
self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
def gather_host_capability_info(self):
hosts_capability_info = dict()
for host in self.hosts:
hc = host.capability
hosts_capability_info[host.name] = dict(
recursiveResourcePoolsSupported=hc.recursiveResourcePoolsSupported,
cpuMemoryResourceConfigurationSupported=hc.cpuMemoryResourceConfigurationSupported,
rebootSupported=hc.rebootSupported,
shutdownSupported=hc.shutdownSupported,
vmotionSupported=hc.vmotionSupported,
standbySupported=hc.standbySupported,
ipmiSupported=hc.ipmiSupported,
maxSupportedVMs=hc.maxSupportedVMs,
maxRunningVMs=hc.maxRunningVMs,
maxSupportedVcpus=hc.maxSupportedVcpus,
maxRegisteredVMs=hc.maxRegisteredVMs,
datastorePrincipalSupported=hc.datastorePrincipalSupported,
sanSupported=hc.sanSupported,
nfsSupported=hc.nfsSupported,
iscsiSupported=hc.iscsiSupported,
vlanTaggingSupported=hc.vlanTaggingSupported,
nicTeamingSupported=hc.nicTeamingSupported,
highGuestMemSupported=hc.highGuestMemSupported,
maintenanceModeSupported=hc.maintenanceModeSupported,
suspendedRelocateSupported=hc.suspendedRelocateSupported,
restrictedSnapshotRelocateSupported=hc.restrictedSnapshotRelocateSupported,
perVmSwapFiles=hc.perVmSwapFiles,
localSwapDatastoreSupported=hc.localSwapDatastoreSupported,
unsharedSwapVMotionSupported=hc.unsharedSwapVMotionSupported,
backgroundSnapshotsSupported=hc.backgroundSnapshotsSupported,
preAssignedPCIUnitNumbersSupported=hc.preAssignedPCIUnitNumbersSupported,
screenshotSupported=hc.screenshotSupported,
scaledScreenshotSupported=hc.scaledScreenshotSupported,
storageVMotionSupported=hc.storageVMotionSupported,
vmotionWithStorageVMotionSupported=hc.vmotionWithStorageVMotionSupported,
vmotionAcrossNetworkSupported=hc.vmotionAcrossNetworkSupported,
maxNumDisksSVMotion=hc.maxNumDisksSVMotion,
hbrNicSelectionSupported=hc.hbrNicSelectionSupported,
vrNfcNicSelectionSupported=hc.vrNfcNicSelectionSupported,
recordReplaySupported=hc.recordReplaySupported,
ftSupported=hc.ftSupported,
replayUnsupportedReason=hc.replayUnsupportedReason,
checkpointFtSupported=hc.checkpointFtSupported,
smpFtSupported=hc.smpFtSupported,
maxVcpusPerFtVm=hc.maxVcpusPerFtVm,
loginBySSLThumbprintSupported=hc.loginBySSLThumbprintSupported,
cloneFromSnapshotSupported=hc.cloneFromSnapshotSupported,
deltaDiskBackingsSupported=hc.deltaDiskBackingsSupported,
perVMNetworkTrafficShapingSupported=hc.perVMNetworkTrafficShapingSupported,
tpmSupported=hc.tpmSupported,
virtualExecUsageSupported=hc.virtualExecUsageSupported,
storageIORMSupported=hc.storageIORMSupported,
vmDirectPathGen2Supported=hc.vmDirectPathGen2Supported,
vmDirectPathGen2UnsupportedReasonExtended=hc.vmDirectPathGen2UnsupportedReasonExtended,
vStorageCapable=hc.vStorageCapable,
snapshotRelayoutSupported=hc.snapshotRelayoutSupported,
firewallIpRulesSupported=hc.firewallIpRulesSupported,
servicePackageInfoSupported=hc.servicePackageInfoSupported,
maxHostRunningVms=hc.maxHostRunningVms,
maxHostSupportedVcpus=hc.maxHostSupportedVcpus,
vmfsDatastoreMountCapable=hc.vmfsDatastoreMountCapable,
eightPlusHostVmfsSharedAccessSupported=hc.eightPlusHostVmfsSharedAccessSupported,
nestedHVSupported=hc.nestedHVSupported,
vPMCSupported=hc.vPMCSupported,
interVMCommunicationThroughVMCISupported=hc.interVMCommunicationThroughVMCISupported,
scheduledHardwareUpgradeSupported=hc.scheduledHardwareUpgradeSupported,
featureCapabilitiesSupported=hc.featureCapabilitiesSupported,
latencySensitivitySupported=hc.latencySensitivitySupported,
storagePolicySupported=hc.storagePolicySupported,
accel3dSupported=hc.accel3dSupported,
reliableMemoryAware=hc.reliableMemoryAware,
multipleNetworkStackInstanceSupported=hc.multipleNetworkStackInstanceSupported,
messageBusProxySupported=hc.messageBusProxySupported,
vsanSupported=hc.vsanSupported,
vFlashSupported=hc.vFlashSupported,
hostAccessManagerSupported=hc.hostAccessManagerSupported,
provisioningNicSelectionSupported=hc.provisioningNicSelectionSupported,
nfs41Supported=hc.nfs41Supported,
nfs41Krb5iSupported=hc.nfs41Krb5iSupported,
turnDiskLocatorLedSupported=hc.turnDiskLocatorLedSupported,
virtualVolumeDatastoreSupported=hc.virtualVolumeDatastoreSupported,
markAsSsdSupported=hc.markAsSsdSupported,
markAsLocalSupported=hc.markAsLocalSupported,
smartCardAuthenticationSupported=hc.smartCardAuthenticationSupported,
cryptoSupported=hc.cryptoSupported,
oneKVolumeAPIsSupported=hc.oneKVolumeAPIsSupported,
gatewayOnNicSupported=hc.gatewayOnNicSupported,
upitSupported=hc.upitSupported,
cpuHwMmuSupported=hc.cpuHwMmuSupported,
encryptedVMotionSupported=hc.encryptedVMotionSupported,
encryptionChangeOnAddRemoveSupported=hc.encryptionChangeOnAddRemoveSupported,
encryptionHotOperationSupported=hc.encryptionHotOperationSupported,
encryptionWithSnapshotsSupported=hc.encryptionWithSnapshotsSupported,
encryptionFaultToleranceSupported=hc.encryptionFaultToleranceSupported,
encryptionMemorySaveSupported=hc.encryptionMemorySaveSupported,
encryptionRDMSupported=hc.encryptionRDMSupported,
encryptionVFlashSupported=hc.encryptionVFlashSupported,
encryptionCBRCSupported=hc.encryptionCBRCSupported,
encryptionHBRSupported=hc.encryptionHBRSupported,
supportedVmfsMajorVersion=[version for version in hc.supportedVmfsMajorVersion],
vmDirectPathGen2UnsupportedReason=[reason for reason in hc.vmDirectPathGen2UnsupportedReason],
ftCompatibilityIssues=[issue for issue in hc.ftCompatibilityIssues],
checkpointFtCompatibilityIssues=[issue for issue in hc.checkpointFtCompatibilityIssues],
smpFtCompatibilityIssues=[issue for issue in hc.smpFtCompatibilityIssues],
replayCompatibilityIssues=[issue for issue in hc.replayCompatibilityIssues],
)
return hosts_capability_info
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
cluster_name=dict(type='str', required=False),
esxi_hostname=dict(type='str', required=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'esxi_hostname'],
],
supports_check_mode=True,
)
host_capability_manager = CapabilityInfoManager(module)
module.exit_json(changed=False,
hosts_capability_info=host_capability_manager.gather_host_capability_info())
if __name__ == "__main__":
main()

View file

@ -0,0 +1,120 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_config_info
short_description: Gathers info about an ESXi host's advance configuration information
description:
- This module can be used to gather information about an ESXi host's advance configuration information when ESXi hostname or Cluster name is given.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
options:
cluster_name:
description:
- Name of the cluster from which the ESXi host belong to.
- If C(esxi_hostname) is not given, this parameter is required.
type: str
esxi_hostname:
description:
- ESXi hostname to gather information from.
- If C(cluster_name) is not given, this parameter is required.
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather info about all ESXi Host in given Cluster
vmware_host_config_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: cluster_name
delegate_to: localhost
- name: Gather info about ESXi Host
vmware_host_config_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
esxi_hostname: '{{ esxi_hostname }}'
delegate_to: localhost
'''
RETURN = r'''
hosts_info:
description:
- dict with hostname as key and dict with host config information
returned: always
type: dict
sample: {
"10.76.33.226": {
"Annotations.WelcomeMessage": "",
"BufferCache.FlushInterval": 30000,
"BufferCache.HardMaxDirty": 95,
"BufferCache.PerFileHardMaxDirty": 50,
"BufferCache.SoftMaxDirty": 15,
}
}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi
class VmwareConfigInfoManager(PyVmomi):
def __init__(self, module):
super(VmwareConfigInfoManager, self).__init__(module)
cluster_name = self.params.get('cluster_name', None)
esxi_host_name = self.params.get('esxi_hostname', None)
self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
def gather_host_info(self):
hosts_info = {}
for host in self.hosts:
host_info = {}
for option in host.configManager.advancedOption.QueryOptions():
host_info[option.key] = option.value
hosts_info[host.name] = host_info
return hosts_info
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
cluster_name=dict(type='str', required=False),
esxi_hostname=dict(type='str', required=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'esxi_hostname'],
],
supports_check_mode=True
)
vmware_host_config = VmwareConfigInfoManager(module)
module.exit_json(changed=False, hosts_info=vmware_host_config.gather_host_info())
if __name__ == "__main__":
main()

View file

@ -0,0 +1,131 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_dns_info
short_description: Gathers info about an ESXi host's DNS configuration information
description:
- This module can be used to gather information about an ESXi host's DNS configuration information when ESXi hostname or Cluster name is given.
- All parameters and VMware object names are case sensitive.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
options:
cluster_name:
description:
- Name of the cluster from which the ESXi host belong to.
- If C(esxi_hostname) is not given, this parameter is required.
type: str
esxi_hostname:
description:
- ESXi hostname to gather information from.
- If C(cluster_name) is not given, this parameter is required.
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather DNS info about all ESXi Hosts in given Cluster
vmware_host_dns_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: cluster_name
delegate_to: localhost
- name: Gather DNS info about ESXi Host
vmware_host_dns_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
esxi_hostname: '{{ esxi_hostname }}'
delegate_to: localhost
'''
RETURN = r'''
hosts_dns_info:
description: metadata about DNS config from given cluster / host system
returned: always
type: dict
sample: {
"DC0_C0_H0": {
"dhcp": true,
"domain_name": "localdomain",
"host_name": "localhost",
"ip_address": [
"8.8.8.8"
],
"search_domain": [
"localdomain"
],
"virtual_nic_device": "vmk0"
}
}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi
class VmwareDnsInfoManager(PyVmomi):
def __init__(self, module):
super(VmwareDnsInfoManager, self).__init__(module)
cluster_name = self.params.get('cluster_name', None)
esxi_host_name = self.params.get('esxi_hostname', None)
self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
def gather_dns_info(self):
hosts_info = {}
for host in self.hosts:
host_info = {}
dns_config = host.config.network.dnsConfig
host_info['dhcp'] = dns_config.dhcp
host_info['virtual_nic_device'] = dns_config.virtualNicDevice
host_info['host_name'] = dns_config.hostName
host_info['domain_name'] = dns_config.domainName
host_info['ip_address'] = [ip for ip in dns_config.address]
host_info['search_domain'] = [domain for domain in dns_config.searchDomain]
hosts_info[host.name] = host_info
return hosts_info
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
cluster_name=dict(type='str', required=False),
esxi_hostname=dict(type='str', required=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'esxi_hostname'],
],
supports_check_mode=True
)
vmware_dns_config = VmwareDnsInfoManager(module)
module.exit_json(changed=False, hosts_dns_info=vmware_dns_config.gather_dns_info())
if __name__ == "__main__":
main()

View file

@ -0,0 +1,143 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_feature_info
short_description: Gathers info about an ESXi host's feature capability information
description:
- This module can be used to gather information about an ESXi host's feature capability information when ESXi hostname or Cluster name is given.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
options:
cluster_name:
description:
- Name of the cluster from all host systems to be used for information gathering.
- If C(esxi_hostname) is not given, this parameter is required.
type: str
esxi_hostname:
description:
- ESXi hostname to gather information from.
- If C(cluster_name) is not given, this parameter is required.
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather feature capability info about all ESXi Hosts in given Cluster
vmware_host_feature_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: cluster_name
delegate_to: localhost
register: all_cluster_hosts_info
- name: Check if ESXi is vulnerable for Speculative Store Bypass Disable (SSBD) vulnerability
vmware_host_feature_info:
hostname: "{{ vcenter_server }}"
username: "{{ vcenter_user }}"
password: "{{ vcenter_pass }}"
validate_certs: no
esxi_hostname: "{{ esxi_hostname }}"
register: features_set
- set_fact:
ssbd : "{{ item.value }}"
loop: "{{ features_set.host_feature_info[esxi_hostname] |json_query(name) }}"
vars:
name: "[?key=='cpuid.SSBD']"
- assert:
that:
- ssbd|int == 1
when: ssbd is defined
'''
RETURN = r'''
hosts_feature_info:
description: metadata about host's feature capability information
returned: always
type: dict
sample: {
"10.76.33.226": [
{
"feature_name": "cpuid.3DNOW",
"key": "cpuid.3DNOW",
"value": "0"
},
{
"feature_name": "cpuid.3DNOWPLUS",
"key": "cpuid.3DNOWPLUS",
"value": "0"
},
]
}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi
class FeatureCapabilityInfoManager(PyVmomi):
def __init__(self, module):
super(FeatureCapabilityInfoManager, self).__init__(module)
cluster_name = self.params.get('cluster_name', None)
esxi_host_name = self.params.get('esxi_hostname', None)
self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
def gather_host_feature_info(self):
host_feature_info = dict()
for host in self.hosts:
host_feature_capabilities = host.config.featureCapability
capability = []
for fc in host_feature_capabilities:
temp_dict = {
'key': fc.key,
'feature_name': fc.featureName,
'value': fc.value,
}
capability.append(temp_dict)
host_feature_info[host.name] = capability
return host_feature_info
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
cluster_name=dict(type='str', required=False),
esxi_hostname=dict(type='str', required=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'esxi_hostname'],
],
supports_check_mode=True,
)
host_capability_manager = FeatureCapabilityInfoManager(module)
module.exit_json(changed=False,
hosts_feature_info=host_capability_manager.gather_host_feature_info())
if __name__ == "__main__":
main()

View file

@ -0,0 +1,164 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_firewall_info
short_description: Gathers info about an ESXi host's firewall configuration information
description:
- This module can be used to gather information about an ESXi host's firewall configuration information when ESXi hostname or Cluster name is given.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
options:
cluster_name:
description:
- Name of the cluster from which the ESXi host belong to.
- If C(esxi_hostname) is not given, this parameter is required.
type: str
esxi_hostname:
description:
- ESXi hostname to gather information from.
- If C(cluster_name) is not given, this parameter is required.
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather firewall info about all ESXi Host in given Cluster
vmware_host_firewall_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: cluster_name
delegate_to: localhost
- name: Gather firewall info about ESXi Host
vmware_host_firewall_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
esxi_hostname: '{{ esxi_hostname }}'
delegate_to: localhost
'''
RETURN = r'''
hosts_firewall_info:
description: metadata about host's firewall configuration
returned: on success
type: dict
sample: {
"esxi_hostname_0001": [
{
"allowed_hosts": {
"all_ip": true,
"ip_address": [
"10.10.10.1",
],
"ip_network": [
"11.111.112.0/22",
"192.168.10.1/24"
],
},
"enabled": true,
"key": "CIMHttpServer",
"rule": [
{
"direction": "inbound",
"end_port": null,
"port": 5988,
"port_type": "dst",
"protocol": "tcp"
}
],
"service": "sfcbd-watchdog"
},
]
}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi
class FirewallInfoManager(PyVmomi):
def __init__(self, module):
super(FirewallInfoManager, self).__init__(module)
cluster_name = self.params.get('cluster_name', None)
esxi_host_name = self.params.get('esxi_hostname', None)
self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
@staticmethod
def normalize_rule_set(rule_obj):
rule_dict = dict()
rule_dict['key'] = rule_obj.key
rule_dict['service'] = rule_obj.service
rule_dict['enabled'] = rule_obj.enabled
rule_dict['rule'] = []
for rule in rule_obj.rule:
rule_set_dict = dict()
rule_set_dict['port'] = rule.port
rule_set_dict['end_port'] = rule.endPort
rule_set_dict['direction'] = rule.direction
rule_set_dict['port_type'] = rule.portType
rule_set_dict['protocol'] = rule.protocol
rule_dict['rule'].append(rule_set_dict)
allowed_host = rule_obj.allowedHosts
rule_allow_host = dict()
rule_allow_host['ip_address'] = [ip for ip in allowed_host.ipAddress]
rule_allow_host['ip_network'] = [ip.network + "/" + str(ip.prefixLength) for ip in allowed_host.ipNetwork]
rule_allow_host['all_ip'] = allowed_host.allIp
rule_dict['allowed_hosts'] = rule_allow_host
return rule_dict
def gather_host_firewall_info(self):
hosts_firewall_info = dict()
for host in self.hosts:
firewall_system = host.configManager.firewallSystem
if firewall_system:
hosts_firewall_info[host.name] = []
for rule_set_obj in firewall_system.firewallInfo.ruleset:
hosts_firewall_info[host.name].append(self.normalize_rule_set(rule_obj=rule_set_obj))
return hosts_firewall_info
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
cluster_name=dict(type='str', required=False),
esxi_hostname=dict(type='str', required=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'esxi_hostname'],
],
supports_check_mode=True
)
vmware_host_firewall = FirewallInfoManager(module)
module.exit_json(changed=False, hosts_firewall_info=vmware_host_firewall.gather_host_firewall_info())
if __name__ == "__main__":
main()

View file

@ -0,0 +1,135 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_ntp_info
short_description: Gathers info about NTP configuration on an ESXi host
description:
- This module can be used to gather information about NTP configurations on an ESXi host.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
options:
cluster_name:
description:
- Name of the cluster.
- NTP config information about each ESXi server will be returned for the given cluster.
- If C(esxi_hostname) is not given, this parameter is required.
type: str
esxi_hostname:
description:
- ESXi hostname.
- NTP config information about this ESXi server will be returned.
- If C(cluster_name) is not given, this parameter is required.
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather NTP info about all ESXi Host in the given Cluster
vmware_host_ntp_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: cluster_name
delegate_to: localhost
register: cluster_host_ntp
- name: Gather NTP info about ESXi Host
vmware_host_ntp_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
esxi_hostname: '{{ esxi_hostname }}'
delegate_to: localhost
register: host_ntp
'''
RETURN = r'''
hosts_ntp_info:
description:
- dict with hostname as key and dict with NTP infos as value
returned: hosts_ntp_info
type: dict
sample: {
"10.76.33.226": [
{
"ntp_servers": [],
"time_zone_description": "UTC",
"time_zone_gmt_offset": 0,
"time_zone_identifier": "UTC",
"time_zone_name": "UTC"
}
]
}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi
class VmwareNtpInfoManager(PyVmomi):
def __init__(self, module):
super(VmwareNtpInfoManager, self).__init__(module)
cluster_name = self.params.get('cluster_name', None)
esxi_host_name = self.params.get('esxi_hostname', None)
self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
def gather_ntp_info(self):
hosts_info = {}
for host in self.hosts:
host_ntp_info = []
host_date_time_manager = host.configManager.dateTimeSystem
if host_date_time_manager:
host_ntp_info.append(
dict(
time_zone_identifier=host_date_time_manager.dateTimeInfo.timeZone.key,
time_zone_name=host_date_time_manager.dateTimeInfo.timeZone.name,
time_zone_description=host_date_time_manager.dateTimeInfo.timeZone.description,
time_zone_gmt_offset=host_date_time_manager.dateTimeInfo.timeZone.gmtOffset,
ntp_servers=[ntp_server for ntp_server in host_date_time_manager.dateTimeInfo.ntpConfig.server]
)
)
hosts_info[host.name] = host_ntp_info
return hosts_info
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
cluster_name=dict(type='str', required=False),
esxi_hostname=dict(type='str', required=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'esxi_hostname'],
],
supports_check_mode=True,
)
vmware_host_ntp_config = VmwareNtpInfoManager(module)
module.exit_json(changed=False, hosts_ntp_info=vmware_host_ntp_config.gather_ntp_info())
if __name__ == "__main__":
main()

View file

@ -0,0 +1,128 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_package_info
short_description: Gathers info about available packages on an ESXi host
description:
- This module can be used to gather information about available packages and their status on an ESXi host.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
options:
cluster_name:
description:
- Name of the cluster.
- Package information about each ESXi server will be returned for given cluster.
- If C(esxi_hostname) is not given, this parameter is required.
type: str
esxi_hostname:
description:
- ESXi hostname.
- Package information about this ESXi server will be returned.
- If C(cluster_name) is not given, this parameter is required.
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather info about all ESXi Host in given Cluster
vmware_host_package_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: cluster_name
delegate_to: localhost
register: cluster_host_packages
- name: Gather info about ESXi Host
vmware_host_package_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
esxi_hostname: '{{ esxi_hostname }}'
delegate_to: localhost
register: host_packages
'''
RETURN = r'''
hosts_package_info:
description:
- dict with hostname as key and dict with package information as value
returned: hosts_package_info
type: dict
sample: { "hosts_package_info": { "localhost.localdomain": []}}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi
class VmwarePackageManager(PyVmomi):
def __init__(self, module):
super(VmwarePackageManager, self).__init__(module)
cluster_name = self.params.get('cluster_name', None)
esxi_host_name = self.params.get('esxi_hostname', None)
self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
def gather_package_info(self):
hosts_info = {}
for host in self.hosts:
host_package_info = []
host_pkg_mgr = host.configManager.imageConfigManager
if host_pkg_mgr:
pkgs = host_pkg_mgr.FetchSoftwarePackages()
for pkg in pkgs:
host_package_info.append(dict(
name=pkg.name,
version=pkg.version,
vendor=pkg.vendor,
summary=pkg.summary,
description=pkg.description,
acceptance_level=pkg.acceptanceLevel,
maintenance_mode_required=pkg.maintenanceModeRequired,
creation_date=pkg.creationDate,
))
hosts_info[host.name] = host_package_info
return hosts_info
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
cluster_name=dict(type='str', required=False),
esxi_hostname=dict(type='str', required=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'esxi_hostname'],
],
supports_check_mode=True,
)
vmware_host_package_config = VmwarePackageManager(module)
module.exit_json(changed=False, hosts_package_info=vmware_host_package_config.gather_package_info())
if __name__ == "__main__":
main()

View file

@ -0,0 +1,154 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_service_info
short_description: Gathers info about an ESXi host's services
description:
- This module can be used to gather information about an ESXi host's services.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
- If source package name is not available then fact is populated as null.
requirements:
- python >= 2.6
- PyVmomi
options:
cluster_name:
description:
- Name of the cluster.
- Service information about each ESXi server will be returned for given cluster.
- If C(esxi_hostname) is not given, this parameter is required.
type: str
esxi_hostname:
description:
- ESXi hostname.
- Service information about this ESXi server will be returned.
- If C(cluster_name) is not given, this parameter is required.
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather info about all ESXi Host in given Cluster
vmware_host_service_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: cluster_name
delegate_to: localhost
register: cluster_host_services
- name: Gather info about ESXi Host
vmware_host_service_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
esxi_hostname: '{{ esxi_hostname }}'
delegate_to: localhost
register: host_services
'''
RETURN = r'''
host_service_info:
description:
- dict with hostname as key and dict with host service config information
returned: always
type: dict
sample: {
"10.76.33.226": [
{
"key": "DCUI",
"label": "Direct Console UI",
"policy": "on",
"required": false,
"running": true,
"uninstallable": false,
"source_package_name": "esx-base",
"source_package_desc": "This VIB contains all of the base functionality of vSphere ESXi."
},
{
"key": "TSM",
"label": "ESXi Shell",
"policy": "off",
"required": false,
"running": false,
"uninstallable": false,
"source_package_name": "esx-base",
"source_package_desc": "This VIB contains all of the base functionality of vSphere ESXi."
},
]
}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi
class VmwareServiceManager(PyVmomi):
def __init__(self, module):
super(VmwareServiceManager, self).__init__(module)
cluster_name = self.params.get('cluster_name', None)
esxi_host_name = self.params.get('esxi_hostname', None)
self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
def gather_host_info(self):
hosts_info = {}
for host in self.hosts:
host_service_info = []
host_service_system = host.configManager.serviceSystem
if host_service_system:
services = host_service_system.serviceInfo.service
for service in services:
host_service_info.append(
dict(
key=service.key,
label=service.label,
required=service.required,
uninstallable=service.uninstallable,
running=service.running,
policy=service.policy,
source_package_name=service.sourcePackage.sourcePackageName if service.sourcePackage else None,
source_package_desc=service.sourcePackage.description if service.sourcePackage else None,
)
)
hosts_info[host.name] = host_service_info
return hosts_info
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
cluster_name=dict(type='str', required=False),
esxi_hostname=dict(type='str', required=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'esxi_hostname'],
],
supports_check_mode=True,
)
vmware_host_service_config = VmwareServiceManager(module)
module.exit_json(changed=False, host_service_info=vmware_host_service_config.gather_host_info())
if __name__ == "__main__":
main()

View file

@ -0,0 +1,149 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_ssl_info
short_description: Gather info of ESXi host system about SSL
description:
- This module can be used to gather information of the SSL thumbprint information for a host.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
options:
cluster_name:
description:
- Name of the cluster.
- SSL thumbprint information about all ESXi host system in the given cluster will be reported.
- If C(esxi_hostname) is not given, this parameter is required.
type: str
esxi_hostname:
description:
- ESXi hostname.
- SSL thumbprint information of this ESXi host system will be reported.
- If C(cluster_name) is not given, this parameter is required.
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather SSL thumbprint information about all ESXi Hosts in given Cluster
vmware_host_ssl_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: '{{ cluster_name }}'
delegate_to: localhost
register: all_host_ssl_info
- name: Get SSL Thumbprint info about "{{ esxi_hostname }}"
vmware_host_ssl_info:
hostname: "{{ vcenter_server }}"
username: "{{ vcenter_user }}"
password: "{{ vcenter_pass }}"
esxi_hostname: '{{ esxi_hostname }}'
register: ssl_info
- set_fact:
ssl_thumbprint: "{{ ssl_info['host_ssl_info'][esxi_hostname]['ssl_thumbprints'][0] }}"
- debug:
msg: "{{ ssl_thumbprint }}"
- name: Add ESXi Host to vCenter
vmware_host:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
datacenter_name: '{{ datacenter_name }}'
cluster_name: '{{ cluster_name }}'
esxi_hostname: '{{ esxi_hostname }}'
esxi_username: '{{ esxi_username }}'
esxi_password: '{{ esxi_password }}'
esxi_ssl_thumbprint: '{{ ssl_thumbprint }}'
state: present
'''
RETURN = r'''
host_ssl_info:
description:
- dict with hostname as key and dict with SSL thumbprint related info
returned: info
type: dict
sample:
{
"10.76.33.215": {
"owner_tag": "",
"principal": "vpxuser",
"ssl_thumbprints": [
"E3:E8:A9:20:8D:32:AE:59:C6:8D:A5:91:B0:20:EF:00:A2:7C:27:EE",
"F1:AC:DA:6E:D8:1E:37:36:4A:5C:07:E5:04:0B:87:C8:75:FB:42:01"
]
}
}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi
class VMwareHostSslManager(PyVmomi):
def __init__(self, module):
super(VMwareHostSslManager, self).__init__(module)
cluster_name = self.params.get('cluster_name', None)
esxi_host_name = self.params.get('esxi_hostname', None)
self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
self.hosts_info = {}
def gather_ssl_info(self):
for host in self.hosts:
self.hosts_info[host.name] = dict(
principal='',
owner_tag='',
ssl_thumbprints=[])
host_ssl_info_mgr = host.config.sslThumbprintInfo
if host_ssl_info_mgr:
self.hosts_info[host.name]['principal'] = host_ssl_info_mgr.principal
self.hosts_info[host.name]['owner_tag'] = host_ssl_info_mgr.ownerTag
self.hosts_info[host.name]['ssl_thumbprints'] = [i for i in host_ssl_info_mgr.sslThumbprints]
self.module.exit_json(changed=False, host_ssl_info=self.hosts_info)
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
cluster_name=dict(type='str'),
esxi_hostname=dict(type='str'),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'esxi_hostname'],
],
supports_check_mode=True,
)
vmware_host_accept_config = VMwareHostSslManager(module)
vmware_host_accept_config.gather_ssl_info()
if __name__ == "__main__":
main()

View file

@ -0,0 +1,218 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Christian Kotte <christian.kotte@gmx.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_vmhba_info
short_description: Gathers info about vmhbas available on the given ESXi host
description:
- This module can be used to gather information about vmhbas available on the given ESXi host.
- If C(cluster_name) is provided, then vmhba information about all hosts from given cluster will be returned.
- If C(esxi_hostname) is provided, then vmhba information about given host system will be returned.
version_added: '2.9'
author:
- Christian Kotte (@ckotte)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
options:
esxi_hostname:
description:
- Name of the host system to work with.
- Vmhba information about this ESXi server will be returned.
- This parameter is required if C(cluster_name) is not specified.
type: str
cluster_name:
description:
- Name of the cluster from which all host systems will be used.
- Vmhba information about each ESXi server will be returned for the given cluster.
- This parameter is required if C(esxi_hostname) is not specified.
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather info about vmhbas of all ESXi Host in the given Cluster
vmware_host_vmhba_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: '{{ cluster_name }}'
delegate_to: localhost
register: cluster_host_vmhbas
- name: Gather info about vmhbas of an ESXi Host
vmware_host_vmhba_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
esxi_hostname: '{{ esxi_hostname }}'
delegate_to: localhost
register: host_vmhbas
'''
RETURN = r'''
hosts_vmhbas_info:
description:
- dict with hostname as key and dict with vmhbas information as value.
returned: hosts_vmhbas_info
type: dict
sample:
{
"10.76.33.204": {
"vmhba_details": [
{
"adapter": "HPE Smart Array P440ar",
"bus": 3,
"device": "vmhba0",
"driver": "nhpsa",
"location": "0000:03:00.0",
"model": "Smart Array P440ar",
"node_wwn": "50:01:43:80:37:18:9e:a0",
"status": "unknown",
"type": "SAS"
},
{
"adapter": "QLogic Corp ISP2532-based 8Gb Fibre Channel to PCI Express HBA",
"bus": 5,
"device": "vmhba1",
"driver": "qlnativefc",
"location": "0000:05:00.0",
"model": "ISP2532-based 8Gb Fibre Channel to PCI Express HBA",
"node_wwn": "57:64:96:32:15:90:23:95:82",
"port_type": "unknown",
"port_wwn": "57:64:96:32:15:90:23:95:82",
"speed": 8,
"status": "online",
"type": "Fibre Channel"
},
{
"adapter": "QLogic Corp ISP2532-based 8Gb Fibre Channel to PCI Express HBA",
"bus": 8,
"device": "vmhba2",
"driver": "qlnativefc",
"location": "0000:08:00.0",
"model": "ISP2532-based 8Gb Fibre Channel to PCI Express HBA",
"node_wwn": "57:64:96:32:15:90:23:95:21",
"port_type": "unknown",
"port_wwn": "57:64:96:32:15:90:23:95:21",
"speed": 8,
"status": "online",
"type": "Fibre Channel"
}
],
}
}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi
class HostVmhbaMgr(PyVmomi):
"""Class to manage vmhba info"""
def __init__(self, module):
super(HostVmhbaMgr, self).__init__(module)
cluster_name = self.params.get('cluster_name', None)
esxi_host_name = self.params.get('esxi_hostname', None)
self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
if not self.hosts:
self.module.fail_json(msg="Failed to find host system.")
def gather_host_vmhba_info(self):
"""Gather vmhba info"""
hosts_vmhba_info = {}
for host in self.hosts:
host_vmhba_info = dict()
host_st_system = host.configManager.storageSystem
if host_st_system:
device_info = host_st_system.storageDeviceInfo
host_vmhba_info['vmhba_details'] = []
for hba in device_info.hostBusAdapter:
hba_info = dict()
if hba.pci:
hba_info['location'] = hba.pci
for pci_device in host.hardware.pciDevice:
if pci_device.id == hba.pci:
hba_info['adapter'] = pci_device.vendorName + ' ' + pci_device.deviceName
break
else:
hba_info['location'] = 'PCI'
hba_info['device'] = hba.device
# contains type as string in format of 'key-vim.host.FibreChannelHba-vmhba1'
hba_type = hba.key.split(".")[-1].split("-")[0]
if hba_type == 'SerialAttachedHba':
hba_info['type'] = 'SAS'
elif hba_type == 'FibreChannelHba':
hba_info['type'] = 'Fibre Channel'
else:
hba_info['type'] = hba_type
hba_info['bus'] = hba.bus
hba_info['status'] = hba.status
hba_info['model'] = hba.model
hba_info['driver'] = hba.driver
try:
hba_info['node_wwn'] = self.format_number(hba.nodeWorldWideName)
except AttributeError:
pass
try:
hba_info['port_wwn'] = self.format_number(hba.portWorldWideName)
except AttributeError:
pass
try:
hba_info['port_type'] = hba.portType
except AttributeError:
pass
try:
hba_info['speed'] = hba.speed
except AttributeError:
pass
host_vmhba_info['vmhba_details'].append(hba_info)
hosts_vmhba_info[host.name] = host_vmhba_info
return hosts_vmhba_info
@staticmethod
def format_number(number):
"""Format number"""
string = str(number)
return ':'.join(a + b for a, b in zip(string[::2], string[1::2]))
def main():
"""Main"""
argument_spec = vmware_argument_spec()
argument_spec.update(
cluster_name=dict(type='str', required=False),
esxi_hostname=dict(type='str', required=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'esxi_hostname'],
],
supports_check_mode=True,
)
host_vmhba_mgr = HostVmhbaMgr(module)
module.exit_json(changed=False, hosts_vmhbas_info=host_vmhba_mgr.gather_host_vmhba_info())
if __name__ == "__main__":
main()

View file

@ -0,0 +1,317 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# Copyright: (c) 2018, Christian Kotte <christian.kotte@gmx.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_vmnic_info
short_description: Gathers info about vmnics available on the given ESXi host
description:
- This module can be used to gather information about vmnics available on the given ESXi host.
- If C(cluster_name) is provided, then vmnic information about all hosts from given cluster will be returned.
- If C(esxi_hostname) is provided, then vmnic information about given host system will be returned.
- Additional details about vswitch and dvswitch with respective vmnic is also provided which is added in 2.7 version.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
- Christian Kotte (@ckotte)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
options:
capabilities:
description:
- Gather information about general capabilities (Auto negotiation, Wake On LAN, and Network I/O Control).
type: bool
default: false
directpath_io:
description:
- Gather information about DirectPath I/O capabilities and configuration.
type: bool
default: false
sriov:
description:
- Gather information about SR-IOV capabilities and configuration.
type: bool
default: false
esxi_hostname:
description:
- Name of the host system to work with.
- Vmnic information about this ESXi server will be returned.
- This parameter is required if C(cluster_name) is not specified.
type: str
cluster_name:
description:
- Name of the cluster from which all host systems will be used.
- Vmnic information about each ESXi server will be returned for the given cluster.
- This parameter is required if C(esxi_hostname) is not specified.
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather info about vmnics of all ESXi Host in the given Cluster
vmware_host_vmnic_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: '{{ cluster_name }}'
delegate_to: localhost
register: cluster_host_vmnics
- name: Gather info about vmnics of an ESXi Host
vmware_host_vmnic_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
esxi_hostname: '{{ esxi_hostname }}'
delegate_to: localhost
register: host_vmnics
'''
RETURN = r'''
hosts_vmnics_info:
description:
- dict with hostname as key and dict with vmnics information as value.
- for C(num_vmnics), only NICs starting with vmnic are counted. NICs like vusb* are not counted.
- details about vswitch and dvswitch was added in version 2.7.
- details about vmnics was added in version 2.8.
returned: hosts_vmnics_info
type: dict
sample:
{
"10.76.33.204": {
"all": [
"vmnic0",
"vmnic1"
],
"available": [],
"dvswitch": {
"dvs_0002": [
"vmnic1"
]
},
"num_vmnics": 2,
"used": [
"vmnic1",
"vmnic0"
],
"vmnic_details": [
{
"actual_duplex": "Full Duplex",
"actual_speed": 10000,
"adapter": "Intel(R) 82599 10 Gigabit Dual Port Network Connection",
"configured_duplex": "Auto negotiate",
"configured_speed": "Auto negotiate",
"device": "vmnic0",
"driver": "ixgbe",
"location": "0000:01:00.0",
"mac": "aa:bb:cc:dd:ee:ff",
"status": "Connected",
},
{
"actual_duplex": "Full Duplex",
"actual_speed": 10000,
"adapter": "Intel(R) 82599 10 Gigabit Dual Port Network Connection",
"configured_duplex": "Auto negotiate",
"configured_speed": "Auto negotiate",
"device": "vmnic1",
"driver": "ixgbe",
"location": "0000:01:00.1",
"mac": "ab:ba:cc:dd:ee:ff",
"status": "Connected",
},
],
"vswitch": {
"vSwitch0": [
"vmnic0"
]
}
}
}
'''
try:
from pyVmomi import vim
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi, get_all_objs
class HostVmnicMgr(PyVmomi):
"""Class to manage vmnic info"""
def __init__(self, module):
super(HostVmnicMgr, self).__init__(module)
self.capabilities = self.params.get('capabilities')
self.directpath_io = self.params.get('directpath_io')
self.sriov = self.params.get('sriov')
cluster_name = self.params.get('cluster_name', None)
esxi_host_name = self.params.get('esxi_hostname', None)
self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
if not self.hosts:
self.module.fail_json(msg="Failed to find host system.")
def find_dvs_by_uuid(self, uuid=None):
"""Find DVS by it's UUID"""
dvs_obj = None
if uuid is None:
return dvs_obj
dvswitches = get_all_objs(self.content, [vim.DistributedVirtualSwitch])
for dvs in dvswitches:
if dvs.uuid == uuid:
dvs_obj = dvs
break
return dvs_obj
def gather_host_vmnic_info(self):
"""Gather vmnic info"""
hosts_vmnic_info = {}
for host in self.hosts:
host_vmnic_info = dict(all=[], available=[], used=[], vswitch=dict(), dvswitch=dict())
host_nw_system = host.configManager.networkSystem
if host_nw_system:
nw_config = host_nw_system.networkConfig
vmnics = [pnic.device for pnic in nw_config.pnic if pnic.device.startswith('vmnic')]
host_vmnic_info['all'] = [pnic.device for pnic in nw_config.pnic]
host_vmnic_info['num_vmnics'] = len(vmnics)
host_vmnic_info['vmnic_details'] = []
for pnic in host.config.network.pnic:
pnic_info = dict()
if pnic.device.startswith('vmnic'):
if pnic.pci:
pnic_info['location'] = pnic.pci
for pci_device in host.hardware.pciDevice:
if pci_device.id == pnic.pci:
pnic_info['adapter'] = pci_device.vendorName + ' ' + pci_device.deviceName
break
else:
pnic_info['location'] = 'PCI'
pnic_info['device'] = pnic.device
pnic_info['driver'] = pnic.driver
if pnic.linkSpeed:
pnic_info['status'] = 'Connected'
pnic_info['actual_speed'] = pnic.linkSpeed.speedMb
pnic_info['actual_duplex'] = 'Full Duplex' if pnic.linkSpeed.duplex else 'Half Duplex'
else:
pnic_info['status'] = 'Disconnected'
pnic_info['actual_speed'] = 'N/A'
pnic_info['actual_duplex'] = 'N/A'
if pnic.spec.linkSpeed:
pnic_info['configured_speed'] = pnic.spec.linkSpeed.speedMb
pnic_info['configured_duplex'] = 'Full Duplex' if pnic.spec.linkSpeed.duplex else 'Half Duplex'
else:
pnic_info['configured_speed'] = 'Auto negotiate'
pnic_info['configured_duplex'] = 'Auto negotiate'
pnic_info['mac'] = pnic.mac
# General NIC capabilities
if self.capabilities:
pnic_info['nioc_status'] = 'Allowed' if pnic.resourcePoolSchedulerAllowed else 'Not allowed'
pnic_info['auto_negotiation_supported'] = pnic.autoNegotiateSupported
pnic_info['wake_on_lan_supported'] = pnic.wakeOnLanSupported
# DirectPath I/O and SR-IOV capabilities and configuration
if self.directpath_io:
pnic_info['directpath_io_supported'] = pnic.vmDirectPathGen2Supported
if self.directpath_io or self.sriov:
if pnic.pci:
for pci_device in host.configManager.pciPassthruSystem.pciPassthruInfo:
if pci_device.id == pnic.pci:
if self.directpath_io:
pnic_info['passthru_enabled'] = pci_device.passthruEnabled
pnic_info['passthru_capable'] = pci_device.passthruCapable
pnic_info['passthru_active'] = pci_device.passthruActive
if self.sriov:
try:
if pci_device.sriovCapable:
pnic_info['sriov_status'] = (
'Enabled' if pci_device.sriovEnabled else 'Disabled'
)
pnic_info['sriov_active'] = \
pci_device.sriovActive
pnic_info['sriov_virt_functions'] = \
pci_device.numVirtualFunction
pnic_info['sriov_virt_functions_requested'] = \
pci_device.numVirtualFunctionRequested
pnic_info['sriov_virt_functions_supported'] = \
pci_device.maxVirtualFunctionSupported
else:
pnic_info['sriov_status'] = 'Not supported'
except AttributeError:
pnic_info['sriov_status'] = 'Not supported'
host_vmnic_info['vmnic_details'].append(pnic_info)
vswitch_vmnics = []
proxy_switch_vmnics = []
if nw_config.vswitch:
for vswitch in nw_config.vswitch:
host_vmnic_info['vswitch'][vswitch.name] = []
# Workaround for "AttributeError: 'NoneType' object has no attribute 'nicDevice'"
# this issue doesn't happen every time; vswitch.spec.bridge.nicDevice exists!
try:
for vnic in vswitch.spec.bridge.nicDevice:
vswitch_vmnics.append(vnic)
host_vmnic_info['vswitch'][vswitch.name].append(vnic)
except AttributeError:
pass
if nw_config.proxySwitch:
for proxy_config in nw_config.proxySwitch:
dvs_obj = self.find_dvs_by_uuid(uuid=proxy_config.uuid)
if dvs_obj:
host_vmnic_info['dvswitch'][dvs_obj.name] = []
for proxy_nic in proxy_config.spec.backing.pnicSpec:
proxy_switch_vmnics.append(proxy_nic.pnicDevice)
if dvs_obj:
host_vmnic_info['dvswitch'][dvs_obj.name].append(proxy_nic.pnicDevice)
used_vmics = proxy_switch_vmnics + vswitch_vmnics
host_vmnic_info['used'] = used_vmics
host_vmnic_info['available'] = [pnic.device for pnic in nw_config.pnic if pnic.device not in used_vmics]
hosts_vmnic_info[host.name] = host_vmnic_info
return hosts_vmnic_info
def main():
"""Main"""
argument_spec = vmware_argument_spec()
argument_spec.update(
cluster_name=dict(type='str', required=False),
esxi_hostname=dict(type='str', required=False),
capabilities=dict(type='bool', required=False, default=False),
directpath_io=dict(type='bool', required=False, default=False),
sriov=dict(type='bool', required=False, default=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'esxi_hostname'],
],
supports_check_mode=True,
)
host_vmnic_mgr = HostVmnicMgr(module)
module.exit_json(changed=False, hosts_vmnics_info=host_vmnic_mgr.gather_host_vmnic_info())
if __name__ == "__main__":
main()

View file

@ -0,0 +1,139 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: vmware_local_role_info
short_description: Gather info about local roles on an ESXi host
description:
- This module can be used to gather information about local role info on an ESXi host
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on ESXi 6.5
- Be sure that the ESXi user used for login, has the appropriate rights to view roles
- The module returns a list of dict in version 2.8 and above.
requirements:
- "python >= 2.6"
- PyVmomi
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
- name: Gather info about local role from an ESXi
vmware_local_role_info:
hostname: '{{ esxi_hostname }}'
username: '{{ esxi_username }}'
password: '{{ esxi_password }}'
register: fact_details
delegate_to: localhost
- name: Get Admin privileges
set_fact:
admin_priv: "{{ fact_details.local_role_info['Admin']['privileges'] }}"
- debug:
msg: "{{ admin_priv }}"
'''
RETURN = r'''
local_role_info:
description: Info about role present on ESXi host
returned: always
type: dict
sample: [
{
"privileges": [
"Alarm.Acknowledge",
"Alarm.Create",
"Alarm.Delete",
"Alarm.DisableActions",
],
"role_id": -12,
"role_info_label": "Ansible User",
"role_info_summary": "Ansible Automation user",
"role_name": "AnsiUser1",
"role_system": true
},
{
"privileges": [],
"role_id": -5,
"role_info_label": "No access",
"role_info_summary": "Used for restricting granted access",
"role_name": "NoAccess",
"role_system": true
},
{
"privileges": [
"System.Anonymous",
"System.View"
],
"role_id": -3,
"role_info_label": "View",
"role_info_summary": "Visibility access (cannot be granted)",
"role_name": "View",
"role_system": true
}
]
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec
class VMwareLocalRoleInfo(PyVmomi):
"""Class to manage local role info"""
def __init__(self, module):
super(VMwareLocalRoleInfo, self).__init__(module)
self.module = module
self.params = module.params
if self.content.authorizationManager is None:
self.module.fail_json(
msg="Failed to get local authorization manager settings.",
details="It seems that '%s' is a vCenter server instead of an ESXi server" % self.params['hostname']
)
def gather_local_role_info(self):
"""Gather info about local roles"""
results = list()
for role in self.content.authorizationManager.roleList:
results.append(
dict(
role_name=role.name,
role_id=role.roleId,
privileges=[priv_name for priv_name in role.privilege],
role_system=role.system,
role_info_label=role.info.label,
role_info_summary=role.info.summary,
)
)
self.module.exit_json(changed=False, local_role_info=results)
def main():
"""Main"""
argument_spec = vmware_argument_spec()
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True)
vmware_local_role_info = VMwareLocalRoleInfo(module)
vmware_local_role_info.gather_local_role_info()
if __name__ == '__main__':
main()

View file

@ -0,0 +1,163 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# Copyright: (c) 2018, Christian Kotte <christian.kotte@gmx.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: vmware_local_user_info
short_description: Gather info about users on the given ESXi host
description:
- This module can be used to gather information about users present on the given ESXi host system in VMware infrastructure.
- All variables and VMware object names are case sensitive.
- User must hold the 'Authorization.ModifyPermissions' privilege to invoke this module.
version_added: "2.9"
author:
- Abhijeet Kasurde (@Akasurde)
- Christian Kotte (@ckotte)
notes:
- Tested on ESXi 6.5
requirements:
- "python >= 2.6"
- PyVmomi
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather info about all Users on given ESXi host system
vmware_local_user_info:
hostname: '{{ esxi_hostname }}'
username: '{{ esxi_username }}'
password: '{{ esxi_password }}'
delegate_to: localhost
register: all_user_info
'''
RETURN = r'''
local_user_info:
description: metadata about all local users
returned: always
type: dict
sample: [
{
"role": "admin",
"description": "Administrator",
"group": false,
"user_id": 0,
"user_name": "root",
"shell_access": true
},
{
"role": "admin",
"description": "DCUI User",
"group": false,
"user_id": 100,
"user_name": "dcui",
"shell_access": false
},
]
'''
try:
from pyVmomi import vmodl
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec
from ansible.module_utils._text import to_native
class VMwareUserInfoManager(PyVmomi):
"""Class to manage local user info"""
def __init__(self, module):
super(VMwareUserInfoManager, self).__init__(module)
if self.is_vcenter():
self.module.fail_json(
msg="Failed to get local account manager settings.",
details="It seems that '%s' is a vCenter server instead of an ESXi server" % self.module.params['hostname']
)
def gather_user_info(self):
"""Gather info about local users"""
results = dict(changed=False, local_user_info=[])
search_string = ''
exact_match = False
find_users = True
find_groups = False
user_accounts = self.content.userDirectory.RetrieveUserGroups(
None, search_string, None, None, exact_match, find_users, find_groups
)
if user_accounts:
for user in user_accounts:
temp_user = dict()
temp_user['user_name'] = user.principal
temp_user['description'] = user.fullName
temp_user['group'] = user.group
temp_user['user_id'] = user.id
temp_user['shell_access'] = user.shellAccess
temp_user['role'] = None
try:
permissions = self.content.authorizationManager.RetrieveEntityPermissions(
entity=self.content.rootFolder,
inherited=False
)
except vmodl.fault.ManagedObjectNotFound as not_found:
self.module.fail_json(
msg="The entity doesn't exist" % to_native(not_found)
)
for permission in permissions:
if permission.principal == user.principal:
temp_user['role'] = self.get_role_name(permission.roleId, self.content.authorizationManager.roleList)
break
results['local_user_info'].append(temp_user)
self.module.exit_json(**results)
@staticmethod
def get_role_name(role_id, role_list):
"""Get role name from role ID"""
role_name = None
# Default role: No access
if role_id == -5:
role_name = 'no-access'
# Default role: Read-only
elif role_id == -2:
role_name = 'read-only'
# Default role: Administrator
elif role_id == -1:
role_name = 'admin'
# Custom roles
else:
for role in role_list:
if role.roleId == role_id:
role_name = role.name
break
return role_name
def main():
"""Main"""
argument_spec = vmware_argument_spec()
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True)
vmware_local_user_info = VMwareUserInfoManager(module)
vmware_local_user_info.gather_user_info()
if __name__ == '__main__':
main()

View file

@ -0,0 +1,224 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# Copyright: (c) 2018, Christian Kotte <christian.kotte@gmx.de>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_portgroup_info
short_description: Gathers info about an ESXi host's Port Group configuration
description:
- This module can be used to gather information about an ESXi host's Port Group configuration when ESXi hostname or Cluster name is given.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
- Christian Kotte (@ckotte)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
options:
policies:
description:
- Gather information about Security, Traffic Shaping, as well as Teaming and failover.
- The property C(ts) stands for Traffic Shaping and C(lb) for Load Balancing.
type: bool
default: false
cluster_name:
description:
- Name of the cluster.
- Info will be returned for all hostsystem belonging to this cluster name.
- If C(esxi_hostname) is not given, this parameter is required.
type: str
esxi_hostname:
description:
- ESXi hostname to gather information from.
- If C(cluster_name) is not given, this parameter is required.
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather portgroup info about all ESXi Host in given Cluster
vmware_portgroup_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: '{{ cluster_name }}'
delegate_to: localhost
- name: Gather portgroup info about ESXi Host system
vmware_portgroup_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
esxi_hostname: '{{ esxi_hostname }}'
delegate_to: localhost
'''
RETURN = r'''
hosts_portgroup_info:
description: metadata about host's portgroup configuration
returned: on success
type: dict
sample: {
"esx01": [
{
"failback": true,
"failover_active": ["vmnic0", "vmnic1"],
"failover_standby": [],
"failure_detection": "link_status_only",
"lb": "loadbalance_srcid",
"notify": true,
"portgroup": "Management Network",
"security": [false, false, false],
"ts": "No override",
"vlan_id": 0,
"vswitch": "vSwitch0"
},
{
"failback": true,
"failover_active": ["vmnic2"],
"failover_standby": ["vmnic3"],
"failure_detection": "No override",
"lb": "No override",
"notify": true,
"portgroup": "vMotion",
"security": [false, false, false],
"ts": "No override",
"vlan_id": 33,
"vswitch": "vSwitch1"
}
]
}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi
class PortgroupInfoManager(PyVmomi):
"""Class to manage Port Group info"""
def __init__(self, module):
super(PortgroupInfoManager, self).__init__(module)
cluster_name = self.params.get('cluster_name', None)
esxi_host_name = self.params.get('esxi_hostname', None)
self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
if not self.hosts:
self.module.fail_json(msg="Failed to find host system.")
self.policies = self.params.get('policies')
@staticmethod
def normalize_pg_info(portgroup_obj, policy_info):
"""Create Port Group information"""
pg_info_dict = dict()
spec = portgroup_obj.spec
pg_info_dict['portgroup'] = spec.name
pg_info_dict['vlan_id'] = spec.vlanId
pg_info_dict['vswitch'] = spec.vswitchName
if policy_info:
# Security info
if spec.policy.security:
promiscuous_mode = spec.policy.security.allowPromiscuous
mac_changes = spec.policy.security.macChanges
forged_transmits = spec.policy.security.forgedTransmits
pg_info_dict['security'] = (
["No override" if promiscuous_mode is None else promiscuous_mode,
"No override" if mac_changes is None else mac_changes,
"No override" if forged_transmits is None else forged_transmits]
)
else:
pg_info_dict['security'] = ["No override", "No override", "No override"]
# Traffic Shaping info
if spec.policy.shapingPolicy and spec.policy.shapingPolicy.enabled is not None:
pg_info_dict['ts'] = portgroup_obj.spec.policy.shapingPolicy.enabled
else:
pg_info_dict['ts'] = "No override"
# Teaming and failover info
if spec.policy.nicTeaming:
if spec.policy.nicTeaming.policy is None:
pg_info_dict['lb'] = "No override"
else:
pg_info_dict['lb'] = spec.policy.nicTeaming.policy
if spec.policy.nicTeaming.notifySwitches is None:
pg_info_dict['notify'] = "No override"
else:
pg_info_dict['notify'] = spec.policy.nicTeaming.notifySwitches
if spec.policy.nicTeaming.rollingOrder is None:
pg_info_dict['failback'] = "No override"
else:
pg_info_dict['failback'] = not spec.policy.nicTeaming.rollingOrder
if spec.policy.nicTeaming.nicOrder is None:
pg_info_dict['failover_active'] = "No override"
pg_info_dict['failover_standby'] = "No override"
else:
pg_info_dict['failover_active'] = spec.policy.nicTeaming.nicOrder.activeNic
pg_info_dict['failover_standby'] = spec.policy.nicTeaming.nicOrder.standbyNic
if spec.policy.nicTeaming.failureCriteria and spec.policy.nicTeaming.failureCriteria.checkBeacon is None:
pg_info_dict['failure_detection'] = "No override"
else:
if spec.policy.nicTeaming.failureCriteria.checkBeacon:
pg_info_dict['failure_detection'] = "beacon_probing"
else:
pg_info_dict['failure_detection'] = "link_status_only"
else:
pg_info_dict['lb'] = "No override"
pg_info_dict['notify'] = "No override"
pg_info_dict['failback'] = "No override"
pg_info_dict['failover_active'] = "No override"
pg_info_dict['failover_standby'] = "No override"
pg_info_dict['failure_detection'] = "No override"
return pg_info_dict
def gather_host_portgroup_info(self):
"""Gather Port Group info per ESXi host"""
hosts_pg_info = dict()
for host in self.hosts:
pgs = host.config.network.portgroup
hosts_pg_info[host.name] = []
for portgroup in pgs:
hosts_pg_info[host.name].append(
self.normalize_pg_info(portgroup_obj=portgroup, policy_info=self.policies)
)
return hosts_pg_info
def main():
"""Main"""
argument_spec = vmware_argument_spec()
argument_spec.update(
cluster_name=dict(type='str', required=False),
esxi_hostname=dict(type='str', required=False),
policies=dict(type='bool', required=False, default=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'esxi_hostname'],
],
supports_check_mode=True
)
host_pg_mgr = PortgroupInfoManager(module)
module.exit_json(changed=False, hosts_portgroup_info=host_pg_mgr.gather_host_portgroup_info())
if __name__ == "__main__":
main()

View file

@ -0,0 +1,140 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_resource_pool_info
short_description: Gathers info about resource pool information
description:
- This module can be used to gather information about all resource configuration information.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather resource pool info about all resource pools available
vmware_resource_pool_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
register: rp_info
delegate_to: localhost
'''
RETURN = r'''
resource_pool_info:
description: metadata about resource pool configuration
returned: on success
type: list
sample: [
{
"cpu_allocation_expandable_reservation": false,
"cpu_allocation_limit": 4121,
"cpu_allocation_overhead_limit": null,
"cpu_allocation_reservation": 4121,
"cpu_allocation_shares": 9000,
"cpu_allocation_shares_level": "custom",
"mem_allocation_expandable_reservation": false,
"mem_allocation_limit": 961,
"mem_allocation_overhead_limit": null,
"mem_allocation_reservation": 961,
"mem_allocation_shares": 9000,
"mem_allocation_shares_level": "custom",
"name": "Resources",
"overall_status": "green",
"owner": "DC0_H0",
"runtime_cpu_max_usage": 4121,
"runtime_cpu_overall_usage": 0,
"runtime_cpu_reservation_used": 0,
"runtime_cpu_reservation_used_vm": 0,
"runtime_cpu_unreserved_for_pool": 4121,
"runtime_cpu_unreserved_for_vm": 4121,
"runtime_memory_max_usage": 1007681536,
"runtime_memory_overall_usage": 0,
"runtime_memory_reservation_used": 0,
"runtime_memory_reservation_used_vm": 0,
"runtime_memory_unreserved_for_pool": 1007681536,
"runtime_memory_unreserved_for_vm": 1007681536
},
]
'''
try:
from pyVmomi import vim
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi, get_all_objs
class ResourcePoolInfoManager(PyVmomi):
def __init__(self, module):
super(ResourcePoolInfoManager, self).__init__(module)
def gather_rp_info(self):
resource_pool_info = []
rps = get_all_objs(self.content, [vim.ResourcePool])
for rp in rps:
tmp_info = dict(
name=rp.name,
cpu_allocation_reservation=rp.config.cpuAllocation.reservation,
cpu_allocation_expandable_reservation=rp.config.cpuAllocation.expandableReservation,
cpu_allocation_limit=rp.config.cpuAllocation.limit,
cpu_allocation_shares=rp.config.cpuAllocation.shares.shares,
cpu_allocation_shares_level=rp.config.cpuAllocation.shares.level,
cpu_allocation_overhead_limit=rp.config.cpuAllocation.overheadLimit,
mem_allocation_reservation=rp.config.memoryAllocation.reservation,
mem_allocation_expandable_reservation=rp.config.memoryAllocation.expandableReservation,
mem_allocation_limit=rp.config.memoryAllocation.limit,
mem_allocation_shares=rp.config.memoryAllocation.shares.shares,
mem_allocation_shares_level=rp.config.memoryAllocation.shares.level,
mem_allocation_overhead_limit=rp.config.memoryAllocation.overheadLimit,
owner=rp.owner.name,
overall_status=rp.summary.runtime.overallStatus,
runtime_cpu_reservation_used=rp.summary.runtime.cpu.reservationUsed,
runtime_cpu_reservation_used_vm=rp.summary.runtime.cpu.reservationUsedForVm,
runtime_cpu_unreserved_for_pool=rp.summary.runtime.cpu.unreservedForPool,
runtime_cpu_unreserved_for_vm=rp.summary.runtime.cpu.unreservedForVm,
runtime_cpu_overall_usage=rp.summary.runtime.cpu.overallUsage,
runtime_cpu_max_usage=rp.summary.runtime.cpu.maxUsage,
runtime_memory_reservation_used=rp.summary.runtime.memory.reservationUsed,
runtime_memory_reservation_used_vm=rp.summary.runtime.memory.reservationUsedForVm,
runtime_memory_unreserved_for_pool=rp.summary.runtime.memory.unreservedForPool,
runtime_memory_unreserved_for_vm=rp.summary.runtime.memory.unreservedForVm,
runtime_memory_overall_usage=rp.summary.runtime.memory.overallUsage,
runtime_memory_max_usage=rp.summary.runtime.memory.maxUsage,
)
resource_pool_info.append(tmp_info)
return resource_pool_info
def main():
argument_spec = vmware_argument_spec()
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
vmware_rp_mgr = ResourcePoolInfoManager(module)
module.exit_json(changed=False, resource_pool_info=vmware_rp_mgr.gather_rp_info())
if __name__ == "__main__":
main()

View file

@ -17,12 +17,13 @@ ANSIBLE_METADATA = {
DOCUMENTATION = r'''
---
module: vmware_tag_facts
short_description: Manage VMware tag facts
module: vmware_tag_info
short_description: Manage VMware tag info
description:
- This module can be used to collect facts about VMware tags.
- This module can be used to collect information about VMware tags.
- Tag feature is introduced in vSphere 6 version, so this module is not supported in the earlier versions of vSphere.
- All variables and VMware object names are case sensitive.
- This module was called C(vmware_tag_facts) before Ansible 2.9. The usage did not change.
version_added: '2.6'
author:
- Abhijeet Kasurde (@Akasurde)
@ -36,15 +37,15 @@ extends_documentation_fragment: vmware_rest_client.documentation
'''
EXAMPLES = r'''
- name: Get facts about tag
vmware_tag_facts:
- name: Get info about tag
vmware_tag_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
delegate_to: localhost
- name: Get category id from the given tag
vmware_tag_facts:
vmware_tag_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
@ -87,10 +88,10 @@ from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware_rest_client import VmwareRestClient
class VmTagFactManager(VmwareRestClient):
class VmTagInfoManager(VmwareRestClient):
def __init__(self, module):
"""Constructor."""
super(VmTagFactManager, self).__init__(module)
super(VmTagInfoManager, self).__init__(module)
self.tag_service = self.api_client.tagging.Tag
self.global_tags = dict()
@ -112,9 +113,11 @@ def main():
argument_spec = VmwareRestClient.vmware_client_argument_spec()
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True)
if module._name == 'vmware_tag_facts':
module.deprecate("The 'vmware_tag_facts' module has been renamed to 'vmware_tag_info'", version='2.13')
vmware_tag_facts = VmTagFactManager(module)
vmware_tag_facts.get_all_tags()
vmware_tag_info = VmTagInfoManager(module)
vmware_tag_info.get_all_tags()
if __name__ == '__main__':

View file

@ -0,0 +1,183 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2015, Joseph Callen <jcallen () csc.com>
# Copyright: (c) 2018, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: vmware_target_canonical_info
short_description: Return canonical (NAA) from an ESXi host system
description:
- This module can be used to gather information about canonical (NAA) from an ESXi host based on SCSI target ID.
version_added: "2.9"
author:
- Joseph Callen (@jcpowermac)
- Abhijeet Kasurde (@Akasurde)
notes:
requirements:
- Tested on vSphere 5.5 and 6.5
- PyVmomi installed
options:
target_id:
description:
- The target id based on order of scsi device.
- version 2.6 onwards, this parameter is optional.
required: False
type: int
cluster_name:
description:
- Name of the cluster.
- Info about all SCSI devices for all host system in the given cluster is returned.
- This parameter is required, if C(esxi_hostname) is not provided.
type: str
esxi_hostname:
description:
- Name of the ESXi host system.
- Info about all SCSI devices for the given ESXi host system is returned.
- This parameter is required, if C(cluster_name) is not provided.
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
- name: Get Canonical name of particular target on particular ESXi host system
vmware_target_canonical_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
target_id: 7
esxi_hostname: esxi_hostname
delegate_to: localhost
- name: Get Canonical name of all target on particular ESXi host system
vmware_target_canonical_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
esxi_hostname: '{{ esxi_hostname }}'
delegate_to: localhost
- name: Get Canonical name of all ESXi hostname on particular Cluster
vmware_target_canonical_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: '{{ cluster_name }}'
delegate_to: localhost
'''
RETURN = r"""
canonical:
description: metadata about SCSI Target device
returned: if host system and target id is given
type: str
sample: "mpx.vmhba0:C0:T0:L0"
scsi_tgt_info:
description: metadata about all SCSI Target devices
returned: if host system or cluster is given
type: dict
sample: {
"DC0_C0_H0": {
"scsilun_canonical": {
"key-vim.host.ScsiDisk-0000000000766d686261303a303a30": "mpx.vmhba0:C0:T0:L0",
"key-vim.host.ScsiLun-0005000000766d686261313a303a30": "mpx.vmhba1:C0:T0:L0"
},
"target_lun_uuid": {
"0": "key-vim.host.ScsiDisk-0000000000766d686261303a303a30"
}
},
"DC0_C0_H1": {
"scsilun_canonical": {
"key-vim.host.ScsiDisk-0000000000766d686261303a303a30": "mpx.vmhba0:C0:T0:L0",
"key-vim.host.ScsiLun-0005000000766d686261313a303a30": "mpx.vmhba1:C0:T0:L0"
},
"target_lun_uuid": {
"0": "key-vim.host.ScsiDisk-0000000000766d686261303a303a30"
}
},
}
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec
class ScsiTargetInfoManager(PyVmomi):
def __init__(self, module):
super(ScsiTargetInfoManager, self).__init__(module)
cluster_name = self.module.params.get('cluster_name')
self.esxi_hostname = self.module.params.get('esxi_hostname')
self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=self.esxi_hostname)
def gather_scsi_device_info(self):
"""
Function to gather information about SCSI target devices
"""
scsi_tgt_info = {}
target_lun_uuid = {}
scsilun_canonical = {}
target_id = self.module.params['target_id']
for host in self.hosts:
# Associate the scsiLun key with the canonicalName (NAA)
for scsilun in host.config.storageDevice.scsiLun:
scsilun_canonical[scsilun.key] = scsilun.canonicalName
# Associate target number with LUN uuid
for target in host.config.storageDevice.scsiTopology.adapter[0].target:
for lun in target.lun:
target_lun_uuid[target.target] = lun.scsiLun
scsi_tgt_info[host.name] = dict(
scsilun_canonical=scsilun_canonical,
target_lun_uuid=target_lun_uuid)
if target_id is not None and self.esxi_hostname is not None:
canonical = ''
temp_lun_data = scsi_tgt_info[self.esxi_hostname]['target_lun_uuid']
if self.esxi_hostname in scsi_tgt_info and \
target_id in temp_lun_data:
temp_scsi_data = scsi_tgt_info[self.esxi_hostname]['scsilun_canonical']
temp_target = temp_lun_data[target_id]
canonical = temp_scsi_data[temp_target]
self.module.exit_json(changed=False, canonical=canonical)
self.module.exit_json(changed=False, scsi_tgt_info=scsi_tgt_info)
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
dict(
target_id=dict(required=False, type='int'),
cluster_name=dict(type='str', required=False),
esxi_hostname=dict(type='str', required=False),
)
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'esxi_hostname'],
],
supports_check_mode=True,
)
scsi_tgt_manager = ScsiTargetInfoManager(module)
scsi_tgt_manager.gather_scsi_device_info()
if __name__ == '__main__':
main()

View file

@ -17,11 +17,12 @@ ANSIBLE_METADATA = {
DOCUMENTATION = r'''
---
module: vmware_vm_facts
short_description: Return basic facts pertaining to a VMware machine guest
module: vmware_vm_info
short_description: Return basic info pertaining to a VMware machine guest
description:
- Return basic facts pertaining to a vSphere or ESXi virtual machine guest.
- Return basic information pertaining to a vSphere or ESXi virtual machine guest.
- Cluster name as fact is added in version 2.7.
- This module was called C(vmware_vm_facts) before Ansible 2.9. The usage did not change.
version_added: '2.0'
author:
- Joseph Callen (@jcpowermac)
@ -29,16 +30,16 @@ author:
- Fedor Vompe (@sumkincpp)
notes:
- Tested on ESXi 6.7, vSphere 5.5 and vSphere 6.5
- From 2.8 and onwards, facts are returned as list of dict instead of dict.
- From 2.8 and onwards, information are returned as list of dict instead of dict.
requirements:
- python >= 2.6
- PyVmomi
options:
vm_type:
description:
- If set to C(vm), then facts are gathered for virtual machines only.
- If set to C(template), then facts are gathered for virtual machine templates only.
- If set to C(all), then facts are gathered for all virtual machines and virtual machine templates.
- If set to C(vm), then information are gathered for virtual machines only.
- If set to C(template), then information are gathered for virtual machine templates only.
- If set to C(all), then information are gathered for all virtual machines and virtual machine templates.
required: False
default: 'all'
choices: [ all, vm, template ]
@ -46,13 +47,13 @@ options:
type: str
show_attribute:
description:
- Attributes related to VM guest shown in facts only when this is set C(true).
- Attributes related to VM guest shown in information only when this is set C(true).
default: no
type: bool
version_added: 2.8
folder:
description:
- Specify a folder location of VMs to gather facts from.
- Specify a folder location of VMs to gather information from.
- 'Examples:'
- ' folder: /ha-datacenter/vm'
- ' folder: ha-datacenter/vm'
@ -76,80 +77,80 @@ extends_documentation_fragment: vmware.documentation
EXAMPLES = r'''
- name: Gather all registered virtual machines
vmware_vm_facts:
vmware_vm_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
delegate_to: localhost
register: vmfacts
register: vminfo
- debug:
var: vmfacts.virtual_machines
var: vminfo.virtual_machines
- name: Gather only registered virtual machine templates
vmware_vm_facts:
vmware_vm_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
vm_type: template
delegate_to: localhost
register: template_facts
register: template_info
- debug:
var: template_facts.virtual_machines
var: template_info.virtual_machines
- name: Gather only registered virtual machines
vmware_vm_facts:
vmware_vm_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
vm_type: vm
delegate_to: localhost
register: vm_facts
register: vm_info
- debug:
var: vm_facts.virtual_machines
var: vm_info.virtual_machines
- name: Get UUID from given VM Name
block:
- name: Get virtual machine facts
vmware_vm_facts:
- name: Get virtual machine info
vmware_vm_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
folder: "/datacenter/vm/folder"
delegate_to: localhost
register: vm_facts
register: vm_info
- debug:
msg: "{{ item.uuid }}"
with_items:
- "{{ vm_facts.virtual_machines | json_query(query) }}"
- "{{ vm_info.virtual_machines | json_query(query) }}"
vars:
query: "[?guest_name=='DC0_H0_VM0']"
- name: Get Tags from given VM Name
block:
- name: Get virtual machine facts
vmware_vm_facts:
- name: Get virtual machine info
vmware_vm_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
folder: "/datacenter/vm/folder"
delegate_to: localhost
register: vm_facts
register: vm_info
- debug:
msg: "{{ item.tags }}"
with_items:
- "{{ vm_facts.virtual_machines | json_query(query) }}"
- "{{ vm_info.virtual_machines | json_query(query) }}"
vars:
query: "[?guest_name=='DC0_H0_VM0']"
'''
RETURN = r'''
virtual_machines:
description: list of dictionary of virtual machines and their facts
description: list of dictionary of virtual machines and their information
returned: success
type: list
sample: [
@ -198,11 +199,11 @@ from ansible.module_utils.vmware import PyVmomi, get_all_objs, vmware_argument_s
from ansible.module_utils.vmware_rest_client import VmwareRestClient
class VmwareVmFacts(PyVmomi):
class VmwareVmInfo(PyVmomi):
def __init__(self, module):
super(VmwareVmFacts, self).__init__(module)
super(VmwareVmInfo, self).__init__(module)
def get_tag_facts(self, vm_dynamic_obj):
def get_tag_info(self, vm_dynamic_obj):
vmware_client = VmwareRestClient(self.module)
return vmware_client.get_tags_for_vm(vm_id=vm_dynamic_obj._moId)
@ -268,7 +269,7 @@ class VmwareVmFacts(PyVmomi):
vm_tags = list()
if self.module.params.get('show_tag'):
vm_tags = self.get_tag_facts(vm)
vm_tags = self.get_tag_info(vm)
virtual_machine = {
"guest_name": summary.config.name,
@ -308,9 +309,11 @@ def main():
argument_spec=argument_spec,
supports_check_mode=True
)
if module._name == 'vmware_vm_facts':
module.deprecate("The 'vmware_vm_facts' module has been renamed to 'vmware_vm_info'", version='2.13')
vmware_vm_facts = VmwareVmFacts(module)
_virtual_machines = vmware_vm_facts.get_all_virtual_machines()
vmware_vm_info = VmwareVmInfo(module)
_virtual_machines = vmware_vm_info.get_all_virtual_machines()
module.exit_json(changed=False, virtual_machines=_virtual_machines)

View file

@ -19,7 +19,7 @@ DOCUMENTATION = r'''
module: vmware_vm_storage_policy_info
short_description: Gather information about vSphere storage profile defined storage policy information.
description:
- Returns basic facts about vSphere storage profiles.
- Returns basic information on vSphere storage profiles.
- A vSphere storage profile defines storage policy information that describes storage requirements
for virtual machines and storage capabilities of storage providers.
version_added: '2.9'
@ -46,7 +46,7 @@ EXAMPLES = r'''
RETURN = r'''
spbm_profiles:
description: list of dictionary of SPBM facts
description: list of dictionary of SPBM info
returned: success
type: list
sample: [

View file

@ -0,0 +1,203 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_vmkernel_info
short_description: Gathers VMKernel info about an ESXi host
description:
- This module can be used to gather VMKernel information about an ESXi host from given ESXi hostname or cluster name.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
options:
cluster_name:
description:
- Name of the cluster.
- VMKernel information about each ESXi server will be returned for the given cluster.
- If C(esxi_hostname) is not given, this parameter is required.
type: str
esxi_hostname:
description:
- ESXi hostname.
- VMKernel information about this ESXi server will be returned.
- If C(cluster_name) is not given, this parameter is required.
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather VMKernel info about all ESXi Host in given Cluster
vmware_vmkernel_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: cluster_name
delegate_to: localhost
register: cluster_host_vmks
- name: Gather VMKernel info about ESXi Host
vmware_vmkernel_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
esxi_hostname: '{{ esxi_hostname }}'
delegate_to: localhost
register: host_vmks
'''
RETURN = r'''
host_vmk_info:
description: metadata about VMKernel present on given host system
returned: success
type: dict
sample:
{
"10.76.33.208": [
{
"device": "vmk0",
"dhcp": true,
"enable_ft": false,
"enable_management": true,
"enable_vmotion": false,
"enable_vsan": false,
"ipv4_address": "10.76.33.28",
"ipv4_subnet_mask": "255.255.255.0",
"key": "key-vim.host.VirtualNic-vmk0",
"mac": "52:54:00:12:50:ce",
"mtu": 1500,
"portgroup": "Management Network",
"stack": "defaultTcpipStack"
},
]
}
'''
try:
from pyVmomi import vim, vmodl
except ImportError:
pass
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi
from ansible.module_utils._text import to_native
class VmkernelInfoManager(PyVmomi):
def __init__(self, module):
super(VmkernelInfoManager, self).__init__(module)
cluster_name = self.params.get('cluster_name', None)
esxi_host_name = self.params.get('esxi_hostname', None)
self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
self.service_type_vmks = dict()
self.get_all_vmks_by_service_type()
def get_all_vmks_by_service_type(self):
"""
Function to return information about service types and VMKernel
"""
for host in self.hosts:
self.service_type_vmks[host.name] = dict(vmotion=[], vsan=[], management=[], faultToleranceLogging=[])
for service_type in self.service_type_vmks[host.name].keys():
vmks_list = self.query_service_type_for_vmks(host, service_type)
self.service_type_vmks[host.name][service_type] = vmks_list
def query_service_type_for_vmks(self, host_system, service_type):
"""
Function to return list of VMKernels
Args:
host_system: Host system managed object
service_type: Name of service type
Returns: List of VMKernel which belongs to that service type
"""
vmks_list = []
query = None
try:
query = host_system.configManager.virtualNicManager.QueryNetConfig(service_type)
except vim.fault.HostConfigFault as config_fault:
self.module.fail_json(msg="Failed to get all VMKs for service type %s due to"
" host config fault : %s" % (service_type, to_native(config_fault.msg)))
except vmodl.fault.InvalidArgument as invalid_argument:
self.module.fail_json(msg="Failed to get all VMKs for service type %s due to"
" invalid arguments : %s" % (service_type, to_native(invalid_argument.msg)))
except Exception as e:
self.module.fail_json(msg="Failed to get all VMKs for service type %s due to"
"%s" % (service_type, to_native(e)))
if not query.selectedVnic:
return vmks_list
selected_vnics = [vnic for vnic in query.selectedVnic]
vnics_with_service_type = [vnic.device for vnic in query.candidateVnic if vnic.key in selected_vnics]
return vnics_with_service_type
def gather_host_vmk_info(self):
hosts_info = {}
for host in self.hosts:
host_vmk_info = []
host_network_system = host.config.network
if host_network_system:
vmks_config = host.config.network.vnic
for vmk in vmks_config:
host_vmk_info.append(dict(
device=vmk.device,
key=vmk.key,
portgroup=vmk.portgroup,
ipv4_address=vmk.spec.ip.ipAddress,
ipv4_subnet_mask=vmk.spec.ip.subnetMask,
dhcp=vmk.spec.ip.dhcp,
mac=vmk.spec.mac,
mtu=vmk.spec.mtu,
stack=vmk.spec.netStackInstanceKey,
enable_vsan=vmk.device in self.service_type_vmks[host.name]['vsan'],
enable_vmotion=vmk.device in self.service_type_vmks[host.name]['vmotion'],
enable_management=vmk.device in self.service_type_vmks[host.name]['management'],
enable_ft=vmk.device in self.service_type_vmks[host.name]['faultToleranceLogging'],
)
)
hosts_info[host.name] = host_vmk_info
return hosts_info
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(
cluster_name=dict(type='str', required=False),
esxi_hostname=dict(type='str', required=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'esxi_hostname'],
],
supports_check_mode=True
)
vmware_vmk_config = VmkernelInfoManager(module)
module.exit_json(changed=False, host_vmk_info=vmware_vmk_config.gather_host_vmk_info())
if __name__ == "__main__":
main()

View file

@ -0,0 +1,157 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_vswitch_info
short_description: Gathers info about an ESXi host's vswitch configurations
description:
- This module can be used to gather information about an ESXi host's vswitch configurations when ESXi hostname or Cluster name is given.
- The vSphere Client shows the value for the number of ports as elastic from vSphere 5.5 and above.
- Other tools like esxcli might show the number of ports as 1536 or 5632.
- See U(https://kb.vmware.com/s/article/2064511) for more details.
version_added: '2.9'
author:
- Abhijeet Kasurde (@Akasurde)
notes:
- Tested on vSphere 6.5
requirements:
- python >= 2.6
- PyVmomi
options:
cluster_name:
description:
- Name of the cluster.
- Info about vswitch belonging to every ESXi host systems under this cluster will be returned.
- If C(esxi_hostname) is not given, this parameter is required.
type: str
esxi_hostname:
description:
- ESXi hostname to gather information from.
- If C(cluster_name) is not given, this parameter is required.
type: str
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = r'''
- name: Gather vswitch info about all ESXi Host in given Cluster
vmware_vswitch_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster_name: '{{ cluster_name }}'
delegate_to: localhost
register: all_hosts_vswitch_info
- name: Gather firewall info about ESXi Host
vmware_vswitch_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
esxi_hostname: '{{ esxi_hostname }}'
delegate_to: localhost
register: all_vswitch_info
'''
RETURN = r'''
hosts_vswitch_info:
description: metadata about host's vswitch configuration
returned: on success
type: dict
sample: {
"10.76.33.218": {
"vSwitch0": {
"mtu": 1500,
"num_ports": 128,
"pnics": [
"vmnic0"
]
},
"vSwitch_0011": {
"mtu": 1500,
"num_ports": 128,
"pnics": [
"vmnic2",
"vmnic1"
]
},
},
}
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.vmware import vmware_argument_spec, PyVmomi
class VswitchInfoManager(PyVmomi):
"""Class to gather vSwitch info"""
def __init__(self, module):
super(VswitchInfoManager, self).__init__(module)
cluster_name = self.params.get('cluster_name', None)
esxi_host_name = self.params.get('esxi_hostname', None)
self.hosts = self.get_all_host_objs(cluster_name=cluster_name, esxi_host_name=esxi_host_name)
if not self.hosts:
self.module.fail_json(msg="Failed to find host system.")
@staticmethod
def serialize_pnics(vswitch_obj):
"""Get pnic names"""
pnics = []
for pnic in vswitch_obj.pnic:
# vSwitch contains all PNICs as string in format of 'key-vim.host.PhysicalNic-vmnic0'
pnics.append(pnic.split("-", 3)[-1])
return pnics
def gather_vswitch_info(self):
"""Gather vSwitch info"""
hosts_vswitch_info = dict()
for host in self.hosts:
network_manager = host.configManager.networkSystem
if network_manager:
temp_switch_dict = dict()
for available_vswitch in network_manager.networkInfo.vswitch:
temp_switch_dict[available_vswitch.name] = dict(
pnics=self.serialize_pnics(available_vswitch),
mtu=available_vswitch.mtu,
# we need to use the spec to get the ports
# otherwise, the output might be different compared to the vswitch config module
# (e.g. 5632 ports instead of 128)
num_ports=available_vswitch.spec.numPorts
)
hosts_vswitch_info[host.name] = temp_switch_dict
return hosts_vswitch_info
def main():
"""Main"""
argument_spec = vmware_argument_spec()
argument_spec.update(
cluster_name=dict(type='str', required=False),
esxi_hostname=dict(type='str', required=False),
)
module = AnsibleModule(
argument_spec=argument_spec,
required_one_of=[
['cluster_name', 'esxi_hostname'],
],
supports_check_mode=True
)
vmware_vswitch_mgr = VswitchInfoManager(module)
module.exit_json(changed=False, hosts_vswitch_info=vmware_vswitch_mgr.gather_vswitch_info())
if __name__ == "__main__":
main()

View file

@ -28,14 +28,14 @@
with_items: "{{ esxi_hosts }}"
- name: The vcenter needs a bit of time to refresh the DS list
vmware_datastore_facts:
vmware_datastore_info:
validate_certs: false
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
cluster: '{{ ccr1 }}'
register: setup_datastore_datatstore_facts
failed_when: setup_datastore_datatstore_facts.datastores|selectattr('type', 'equalto', 'NFS')|list|length != 2
until: setup_datastore_datatstore_facts is succeeded
register: setup_datastore_datatstore_info
failed_when: setup_datastore_datatstore_info.datastores|selectattr('type', 'equalto', 'NFS')|list|length != 2
until: setup_datastore_datatstore_info is succeeded
retries: 60
delay: 1

View file

@ -1,5 +1,5 @@
- name: Get Category facts
vmware_category_facts:
vmware_category_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
@ -10,7 +10,7 @@
set_fact:
cluster_category_id: "{{ item.category_id }}"
with_items:
- "{{ cat_info.tag_category_facts | json_query(query) }}"
- "{{ cat_info.tag_category_info | json_query(query) }}"
vars:
query: "[?category_name=='{{ cluster_category }}']"

View file

@ -0,0 +1,3 @@
shippable/vcenter/group1
cloud/vcenter
needs/target/prepare_vmware_tests

View file

@ -0,0 +1,58 @@
# Test code for the vmware_about_info module.
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
- import_role:
name: prepare_vmware_tests
- name: Get Details about VMware vCenter Server
vmware_about_info: &vmware_about_data
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
register: about
- assert:
that:
- about.about_info["{{ item }}"] is defined
with_items:
- api_type
- api_version
- build
- instance_uuid
- license_product_name
- license_product_version
- locale_build
- locale_version
- os_type
- product_full_name
- product_line_id
- product_name
- vendor
- version
- name: Get Details about VMware vCenter Server in check mode
vmware_about_info:
<<: *vmware_about_data
register: about
check_mode: yes
- assert:
that:
- about.about_info["{{ item }}"] is defined
with_items:
- api_type
- api_version
- build
- instance_uuid
- license_product_name
- license_product_version
- locale_build
- locale_version
- os_type
- product_full_name
- product_line_id
- product_name
- vendor
- version

View file

@ -0,0 +1,3 @@
shippable/vcenter/group1
cloud/vcenter
needs/target/prepare_vmware_tests

View file

@ -0,0 +1,91 @@
# Test code for the vmware_cluster_info module.
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
- import_role:
name: prepare_vmware_tests
- &vc_all_data
name: gather info about all clusters in the given datacenter
vmware_cluster_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: False
datacenter: "{{ dc1 }}"
register: all_cluster_result
- &ensure_vc_all_data
name: ensure info are gathered for all clusters
assert:
that:
- all_cluster_result.clusters
- not all_cluster_result.changed
- <<: *vc_all_data
name: Gather info about all clusters in the given datacenter in check mode
check_mode: yes
- debug: msg=all_cluster_result
- <<: *ensure_vc_all_data
name: Ensure info is gathered for all clusters in check mode
- &vc_cluster_data
name: Gather info about the given cluster
vmware_cluster_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: False
cluster_name: "{{ ccr1 }}"
register: cluster_result
- &ensure_vc_cluster_data
name: Ensure info are gathered for the given cluster
assert:
that:
- cluster_result.clusters
- not cluster_result.changed
- <<: *vc_cluster_data
name: Gather info about the given cluster in check mode
check_mode: yes
- <<: *ensure_vc_cluster_data
name: Ensure info is gathered for the given cluster in check mode
- when: vcsim is not defined
block:
- import_role:
name: prepare_vmware_tests
vars:
setup_category: true
setup_tag: true
- name: Apply tag to cluster
vmware_tag_manager:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
tag_names:
- '{{ cluster_category }}:{{ cluster_tag }}'
state: present
object_name: '{{ ccr1 }}'
object_type: ClusterComputeResource
- name: Get info about cluster
vmware_cluster_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: no
show_tag: True
cluster_name: "{{ ccr1 }}"
register: cluster_info
- assert:
that:
- cluster_info is defined
- cluster_info.clusters[ccr1].tags is defined

View file

@ -32,9 +32,9 @@
password: '{{ vcenter_password }}'
library_id: '{{ content_library }}'
validate_certs: false
register: content_lib_facts
register: content_lib_info
- name: Check Content Library details
assert:
that:
- '{{ content_lib_facts.content_lib_details[0].library_id == content_library }}'
- '{{ content_lib_info.content_lib_details[0].library_id == content_library }}'

View file

@ -0,0 +1,3 @@
shippable/vcenter/group1
cloud/vcenter
needs/target/prepare_vmware_tests

View file

@ -0,0 +1,126 @@
# Test code for the vmware_datastore_info module.
# Copyright (c) 2017, Tim Rightnour <thegarbledone@gmail.com>
# Copyright (c) 2018, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
- import_role:
name: prepare_vmware_tests
vars:
setup_attach_host: true
setup_datastore: true
- when: vcsim is not defined
block:
- name: get list of info about datastores from the ESXi
vmware_datastore_info:
validate_certs: False
hostname: '{{ item }}'
username: '{{ esxi_user }}'
password: '{{ esxi_password }}'
register: info_from_esxi
with_items: "{{ esxi_hosts }}"
- assert:
that:
- "info_from_esxi.results[0].datastores|selectattr('type', 'equalto', 'NFS')|list|length == 2"
- name: get list of info about datastores
vmware_datastore_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ dc1 }}"
gather_nfs_mount_info: true
register: info_from_vcenter_with_dc_filter
- when: vcsim is not defined
block:
- name: get list of info about datastores
vmware_datastore_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
gather_nfs_mount_info: true
register: info_from_vcenter_with_no_filter
- assert:
that:
- "info_from_vcenter_with_dc_filter.datastores|selectattr('type', 'equalto', 'NFS')|list|length == 2"
- "info_from_vcenter_with_no_filter.datastores|selectattr('type', 'equalto', 'NFS')|list|length == 2"
- "info_from_vcenter_with_no_filter.datastores[0]['capacity'] is defined"
# Testcase 0002: Get a full list of datastores in a cluster
- name: get list of info about datastores - no dc
vmware_datastore_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
cluster: "{{ ccr1 }}"
register: datastore_info_0002
- debug:
msg: "{{ datastore_info_0002 }}"
- assert:
that:
- "datastore_info_0002['datastores'][0]['capacity'] is defined"
# Testcase 0003: Find a specific datastore
- name: get list of info about one datastore
vmware_datastore_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ dc1 }}"
name: "{{ ds1 }}"
register: datastore_info_0003
- debug:
msg: "{{ datastore_info_0003 }}"
- assert:
that:
- "datastore_info_0003['datastores'][0]['name'] == ds1"
- "datastore_info_0003['datastores'][0]['capacity'] is defined"
- name: get list of extended info about one datastore
vmware_datastore_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ dc1 }}"
name: "{{ ds1 | basename }}"
gather_nfs_mount_info: True
gather_vmfs_mount_info: True
register: datastore_info_0004
- debug:
msg: "{{ datastore_info_0004 }}"
- assert:
that:
- "datastore_info_0004['datastores'][0]['name'] == ds1"
- "datastore_info_0004['datastores'][0]['capacity'] is defined"
- name: get list of info about one datastore in check mode
vmware_datastore_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ dc1 }}"
name: "{{ ds1 | basename }}"
register: datastore_info_0005
- debug:
msg: "{{ datastore_info_0005 }}"
- assert:
that:
- "datastore_info_0005['datastores'][0]['name'] == ds1"
- "datastore_info_0005['datastores'][0]['capacity'] is defined"

View file

@ -0,0 +1,3 @@
shippable/vcenter/group1
cloud/vcenter
needs/target/prepare_vmware_tests

View file

@ -0,0 +1,44 @@
# Test code for the vmware_drs_group_info module
# Copyright: (c) 2018, Karsten Kaj Jakobsen <kj@patientsky.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
- import_role:
name: prepare_vmware_tests
- when: vcsim is defined or esxi_hosts | length >= 3
block:
- name: Gather DRS group info from given cluster
vmware_drs_group_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
cluster_name: '{{ ccr1 }}'
validate_certs: False
register: drs_group_0001_results
- debug:
var: drs_group_0001_results
- assert:
that:
- "drs_group_0001_results.drs_group_info.DC0_C0 is defined"
- "not drs_group_0001_results.drs_group_info.DC0_C1 is defined"
- "not drs_group_0001_results.changed"
- name: Gather DRS group info from given datacenter
vmware_drs_group_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: '{{ dc1 }}'
validate_certs: False
register: drs_group_0002_results
- debug:
var: drs_group_0002_results
- assert:
that:
- "drs_group_0002_results.drs_group_info.DC0_C0 is defined"
- "not drs_group_0002_results.drs_group_info.DC0_C1 is defined"
- "not drs_group_0002_results.changed"

View file

@ -0,0 +1,3 @@
shippable/vcenter/group1
cloud/vcenter
needs/target/prepare_vmware_tests

View file

@ -0,0 +1,47 @@
# Test code for the vmware_drs_rule_info module
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
- import_role:
name: prepare_vmware_tests
- when: vcsim is defined or esxi_hosts | length >= 3
block:
- import_role:
name: prepare_vmware_tests
vars:
setup_attach_host: true
- name: Gather info about DRS rule from given cluster
vmware_drs_rule_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
cluster_name: DC0_C0
register: drs_rule_0001_results
- debug:
var: drs_rule_0001_results
- assert:
that:
- "drs_rule_0001_results.drs_rule_info is defined"
- "not drs_rule_0001_results.changed"
- name: Gather info about DRS rule from given datacenter
vmware_drs_rule_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: DC0
register: drs_rule_0001_results
- debug:
var: drs_rule_0001_results
- assert:
that:
- "drs_rule_0001_results.drs_rule_info is defined"
- "not drs_rule_0001_results.changed"

View file

@ -0,0 +1,3 @@
cloud/vcenter
shippable/vcenter/group1
needs/target/prepare_vmware_tests

View file

@ -0,0 +1,56 @@
# Test code for the vmware_dvs_portgroup_info module.
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
- import_role:
name: prepare_vmware_tests
vars:
setup_dvswitch: true
- when: vcsim is not defined
block:
- &dvs_info
name: Gather info about DVS portgroup
vmware_dvs_portgroup_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ dc1 }}"
register: dvs_results
- debug:
var: dvs_results
- assert:
that:
- dvs_results.dvs_portgroup_info is defined
- <<: *dvs_info
name: Gather info about DVS portgroup in check mode
check_mode: yes
- debug:
var: dvs_results
- assert:
that:
- dvs_results.dvs_portgroup_info is defined
# Testcase 0002: Get portgroup info for a given dvswitch
- name: get info for a given dvswitch
vmware_dvs_portgroup_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ dc1 }}"
dvswitch: "{{ dvswitch1 }}"
register: dvs_results_0002
- debug:
msg: "{{ dvs_results_0002 }}"
- assert:
that:
- "dvs_results_0002['dvs_portgroup_info']['DVS0'] is defined"

View file

@ -0,0 +1,3 @@
cloud/vcenter
shippable/vcenter/group1
needs/target/prepare_vmware_tests

View file

@ -0,0 +1,51 @@
# Test code for the vmware_guest_boot_info module.
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
- when: vcsim is not defined
block:
- import_role:
name: prepare_vmware_tests
vars:
setup_attach_host: true
setup_datastore: true
setup_virtualmachines: true
- name: Gather info about VM boot order
vmware_guest_boot_info:
validate_certs: no
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
name: "{{ virtual_machines[0].name }}"
register: vm1_info
- debug: var=vm1_info
- name: assert that values are set
assert:
that:
- vm1_info.vm_boot_info.current_boot_delay is defined
- vm1_info.vm_boot_info.current_boot_firmware is defined
- vm1_info.vm_boot_info.current_boot_order is defined
- vm1_info.vm_boot_info.current_boot_retry_delay is defined
- vm1_info.vm_boot_info.current_boot_retry_enabled is defined
- vm1_info.vm_boot_info.current_enter_bios_setup is defined
- name: Gather info about VM boot order in check mode
vmware_guest_boot_info:
validate_certs: no
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
name: "{{ virtual_machines[0].name }}"
check_mode: yes
register: vm1_info
- debug: var=vm1_info
- name: assert that values are set
assert:
that:
- vm1_info.vm_boot_info.current_boot_delay is defined
- vm1_info.vm_boot_info.current_boot_firmware is defined
- vm1_info.vm_boot_info.current_boot_order is defined
- vm1_info.vm_boot_info.current_boot_retry_delay is defined
- vm1_info.vm_boot_info.current_boot_retry_enabled is defined
- vm1_info.vm_boot_info.current_enter_bios_setup is defined

View file

@ -27,13 +27,13 @@
value: 'sample_2_value'
- name: 'sample_3'
value: 'sample_3_value'
register: guest_facts_0001
register: guest_info_0001
- debug: var=guest_facts_0001
- debug: var=guest_info_0001
- assert:
that:
- guest_facts_0001 is changed
- guest_info_0001 is changed
- name: Add custom attribute to the given virtual machine again
vmware_guest_custom_attributes:
@ -52,13 +52,13 @@
value: 'sample_2_value'
- name: 'sample_3'
value: 'sample_3_value'
register: guest_facts_0002
register: guest_info_0002
- debug: var=guest_facts_0002
- debug: var=guest_info_0002
- assert:
that:
- not (guest_facts_0002 is changed)
- not (guest_info_0002 is changed)
- name: Remove custom attribute to the given virtual machine
vmware_guest_custom_attributes:
@ -74,13 +74,13 @@
- name: 'sample_1'
- name: 'sample_2'
- name: 'sample_3'
register: guest_facts_0004
register: guest_info_0004
- debug: msg="{{ guest_facts_0004 }}"
- debug: msg="{{ guest_info_0004 }}"
- assert:
that:
- "guest_facts_0004.changed"
- "guest_info_0004.changed"
# TODO: vcsim returns duplicate values so removing custom attributes
# results in change. vCenter show correct behavior. Commenting this
@ -101,10 +101,10 @@
- name: 'sample_1'
- name: 'sample_2'
- name: 'sample_3'
register: guest_facts_0005
register: guest_info_0005
- debug: var=guest_facts_0005
- debug: var=guest_info_0005
- assert:
that:
- not (guest_facts_0005 is changed)
- not (guest_info_0005 is changed)

View file

@ -0,0 +1,3 @@
cloud/vcenter
shippable/vcenter/group1
needs/target/prepare_vmware_tests

View file

@ -0,0 +1,40 @@
# Test code for the vmware_guest_customization_info module.
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# TODO: vcsim does not support customizationspecmanager related functionalities
- when: vcsim is not defined
block:
- import_role:
name: prepare_vmware_tests
vars:
setup_attach_host: true
setup_datastore: true
setup_virtualmachines: true
- &vm_guest_info
name: Gather info about given customization spec
vmware_guest_customization_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
register: vm_custom_spec_info
- debug:
var: vm_custom_spec_info
- assert:
that:
- "not vm_custom_spec_info.changed"
- <<: *vm_guest_info
name: Gather info about given customization spec in check module
- debug:
var: vm_custom_spec_info
- assert:
that:
- "not vm_custom_spec_info.changed"

View file

@ -0,0 +1,3 @@
cloud/vcenter
shippable/vcenter/group1
needs/target/prepare_vmware_tests

View file

@ -0,0 +1,43 @@
# Test code for the vmware_guest_disk_info module.
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
- import_role:
name: prepare_vmware_tests
vars:
setup_attach_host: true
setup_datastore: true
setup_virtualmachines: true
- name: Gather info about virtual machine disks
vmware_guest_disk_info: &get_info
validate_certs: no
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
name: "{{ virtual_machines[0].name }}"
datacenter: '{{ dc1 }}'
register: disk_info
- debug:
msg: '{{ disk_info }}'
- name: assert that no changes were made
assert:
that:
- "not disk_info.changed"
- name: Gather info about virtual machine disks in check mode
vmware_guest_disk_info:
<<: *get_info
register: disk_info
check_mode: yes
- debug:
msg: '{{ disk_info }}'
- name: assert that no changes were made
assert:
that:
- "not disk_info.changed"

View file

@ -32,7 +32,7 @@
with_items: "{{ folders.results }}"
- name: get fact of the first VM
vmware_guest_facts:
vmware_guest_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
@ -40,9 +40,9 @@
datacenter: "{{ dc1 }}"
name: "{{ virtual_machines[0].name }}"
folder: "{{ virtual_machines[0].folder }}"
register: guest_facts_0001
register: guest_info_0001
- debug: var=guest_facts_0001
- debug: var=guest_info_0001
- name: find folders for each vm using UUID
vmware_guest_find:
@ -50,7 +50,7 @@
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
uuid: "{{ guest_facts_0001['instance']['hw_product_uuid'] }}"
uuid: "{{ guest_info_0001['instance']['hw_product_uuid'] }}"
register: folder_uuid
- debug: var=folder_uuid

View file

@ -0,0 +1,3 @@
shippable/vcenter/group1
cloud/vcenter
needs/target/prepare_vmware_tests

View file

@ -0,0 +1,226 @@
# Test code for the vmware_guest_info module.
# Copyright: (c) 2017, Abhijeet Kasurde <akasurde@redhat.com>
# Copyright: (c) 2018, James E. King III (@jeking3) <jking@apache.org>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
- import_role:
name: prepare_vmware_tests
vars:
setup_attach_host: true
setup_datastore: true
setup_virtualmachines: true
# Testcase 0001: Get details about virtual machines
- name: get list of info about virtual machines
vmware_guest_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ dc1 }}"
name: "{{ virtual_machines[0].name }}"
folder: "{{ virtual_machines[0].folder }}"
register: guest_info_0001
- debug:
var: guest_info_0001
- assert:
that:
- "guest_info_0001['instance']['hw_name'] == virtual_machines[0].name"
- "guest_info_0001['instance']['hw_product_uuid'] is defined"
- "guest_info_0001['instance']['hw_cores_per_socket'] is defined"
- "guest_info_0001['instance']['hw_datastores'] is defined"
- "guest_info_0001['instance']['hw_esxi_host'] is defined"
- "guest_info_0001['instance']['hw_files'] is defined"
- "guest_info_0001['instance']['hw_guest_ha_state'] is defined"
- "guest_info_0001['instance']['hw_is_template'] is defined"
- "guest_info_0001['instance']['hw_folder'] is defined"
- "guest_info_0001['instance']['guest_question'] is defined"
- "guest_info_0001['instance']['guest_consolidation_needed'] is defined"
- "guest_info_0001['instance']['moid'] is defined"
- "guest_info_0001['instance']['vimref'] is defined"
- "'portgroup_portkey' in guest_info_0001['instance']['hw_eth0']"
- "'portgroup_key' in guest_info_0001['instance']['hw_eth0']"
- "guest_info_0001['instance']['instance_uuid'] is defined"
- set_fact: vm1_uuid="{{ guest_info_0001['instance']['hw_product_uuid'] }}"
- set_fact: vm1_instance_uuid="{{ guest_info_0001['instance']['instance_uuid'] }}"
- set_fact: vm1_moid="{{ guest_info_0001['instance']['moid'] }}"
- debug:
var: vm1_uuid
# Testcase 0002: Get details about virtual machines using UUID
- name: get list of info about virtual machines using UUID
vmware_guest_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ dc1 }}"
uuid: "{{ vm1_uuid }}"
register: guest_info_0002
- debug:
var: guest_info_0002
- name: Get specific details about virtual machines using the vsphere output schema
vmware_guest_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ dc1 }}"
uuid: "{{ vm1_uuid }}"
schema: vsphere
properties:
- config.hardware.memoryMB
- guest
- name
- summary.runtime.connectionState
register: guest_info_0002b
- debug:
var: guest_info_0002b
- assert:
that:
- "guest_info_0002['instance']['hw_name'] == virtual_machines[0].name"
- "guest_info_0002['instance']['hw_product_uuid'] is defined"
- "guest_info_0002['instance']['hw_product_uuid'] == vm1_uuid"
- "guest_info_0002['instance']['hw_cores_per_socket'] is defined"
- "guest_info_0002b['instance']['config']['hardware']['memoryMB'] is defined"
- "guest_info_0002b['instance']['config']['hardware']['numCoresPerSocket'] is not defined"
- "guest_info_0002b['instance']['guest']['toolsVersion'] is defined"
- "guest_info_0001['instance']['moid'] is defined"
- "guest_info_0001['instance']['vimref'] is defined"
- "guest_info_0002b['instance']['overallStatus'] is not defined"
# Testcase 0003: Get details about virtual machines without snapshots using UUID
- name: get empty list of snapshots from virtual machine using UUID
vmware_guest_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ dc1 }}"
uuid: "{{ vm1_uuid }}"
register: guest_info_0003
- debug:
var: guest_info_0003
- assert:
that:
- "guest_info_0003['instance']['snapshots']|length == 0"
- "guest_info_0003['instance']['current_snapshot'] is none"
# Testcase 0004: Get details about virtual machines with two snapshots using UUID
- name: Create first snapshot
vmware_guest_snapshot: &vm_snap
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ dc1 }}"
name: "{{ virtual_machines[0].name }}"
folder: "{{ virtual_machines[0].folder }}"
state: present
snapshot_name: snap1
- name: Create second snapshot
vmware_guest_snapshot:
<<: *vm_snap
snapshot_name: snap2
- name: get list of snapshots from virtual machine using UUID
vmware_guest_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ dc1 }}"
uuid: "{{ vm1_uuid }}"
register: guest_info_0004
- debug:
var: guest_info_0004
- assert:
that:
- "guest_info_0004['instance']['snapshots'] is defined"
- "guest_info_0004['instance']['snapshots'][0]['name'] == 'snap1'"
- "guest_info_0004['instance']['snapshots'][1]['name'] == 'snap2'"
- "guest_info_0004['instance']['current_snapshot']['name'] == 'snap2'"
- "guest_info_0004['instance']['hw_folder'] is defined"
# Testcase 0005: Get details about virtual machines using UUID
- name: get list of info about virtual machines using instance UUID
vmware_guest_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ dc1 }}"
uuid: "{{ vm1_instance_uuid }}"
use_instance_uuid: True
register: guest_info_0005
- debug:
msg: "{{ guest_info_0005 }}"
- assert:
that:
- "guest_info_0005['instance']['hw_name'] == virtual_machines[0].name"
- "guest_info_0005['instance']['hw_product_uuid'] is defined"
- "guest_info_0005['instance']['hw_product_uuid'] == vm1_uuid"
- "guest_info_0005['instance']['hw_cores_per_socket'] is defined"
- "guest_info_0005['instance']['hw_datastores'] is defined"
- "guest_info_0005['instance']['hw_esxi_host'] is defined"
- "guest_info_0005['instance']['hw_files'] is defined"
- "guest_info_0005['instance']['hw_guest_ha_state'] is defined"
- "guest_info_0005['instance']['hw_is_template'] is defined"
- "guest_info_0005['instance']['hw_folder'] is defined"
- "guest_info_0005['instance']['guest_question'] is defined"
- "guest_info_0005['instance']['guest_consolidation_needed'] is defined"
- "guest_info_0005['instance']['instance_uuid'] is defined"
- "guest_info_0005['instance']['instance_uuid'] == vm1_instance_uuid"
- "guest_info_0005['instance']['moid'] is defined"
- "guest_info_0005['instance']['vimref'] is defined"
# Testcase 0006: Get details about virtual machines using MoID
- name: get list of information about virtual machines using instance MoID
vmware_guest_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ dc1 }}"
moid: "{{ vm1_moid }}"
use_instance_uuid: True
register: guest_info_0006
- debug:
msg: "{{ guest_info_0006 }}"
- assert:
that:
- "guest_info_0006['instance']['hw_name'] == virtual_machines[0].name"
- "guest_info_0006['instance']['hw_product_uuid'] is defined"
- "guest_info_0006['instance']['hw_product_uuid'] == vm1_uuid"
- "guest_info_0006['instance']['hw_cores_per_socket'] is defined"
- "guest_info_0006['instance']['hw_datastores'] is defined"
- "guest_info_0006['instance']['hw_esxi_host'] is defined"
- "guest_info_0006['instance']['hw_files'] is defined"
- "guest_info_0006['instance']['hw_guest_ha_state'] is defined"
- "guest_info_0006['instance']['hw_is_template'] is defined"
- "guest_info_0006['instance']['hw_folder'] is defined"
- "guest_info_0006['instance']['guest_question'] is defined"
- "guest_info_0006['instance']['guest_consolidation_needed'] is defined"
- "guest_info_0006['instance']['instance_uuid'] is defined"
- "guest_info_0006['instance']['instance_uuid'] == vm1_instance_uuid"
- "guest_info_0006['instance']['moid'] is defined"
- "guest_info_0006['instance']['vimref'] is defined"

View file

@ -31,7 +31,7 @@
name: '{{ virtual_machines[0].name }}'
# Depends-On: https://github.com/ansible/ansible/pull/55237
dest_folder: '{{ dest_folder.result.path }}'
register: vm_facts_0001
register: vm_info_0001
# Testcase 0002: Move vm and get OK status (Already Moved)
@ -45,19 +45,19 @@
datacenter: '{{ dc1 }}'
name: '{{ virtual_machines[0].name }}'
dest_folder: '{{ dest_folder.result.path }}'
register: vm_facts_0002
register: vm_info_0002
- debug:
msg: "{{ vm_facts_0001 }}"
msg: "{{ vm_info_0001 }}"
- debug:
msg: "{{ vm_facts_0002 }}"
msg: "{{ vm_info_0002 }}"
- name: Make sure changes are done
assert:
that:
- vm_facts_0001.changed
- not vm_facts_0002.changed
- vm_info_0001.changed
- not vm_info_0002.changed
- <<: *vm_move
name: Move VM in check mode

View file

@ -18,14 +18,14 @@
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
name: "{{ virtual_machines[0].name }}"
gather_network_facts: true
register: netadapter_facts
gather_network_info: true
register: netadapter_info
- debug: var=netadapter_facts
- debug: var=netadapter_info
- name: get number of existing netowrk adapters
set_fact:
netadapter_num: "{{ netadapter_facts.network_data | length }}"
netadapter_num: "{{ netadapter_info.network_data | length }}"
- name: add new network adapters to virtual machine
vmware_guest_network:

View file

@ -0,0 +1,3 @@
cloud/vcenter
shippable/vcenter/group1
needs/target/prepare_vmware_tests

View file

@ -0,0 +1,28 @@
# Test code for the vmware_host_dns_info module.
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# TODO: vcsim does not support snapshot related functionalities
- import_role:
name: prepare_vmware_tests
vars:
setup_attach_host: true
setup_datastore: true
setup_virtualmachines: true
- name: Gather snapshot info about given virtual machine
vmware_guest_snapshot_info:
validate_certs: False
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ dc1 }}"
name: "{{ virtual_machines[0].name }}"
folder: "{{ virtual_machines[0].folder }}"
register: vm_snapshot_info
- debug: var=vm_snapshot_info
- assert:
that:
- '"guest_snapshots" in vm_snapshot_info'

Some files were not shown because too many files have changed in this diff Show more