# Buggy code
def _get_instances(self, inkwargs):
    """Make API calls"""
    instances = []
    try:
        si = SmartConnect(**inkwargs)
    except ssl.SSLError as connection_error:
        if (
            "[SSL: CERTIFICATE_VERIFY_FAILED]" in str(connection_error)
            and self.validate_certs
        ):
            sys.exit(
                "Unable to connect to ESXi server due to %s, "
                "please specify validate_certs=False and try again" % connection_error
            )

    except Exception as exc:
        self.debugl("Unable to connect to ESXi server due to %s" % exc)
        sys.exit("Unable to connect to ESXi server due to %s" % exc)

    self.debugl("retrieving all instances")
    if not si:
        sys.exit(
            "Could not connect to the specified host using specified "
            "username and password"
        )
    atexit.register(Disconnect, si)
    content = si.RetrieveContent()

    # Create a search container for virtualmachines
    self.debugl("creating containerview for virtualmachines")
    container = content.rootFolder
    viewType = [vim.VirtualMachine]
    recursive = True
    containerView = content.viewManager.CreateContainerView(
        container, viewType, recursive
    )
    children = containerView.view
    for child in children:
        # If requested, limit the total number of instances
        if self.args.max_instances:
            if len(instances) >= self.args.max_instances:
                break
        instances.append(child)
    self.debugl("%s total instances in container view" % len(instances))

    if self.args.host:
        instances = [x for x in instances if x.name == self.args.host]

    instance_tuples = []
    for instance in instances:
        if self.guest_props:
            ifacts = self.facts_from_proplist(instance)
        else:
            ifacts = self.facts_from_vobj(instance)
        instance_tuples.append((instance, ifacts))
    self.debugl("facts collected for all instances")

    try:
        cfm = content.customFieldsManager
        if cfm is not None and cfm.field:
            for f in cfm.field:
                if not f.managedObjectType or f.managedObjectType == vim.VirtualMachine:
                    self.custom_fields[f.key] = f.name
            self.debugl("%d custom fields collected" % len(self.custom_fields))
    except vmodl.RuntimeFault as exc:
        self.debugl("Unable to gather custom fields due to %s" % exc.msg)
    except IndexError as exc:
        self.debugl("Unable to gather custom fields due to %s" % exc)

    return instance_tuples


# Traceback (RuntimeError)
4.545 INFO     Updating inventory 28: VCENTER_INVENTORY
5.489 INFO     Reading Ansible inventory source: /var/lib/awx/venv/awx/lib64/python3.6/site-packages/awx/plugins/inventory/vmware_inventory.py
5.495 INFO     Using VIRTUAL_ENV: /var/lib/awx/venv/ansible
5.495 INFO     Using PATH: /var/lib/awx/venv/ansible/bin:/var/lib/awx/venv/awx/bin:/var/lib/awx/venv/awx/bin:/var/lib/awx/venv/awx/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
5.496 INFO     Using PYTHONPATH: /var/lib/awx/venv/ansible/lib/python3.6/site-packages:
Traceback (most recent call last):
File "/var/lib/awx/venv/awx/bin/awx-manage", line 11, in <module>
load_entry_point('awx==9.1.0', 'console_scripts', 'awx-manage')()
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/awx/__init__.py", line 165, in manage
execute_from_command_line(sys.argv)
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/awx/main/management/commands/inventory_import.py", line 1158, in handle
raise exc
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/awx/main/management/commands/inventory_import.py", line 1048, in handle
venv_path=venv_path, verbosity=self.verbosity).load()
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/awx/main/management/commands/inventory_import.py", line 215, in load
return self.command_to_json(base_args + ['--list'])
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/awx/main/management/commands/inventory_import.py", line 198, in command_to_json
self.method, proc.returncode, stdout, stderr))
RuntimeError: ansible-inventory failed (rc=1) with stdout:
stderr:
ansible-inventory 2.9.2
config file = /etc/ansible/ansible.cfg
configured module search path = ['/var/lib/awx/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.6/site-packages/ansible
executable location = /usr/local/bin/ansible-inventory
python version = 3.6.8 (default, Oct  7 2019, 17:58:22) [GCC 8.2.1 20180905 (Red Hat 8.2.1-3)]
Using /etc/ansible/ansible.cfg as config file
[WARNING]:  * Failed to parse /var/lib/awx/venv/awx/lib64/python3.6/site-
packages/awx/plugins/inventory/vmware_inventory.py with script plugin:
Inventory script (/var/lib/awx/venv/awx/lib64/python3.6/site-
packages/awx/plugins/inventory/vmware_inventory.py) had an execution error:
Traceback (most recent call last):   File
"/var/lib/awx/venv/awx/lib64/python3.6/site-
packages/awx/plugins/inventory/vmware_inventory.py", line 792, in <module>
print(VMWareInventory().show())   File
"/var/lib/awx/venv/awx/lib64/python3.6/site-
packages/awx/plugins/inventory/vmware_inventory.py", line 146, in __init__
self.do_api_calls_update_cache()   File
"/var/lib/awx/venv/awx/lib64/python3.6/site-
packages/awx/plugins/inventory/vmware_inventory.py", line 185, in
do_api_calls_update_cache     self.inventory =
self.instances_to_inventory(self.get_instances())   File
"/var/lib/awx/venv/awx/lib64/python3.6/site-
packages/awx/plugins/inventory/vmware_inventory.py", line 364, in get_instances
return self._get_instances(kwargs)   File
"/var/lib/awx/venv/awx/lib64/python3.6/site-
packages/awx/plugins/inventory/vmware_inventory.py", line 381, in
_get_instances     if not si: UnboundLocalError: local variable 'si' referenced
before assignment

File "/usr/local/lib/python3.6/site-packages/ansible/inventory/manager.py", line 280, in parse_source
plugin.parse(self._inventory, self._loader, source, cache=cache)
File "/usr/local/lib/python3.6/site-packages/ansible/plugins/inventory/script.py", line 161, in parse
raise AnsibleParserError(to_native(e))

[WARNING]: Unable to parse /var/lib/awx/venv/awx/lib64/python3.6/site-
packages/awx/plugins/inventory/vmware_inventory.py as an inventory source

ERROR! No inventory was parsed, please check your configuration and options.

# Fixed code
def _get_instances(self, inkwargs):
    """Make API calls"""
    instances = []
    si = None
    try:
        si = SmartConnect(**inkwargs)
    except ssl.SSLError as connection_error:
        if (
            "[SSL: CERTIFICATE_VERIFY_FAILED]" in str(connection_error)
            and self.validate_certs
        ):
            sys.exit(
                "Unable to connect to ESXi server due to %s, "
                "please specify validate_certs=False and try again" % connection_error
            )

    except Exception as exc:
        self.debugl("Unable to connect to ESXi server due to %s" % exc)
        sys.exit("Unable to connect to ESXi server due to %s" % exc)

    self.debugl("retrieving all instances")
    if not si:
        sys.exit(
            "Could not connect to the specified host using specified "
            "username and password"
        )
    atexit.register(Disconnect, si)
    content = si.RetrieveContent()

    # Create a search container for virtualmachines
    self.debugl("creating containerview for virtualmachines")
    container = content.rootFolder
    viewType = [vim.VirtualMachine]
    recursive = True
    containerView = content.viewManager.CreateContainerView(
        container, viewType, recursive
    )
    children = containerView.view
    for child in children:
        # If requested, limit the total number of instances
        if self.args.max_instances:
            if len(instances) >= self.args.max_instances:
                break
        instances.append(child)
    self.debugl("%s total instances in container view" % len(instances))

    if self.args.host:
        instances = [x for x in instances if x.name == self.args.host]

    instance_tuples = []
    for instance in instances:
        if self.guest_props:
            ifacts = self.facts_from_proplist(instance)
        else:
            ifacts = self.facts_from_vobj(instance)
        instance_tuples.append((instance, ifacts))
    self.debugl("facts collected for all instances")

    try:
        cfm = content.customFieldsManager
        if cfm is not None and cfm.field:
            for f in cfm.field:
                if not f.managedObjectType or f.managedObjectType == vim.VirtualMachine:
                    self.custom_fields[f.key] = f.name
            self.debugl("%d custom fields collected" % len(self.custom_fields))
    except vmodl.RuntimeFault as exc:
        self.debugl("Unable to gather custom fields due to %s" % exc.msg)
    except IndexError as exc:
        self.debugl("Unable to gather custom fields due to %s" % exc)

    return instance_tuples