VMware: Refactor vmware_guest_tools_wait (#36098)

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
This commit is contained in:
Abhijeet Kasurde 2018-02-19 13:53:38 +05:30 committed by GitHub
parent b34ab6a0c4
commit 4d18586fc9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,15 +1,16 @@
#!/usr/bin/python #!/usr/bin/python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Copyright (c) 2017 Philippe Dellaert <philippe@dellaert.org> # Copyright (c) 2017 Philippe Dellaert <philippe@dellaert.org>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # 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) from __future__ import (absolute_import, division, print_function)
__metaclass__ = type __metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1', ANSIBLE_METADATA = {
'status': ['preview'], 'metadata_version': '1.1',
'supported_by': 'community'} 'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = ''' DOCUMENTATION = '''
@ -17,7 +18,7 @@ DOCUMENTATION = '''
module: vmware_guest_tools_wait module: vmware_guest_tools_wait
short_description: Wait for VMware tools to become available short_description: Wait for VMware tools to become available
description: description:
- Wait for VMware tools to become available on the VM and return facts. - This module can be used to wait for VMware tools to become available on the given VM and return facts.
version_added: '2.4' version_added: '2.4'
author: author:
- Philippe Dellaert (@pdellaert) <philippe@dellaert.org> - Philippe Dellaert (@pdellaert) <philippe@dellaert.org>
@ -28,34 +29,33 @@ requirements:
- PyVmomi - PyVmomi
options: options:
name: name:
description: description:
- Name of the VM for which to wait until the tools become available. - Name of the VM for which to wait until the tools become available.
- This is required if uuid is not supplied. - This is required if uuid is not supplied.
name_match: name_match:
description: description:
- If multiple VMs match the name, use the first or last found. - If multiple VMs match the name, use the first or last found.
default: 'first' default: 'first'
choices: ['first', 'last'] choices: ['first', 'last']
folder: folder:
description: description:
- Destination folder, absolute or relative path to find an existing guest. - Destination folder, absolute or relative path to find an existing guest.
- This is required if C(name) is supplied. - This is required only, if multiple VMs with same C(name) is found.
- The folder should include the datacenter. ESX's datacenter is C(ha-datacenter). - The folder should include the datacenter. ESX's datacenter is C(ha-datacenter).
- 'Examples:' - 'Examples:'
- ' folder: /ha-datacenter/vm' - ' folder: /ha-datacenter/vm'
- ' folder: ha-datacenter/vm' - ' folder: ha-datacenter/vm'
- ' folder: /datacenter1/vm' - ' folder: /datacenter1/vm'
- ' folder: datacenter1/vm' - ' folder: datacenter1/vm'
- ' folder: /datacenter1/vm/folder1' - ' folder: /datacenter1/vm/folder1'
- ' folder: datacenter1/vm/folder1' - ' folder: datacenter1/vm/folder1'
- ' folder: /folder1/datacenter1/vm' - ' folder: /folder1/datacenter1/vm'
- ' folder: folder1/datacenter1/vm' - ' folder: folder1/datacenter1/vm'
- ' folder: /folder1/datacenter1/vm/folder2' - ' folder: /folder1/datacenter1/vm/folder2'
default: /vm
uuid: uuid:
description: description:
- UUID of the VM for which to wait until the tools become available, if known. This is VMware's unique identifier. - UUID of the VM for which to wait until the tools become available, if known. This is VMware's unique identifier.
- This is required if C(name) is not supplied. - This is required, if C(name) is not supplied.
extends_documentation_fragment: vmware.documentation extends_documentation_fragment: vmware.documentation
''' '''
@ -94,37 +94,19 @@ import time
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
from ansible.module_utils.vmware import connect_to_api, gather_vm_facts, vmware_argument_spec, find_vm_by_id from ansible.module_utils.vmware import PyVmomi, gather_vm_facts, vmware_argument_spec
HAS_PYVMOMI = False
try: try:
import pyVmomi import pyVmomi
from pyVmomi import vim from pyVmomi import vim
HAS_PYVMOMI = True
except ImportError: except ImportError:
pass pass
class PyVmomiHelper(object): class PyVmomiHelper(PyVmomi):
def __init__(self, module): def __init__(self, module):
if not HAS_PYVMOMI: super(PyVmomiHelper, self).__init__(module)
module.fail_json(msg='pyvmomi module required')
self.module = module
self.params = module.params
self.content = connect_to_api(self.module)
def getvm(self, name=None, uuid=None, folder=None):
vm = None
match_first = False
if uuid:
vm = find_vm_by_id(self.content, vm_id=uuid, vm_id_type="uuid")
elif folder and name:
if self.params['name_match'] == 'first':
match_first = True
vm = find_vm_by_id(self.content, vm_id=name, vm_id_type="inventory_path", folder=folder, match_first=match_first)
return vm
def gather_facts(self, vm): def gather_facts(self, vm):
return gather_vm_facts(self.content, vm) return gather_vm_facts(self.content, vm)
@ -133,9 +115,8 @@ class PyVmomiHelper(object):
tools_running = False tools_running = False
vm_facts = {} vm_facts = {}
poll_num = 0 poll_num = 0
vm_uuid = vm.config.uuid
while not tools_running and poll_num <= poll: while not tools_running and poll_num <= poll:
newvm = self.getvm(uuid=vm_uuid) newvm = self.get_vm()
vm_facts = self.gather_facts(newvm) vm_facts = self.gather_facts(newvm)
if vm_facts['guest_tools_status'] == 'guestToolsRunning': if vm_facts['guest_tools_status'] == 'guestToolsRunning':
tools_running = True tools_running = True
@ -157,38 +138,39 @@ def main():
argument_spec.update( argument_spec.update(
name=dict(type='str'), name=dict(type='str'),
name_match=dict(type='str', default='first'), name_match=dict(type='str', default='first'),
folder=dict(type='str', default='/vm'), folder=dict(type='str'),
uuid=dict(type='str'), uuid=dict(type='str'),
) )
module = AnsibleModule( module = AnsibleModule(
argument_spec=argument_spec, argument_spec=argument_spec,
required_one_of=[['name', 'uuid']], required_one_of=[['name', 'uuid']])
required_together=['name', 'folder']
)
# FindByInventoryPath() does not require an absolute path if module.params['folder']:
# so we should leave the input folder path unmodified # FindByInventoryPath() does not require an absolute path
module.params['folder'] = module.params['folder'].rstrip('/') # so we should leave the input folder path unmodified
module.params['folder'] = module.params['folder'].rstrip('/')
pyv = PyVmomiHelper(module) pyv = PyVmomiHelper(module)
# Check if the VM exists before continuing # Check if the VM exists before continuing
vm = pyv.getvm(name=module.params['name'], vm = pyv.get_vm()
folder=module.params['folder'],
uuid=module.params['uuid'])
if not vm: if not vm:
vm_id = module.params.get('name') or module.params.get('uuid') module.fail_json(msg="Unable to wait for VMware tools for "
module.fail_json(msg="Unable to wait for tools for non-existing VM {0:s}".format(vm_id)) "non-existing VM '%s'." % (module.params.get('name') or
module.params.get('uuid')))
result = dict(changed=False)
try: try:
result = pyv.wait_for_tools(vm) result = pyv.wait_for_tools(vm)
except Exception as e: except Exception as e:
module.fail_json(msg="Waiting for tools failed with exception: {0:s}".format(to_native(e))) module.fail_json(msg="Waiting for VMware tools failed with"
" exception: {0:s}".format(to_native(e)))
if result['failed']: if result['failed']:
module.fail_json(**result) module.fail_json(**result)
else: else:
module.exit_json(**result) module.exit_json(**result)
if __name__ == '__main__': if __name__ == '__main__':
main() main()