1#!/usr/local/bin/python3.8
2# -*- coding: utf-8 -*-
3#
4# Copyright: (c) 2018, Ansible Project
5# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
6# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8from __future__ import absolute_import, division, print_function
9__metaclass__ = type
10
11ANSIBLE_METADATA = {
12    'metadata_version': '1.1',
13    'status': ['deprecated'],
14    'supported_by': 'community'
15}
16
17DOCUMENTATION = r'''
18---
19module: vmware_guest_customization_facts
20deprecated:
21  removed_at_date: '2021-12-01'
22  why: Deprecated in favour of M(community.vmware.vmware_guest_customization_info) module.
23  alternative: Use M(community.vmware.vmware_guest_customization_info) instead.
24short_description: Gather facts about VM customization specifications
25description:
26    - This module can be used to gather facts about customization specifications.
27    - All parameters and VMware object names are case sensitive.
28author:
29    - Abhijeet Kasurde (@Akasurde)
30notes:
31    - Tested on vSphere 6.0 and 6.5
32requirements:
33    - "python >= 2.6"
34    - PyVmomi
35options:
36   spec_name:
37     description:
38     - Name of customization specification to find.
39     required: False
40     type: str
41extends_documentation_fragment:
42- community.vmware.vmware.documentation
43
44'''
45
46EXAMPLES = r'''
47- name: Gather facts about all customization specification
48  community.vmware.vmware_guest_customization_facts:
49    hostname: "{{ vcenter_hostname }}"
50    username: "{{ vcenter_username }}"
51    password: "{{ vcenter_password }}"
52  delegate_to: localhost
53  register: all_custom_spec_facts
54
55- name: Gather facts about customization specification with the given name
56  community.vmware.vmware_guest_customization_facts:
57    hostname: "{{ vcenter_hostname }}"
58    username: "{{ vcenter_username }}"
59    password: "{{ vcenter_password }}"
60    spec_name: custom_linux_spec
61  delegate_to: localhost
62  register: custom_spec_facts
63'''
64
65RETURN = r'''
66custom_spec_facts:
67    description: metadata about the customization specification
68    returned: always
69    type: dict
70    sample: {
71        "assignip-eee0d684-44b7-457c-8c55-2585590b0d99": {
72            "change_version": "1523438001",
73            "description": "sample description",
74            "dns_server_list": [],
75            "dns_suffix_list": [],
76            "domain": "None",
77            "hostname": "sample1",
78            "hw_clock_utc": null,
79            "last_updated_time": "2018-04-11T09:13:21+00:00",
80            "name": "sample",
81            "nic_setting_map": [
82                {
83                    "dns_domain": null,
84                    "gateway": [],
85                    "ip_address": "192.168.10.10",
86                    "net_bios": null,
87                    "nic_dns_server_list": [],
88                    "primary_wins": null,
89                    "secondry_wins": null,
90                    "subnet_mask": "255.255.255.0"
91                }
92            ],
93            "time_zone": null,
94            "type": "Linux"
95        },
96    }
97'''
98
99try:
100    from pyVmomi import vim
101except ImportError:
102    pass
103
104from ansible.module_utils.basic import AnsibleModule
105from ansible.module_utils._text import to_text
106from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi, vmware_argument_spec
107
108
109class VmwareCustomSpecManger(PyVmomi):
110    def __init__(self, module):
111        super(VmwareCustomSpecManger, self).__init__(module)
112        self.cc_mgr = self.content.customizationSpecManager
113        if self.cc_mgr is None:
114            self.module.fail_json(msg="Failed to get customization spec manager.")
115
116    def gather_custom_spec_facts(self):
117        """
118        Gather facts about customization specifications
119        """
120
121        spec_name = self.params.get('spec_name', None)
122        specs_list = []
123        if spec_name:
124            if self.cc_mgr.DoesCustomizationSpecExist(name=spec_name):
125                specs_list.append(spec_name)
126            else:
127                self.module.fail_json(msg="Unable to find customization specification named '%s'" % spec_name)
128        else:
129            available_specs = self.cc_mgr.info
130            for spec_info in available_specs:
131                specs_list.append(spec_info.name)
132
133        spec_facts = dict()
134        for spec in specs_list:
135            current_spec = self.cc_mgr.GetCustomizationSpec(name=spec)
136            adapter_mapping_list = []
137            for nic in current_spec.spec.nicSettingMap:
138                temp_data = dict(
139                    mac_address=nic.macAddress,
140                    ip_address=nic.adapter.ip.ipAddress,
141                    subnet_mask=nic.adapter.subnetMask,
142                    gateway=list(nic.adapter.gateway),
143                    nic_dns_server_list=list(nic.adapter.dnsServerList),
144                    dns_domain=nic.adapter.dnsDomain,
145                    primary_wins=nic.adapter.primaryWINS,
146                    secondry_wins=nic.adapter.secondaryWINS,
147                    net_bios=nic.adapter.netBIOS,
148                )
149                adapter_mapping_list.append(temp_data)
150
151            current_hostname = None
152            if isinstance(current_spec.spec.identity.hostName, vim.vm.customization.PrefixNameGenerator):
153                current_hostname = current_spec.spec.identity.hostName.base
154            elif isinstance(current_spec.spec.identity.hostName, vim.vm.customization.FixedName):
155                current_hostname = current_spec.spec.identity.hostName.name
156
157            spec_facts[spec] = dict(
158                # Spec
159                name=current_spec.info.name,
160                description=current_spec.info.description,
161                type=current_spec.info.type,
162                last_updated_time=current_spec.info.lastUpdateTime,
163                change_version=current_spec.info.changeVersion,
164                # Identity
165                hostname=current_hostname,
166                domain=current_spec.spec.identity.domain,
167                time_zone=current_spec.spec.identity.timeZone,
168                hw_clock_utc=current_spec.spec.identity.hwClockUTC,
169                # global IP Settings
170                dns_suffix_list=list(current_spec.spec.globalIPSettings.dnsSuffixList),
171                dns_server_list=list(current_spec.spec.globalIPSettings.dnsServerList),
172                # NIC setting map
173                nic_setting_map=adapter_mapping_list,
174            )
175        return spec_facts
176
177
178def main():
179    argument_spec = vmware_argument_spec()
180    argument_spec.update(
181        spec_name=dict(type='str'),
182    )
183    module = AnsibleModule(
184        argument_spec=argument_spec,
185        supports_check_mode=True
186    )
187
188    if module._name in ('vmware_guest_customization_facts', 'community.vmware.vmware_guest_customization_facts'):
189        module.deprecate("The 'vmware_guest_boot_facts' module has been renamed to 'vmware_guest_customization_info'",
190                         version='3.0.0', collection_name='community.vmware')  # was Ansible 2.13
191
192    pyv = VmwareCustomSpecManger(module)
193    try:
194        module.exit_json(custom_spec_facts=pyv.gather_custom_spec_facts())
195    except Exception as exc:
196        module.fail_json(msg="Failed to gather facts with exception : %s" % to_text(exc))
197
198
199if __name__ == '__main__':
200    main()
201