# Buggy code
def main():
    module = AnsibleModule(
        argument_spec=dict(
            hostname=dict(type="str", default=os.environ.get("VMWARE_HOST")),
            username=dict(type="str", default=os.environ.get("VMWARE_USER")),
            password=dict(
                type="str", no_log=True, default=os.environ.get("VMWARE_PASSWORD")
            ),
            state=dict(
                required=False,
                choices=["present", "absent", "revert", "remove_all"],
                default="present",
            ),
            validate_certs=dict(required=False, type="bool", default=True),
            name=dict(required=True, type="str"),
            name_match=dict(required=False, type="str", default="first"),
            uuid=dict(required=False, type="str"),
            folder=dict(required=False, type="str", default="/vm"),
            datacenter=dict(required=True, type="str"),
            snapshot_name=dict(required=False, type="str"),
            description=dict(required=False, type="str", default=""),
            quiesce=dict(type="bool", default=False),
            memory_dump=dict(type="bool", default=False),
            remove_children=dict(type="bool", default=False),
        ),
    )

    # Prepend /vm if it was missing from the folder path, also strip trailing slashes
    if not module.params["folder"].startswith("/vm") and module.params[
        "folder"
    ].startswith("/"):
        module.params["folder"] = "/vm%(folder)s" % module.params
    module.params["folder"] = module.params["folder"].rstrip("/")

    pyv = PyVmomiHelper(module)
    # Check if the VM exists before continuing
    vm = pyv.getvm(
        name=module.params["name"],
        folder=module.params["folder"],
        uuid=module.params["uuid"],
    )

    if not vm:
        # If UUID is set, getvm select UUID, show error message accordingly.
        if module.params["uuid"] is not None:
            module.fail_json(
                msg="Unable to manage snapshots for non-existing VM %(uuid)s"
                % module.params
            )
        else:
            module.fail_json(
                msg="Unable to manage snapshots for non-existing VM %(name)s"
                % module.params
            )

    if not module.params["snapshot_name"] and module.params["state"] != "remove_all":
        module.fail_json(
            msg="snapshot_name param is required when state is '%(state)s'"
            % module.params
        )

    result = pyv.apply_snapshot_op(vm)

    if "failed" not in result:
        result["failed"] = False

    if result["failed"]:
        module.fail_json(**result)
    else:
        module.exit_json(**result)


# Traceback (nAttributeError)
{
"_ansible_parsed": false,
"exception": "Traceback (most recent call last):\n  File \"/tmp/ansible_t0MsFQ/ansible_module_vmware_guest.py\", line 1332, in <module>\n    main()\n  File \"/tmp/ansible_t0MsFQ/ansible_module_vmware_guest.py\", line 1291, in main\n    pyv = PyVmomiHelper(module)\n  File \"/tmp/ansible_t0MsFQ/ansible_module_vmware_guest.py\", line 436, in __init__\n    self.content = connect_to_api(self.module)\n  File \"/tmp/ansible_t0MsFQ/ansible_modlib.zip/ansible/module_utils/vmware.py\", line 333, in connect_to_api\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/pyVim/connect.py\", line 817, in SmartConnect\n    sslContext)\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/pyVim/connect.py\", line 702, in __FindSupportedVersion\n    sslContext)\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/pyVim/connect.py\", line 622, in __GetServiceVersionDescription\n    path + \"/vimServiceVersions.xml\", sslContext)\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/pyVim/connect.py\", line 588, in __GetElementTree\n    conn.request(\"GET\", path)\n  File \"/usr/lib64/python2.7/httplib.py\", line 1017, in request\n    self._send_request(method, url, body, headers)\n  File \"/usr/lib64/python2.7/httplib.py\", line 1045, in _send_request\n    self.putrequest(method, url, **skips)\n  File \"/usr/lib64/python2.7/httplib.py\", line 946, in putrequest\n    host_enc = self.host.encode(\"ascii\")\nAttributeError: 'NoneType' object has no attribute 'encode'\n",
"_ansible_no_log": false,
"_ansible_delegated_vars": {
"ansible_host": "localhost"
},
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_t0MsFQ/ansible_module_vmware_guest.py\", line 1332, in <module>\n    main()\n  File \"/tmp/ansible_t0MsFQ/ansible_module_vmware_guest.py\", line 1291, in main\n    pyv = PyVmomiHelper(module)\n  File \"/tmp/ansible_t0MsFQ/ansible_module_vmware_guest.py\", line 436, in __init__\n    self.content = connect_to_api(self.module)\n  File \"/tmp/ansible_t0MsFQ/ansible_modlib.zip/ansible/module_utils/vmware.py\", line 333, in connect_to_api\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/pyVim/connect.py\", line 817, in SmartConnect\n    sslContext)\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/pyVim/connect.py\", line 702, in __FindSupportedVersion\n    sslContext)\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/pyVim/connect.py\", line 622, in __GetServiceVersionDescription\n    path + \"/vimServiceVersions.xml\", sslContext)\n  File \"/var/lib/awx/venv/ansible/lib/python2.7/site-packages/pyVim/connect.py\", line 588, in __GetElementTree\n    conn.request(\"GET\", path)\n  File \"/usr/lib64/python2.7/httplib.py\", line 1017, in request\n    self._send_request(method, url, body, headers)\n  File \"/usr/lib64/python2.7/httplib.py\", line 1045, in _send_request\n    self.putrequest(method, url, **skips)\n  File \"/usr/lib64/python2.7/httplib.py\", line 946, in putrequest\n    host_enc = self.host.encode(\"ascii\")\nAttributeError: 'NoneType' object has no attribute 'encode'\n",
"changed": false,
"module_stdout": "",
"failed": true,
"rc": 0,
"msg": "MODULE FAILURE"
}

# Fixed code
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(
        state=dict(
            default="present", choices=["present", "absent", "revert", "remove_all"]
        ),
        name=dict(required=True, type="str"),
        name_match=dict(type="str", default="first"),
        uuid=dict(type="str"),
        folder=dict(type="str", default="/vm"),
        datacenter=dict(required=True, type="str"),
        snapshot_name=dict(type="str"),
        description=dict(type="str", default=""),
        quiesce=dict(type="bool", default=False),
        memory_dump=dict(type="bool", default=False),
        remove_children=dict(type="bool", default=False),
    )
    module = AnsibleModule(argument_spec=argument_spec)

    # Prepend /vm if it was missing from the folder path, also strip trailing slashes
    if not module.params["folder"].startswith("/vm") and module.params[
        "folder"
    ].startswith("/"):
        module.params["folder"] = "/vm%(folder)s" % module.params
    module.params["folder"] = module.params["folder"].rstrip("/")

    pyv = PyVmomiHelper(module)
    # Check if the VM exists before continuing
    vm = pyv.getvm(
        name=module.params["name"],
        folder=module.params["folder"],
        uuid=module.params["uuid"],
    )

    if not vm:
        # If UUID is set, getvm select UUID, show error message accordingly.
        if module.params["uuid"] is not None:
            module.fail_json(
                msg="Unable to manage snapshots for non-existing VM %(uuid)s"
                % module.params
            )
        else:
            module.fail_json(
                msg="Unable to manage snapshots for non-existing VM %(name)s"
                % module.params
            )

    if not module.params["snapshot_name"] and module.params["state"] != "remove_all":
        module.fail_json(
            msg="snapshot_name param is required when state is '%(state)s'"
            % module.params
        )

    result = pyv.apply_snapshot_op(vm)

    if "failed" not in result:
        result["failed"] = False

    if result["failed"]:
        module.fail_json(**result)
    else:
        module.exit_json(**result)