1#!/usr/bin/python
2# -*- coding: utf-8 -*-
3#
4# Copyright: (c) 2018, Ansible Project
5# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
6#
7# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
8
9from __future__ import absolute_import, division, print_function
10__metaclass__ = type
11
12ANSIBLE_METADATA = {
13    'metadata_version': '1.1',
14    'status': ['deprecated'],
15    'supported_by': 'community'
16}
17
18DOCUMENTATION = '''
19---
20module: vmware_guest_boot_facts
21deprecated:
22  removed_in: '2.13'
23  why: Deprecated in favour of C(_info) module.
24  alternative: Use M(vmware_guest_boot_info) instead.
25short_description: Gather facts about boot options for the given virtual machine
26description:
27    - Gather facts about boot options for the given virtual machine.
28version_added: 2.7
29author:
30    - Abhijeet Kasurde (@Akasurde)
31notes:
32    - Tested on vSphere 6.5
33requirements:
34    - "python >= 2.6"
35    - PyVmomi
36options:
37   name:
38     description:
39     - Name of the VM to work with.
40     - This is required if C(uuid) or C(moid) parameter is not supplied.
41     type: str
42   uuid:
43     description:
44     - UUID of the instance to manage if known, this is VMware's BIOS UUID by default.
45     - This is required if C(name) or C(moid) parameter is not supplied.
46     type: str
47   moid:
48     description:
49     - Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance.
50     - This is required if C(name) or C(uuid) is not supplied.
51     version_added: '2.9'
52     type: str
53   use_instance_uuid:
54     description:
55     - Whether to use the VMware instance UUID rather than the BIOS UUID.
56     default: no
57     type: bool
58     version_added: '2.8'
59   name_match:
60     description:
61     - If multiple virtual machines matching the name, use the first or last found.
62     default: 'first'
63     choices: ['first', 'last']
64     type: str
65extends_documentation_fragment: vmware.documentation
66'''
67
68EXAMPLES = r'''
69- name: Gather facts about virtual machine's boot order and related parameters
70  vmware_guest_boot_facts:
71    hostname: "{{ vcenter_hostname }}"
72    username: "{{ vcenter_username }}"
73    password: "{{ vcenter_password }}"
74    validate_certs: no
75    name: "{{ vm_name }}"
76  register: vm_boot_order_facts
77
78- name: Gather facts about virtual machine's boot order using MoID
79  vmware_guest_boot_facts:
80    hostname: "{{ vcenter_hostname }}"
81    username: "{{ vcenter_username }}"
82    password: "{{ vcenter_password }}"
83    validate_certs: no
84    moid: "vm-42"
85  register: vm_moid_boot_order_facts
86'''
87
88RETURN = r"""
89vm_boot_facts:
90    description: metadata about boot order of virtual machine
91    returned: always
92    type: dict
93    sample: {
94        "current_boot_order": [
95            "floppy",
96            "disk",
97            "ethernet",
98            "cdrom"
99        ],
100        "current_boot_delay": 2000,
101        "current_boot_retry_delay": 22300,
102        "current_boot_retry_enabled": true,
103        "current_enter_bios_setup": true,
104        "current_boot_firmware": "bios",
105        "current_secure_boot_enabled": false,
106    }
107"""
108
109
110from ansible.module_utils.basic import AnsibleModule
111from ansible.module_utils.vmware import PyVmomi, vmware_argument_spec, find_vm_by_id
112
113try:
114    from pyVmomi import vim, VmomiSupport
115except ImportError:
116    pass
117
118
119class VmBootFactsManager(PyVmomi):
120    def __init__(self, module):
121        super(VmBootFactsManager, self).__init__(module)
122        self.name = self.params['name']
123        self.uuid = self.params['uuid']
124        self.moid = self.params['moid']
125        self.use_instance_uuid = self.params['use_instance_uuid']
126        self.vm = None
127
128    def _get_vm(self):
129        vms = []
130
131        if self.uuid:
132            if self.use_instance_uuid:
133                vm_obj = find_vm_by_id(self.content, vm_id=self.uuid, vm_id_type="use_instance_uuid")
134            else:
135                vm_obj = find_vm_by_id(self.content, vm_id=self.uuid, vm_id_type="uuid")
136            if vm_obj is None:
137                self.module.fail_json(msg="Failed to find the virtual machine with UUID : %s" % self.uuid)
138            vms = [vm_obj]
139
140        elif self.name:
141            objects = self.get_managed_objects_properties(vim_type=vim.VirtualMachine, properties=['name'])
142            for temp_vm_object in objects:
143                if temp_vm_object.obj.name == self.name:
144                    vms.append(temp_vm_object.obj)
145
146        elif self.moid:
147            vm_obj = VmomiSupport.templateOf('VirtualMachine')(self.module.params['moid'], self.si._stub)
148            if vm_obj:
149                vms.append(vm_obj)
150
151        if vms:
152            if self.params.get('name_match') == 'first':
153                self.vm = vms[0]
154            elif self.params.get('name_match') == 'last':
155                self.vm = vms[-1]
156        else:
157            self.module.fail_json(msg="Failed to find virtual machine using %s" % (self.name or self.uuid or self.moid))
158
159    @staticmethod
160    def humanize_boot_order(boot_order):
161        results = []
162        for device in boot_order:
163            if isinstance(device, vim.vm.BootOptions.BootableCdromDevice):
164                results.append('cdrom')
165            elif isinstance(device, vim.vm.BootOptions.BootableDiskDevice):
166                results.append('disk')
167            elif isinstance(device, vim.vm.BootOptions.BootableEthernetDevice):
168                results.append('ethernet')
169            elif isinstance(device, vim.vm.BootOptions.BootableFloppyDevice):
170                results.append('floppy')
171        return results
172
173    def ensure(self):
174        self._get_vm()
175
176        results = dict()
177        if self.vm and self.vm.config:
178            results = dict(
179                current_boot_order=self.humanize_boot_order(self.vm.config.bootOptions.bootOrder),
180                current_boot_delay=self.vm.config.bootOptions.bootDelay,
181                current_enter_bios_setup=self.vm.config.bootOptions.enterBIOSSetup,
182                current_boot_retry_enabled=self.vm.config.bootOptions.bootRetryEnabled,
183                current_boot_retry_delay=self.vm.config.bootOptions.bootRetryDelay,
184                current_boot_firmware=self.vm.config.firmware,
185                current_secure_boot_enabled=self.vm.config.bootOptions.efiSecureBootEnabled
186            )
187
188        self.module.exit_json(changed=False, vm_boot_facts=results)
189
190
191def main():
192    argument_spec = vmware_argument_spec()
193    argument_spec.update(
194        name=dict(type='str'),
195        uuid=dict(type='str'),
196        moid=dict(type='str'),
197        use_instance_uuid=dict(type='bool', default=False),
198        name_match=dict(
199            choices=['first', 'last'],
200            default='first'
201        ),
202    )
203
204    module = AnsibleModule(
205        argument_spec=argument_spec,
206        required_one_of=[
207            ['name', 'uuid', 'moid']
208        ],
209        mutually_exclusive=[
210            ['name', 'uuid', 'moid']
211        ],
212        supports_check_mode=True,
213    )
214
215    pyv = VmBootFactsManager(module)
216    pyv.ensure()
217
218
219if __name__ == '__main__':
220    main()
221