# Buggy code
def set_powerstate(self, vm, state, force):
    """
    Set the power status for a VM determined by the current and
    requested states. force is forceful
    """
    facts = self.gather_facts(vm)
    expected_state = state.replace("_", "").lower()
    current_state = facts["hw_power_status"].lower()
    result = {}

    # Need Force
    if not force and current_state not in ["poweredon", "poweredoff"]:
        return "VM is in %s power state. Force is required!" % current_state

    # State is already true
    if current_state == expected_state:
        result["changed"] = False
        result["failed"] = False
    else:
        task = None
        try:
            if expected_state == "poweredoff":
                task = vm.PowerOff()

            elif expected_state == "poweredon":
                task = vm.PowerOn()

            elif expected_state == "restarted":
                if current_state in (
                    "poweredon",
                    "poweringon",
                    "resetting",
                    "poweredoff",
                ):
                    task = vm.Reset()
                else:
                    result = {
                        "changed": False,
                        "failed": True,
                        "msg": "Cannot restart VM in the current state %s"
                        % current_state,
                    }
            elif expected_state == "suspended":
                if current_state in ("poweredon", "poweringon"):
                    task = vm.Suspend()
                else:
                    result = {
                        "changed": False,
                        "failed": True,
                        "msg": "Cannot suspend VM in the current state %s"
                        % current_state,
                    }

        except Exception:
            result = {"changed": False, "failed": True, "msg": get_exception()}

        if task:
            self.wait_for_task(task)
            if task.info.state == "error":
                result = {"changed": False, "failed": True, "msg": task.info.error.msg}
            else:
                result = {"changed": True, "failed": False}

    # need to get new metadata if changed
    if result["changed"]:
        newvm = self.getvm(uuid=vm.config.uuid)
        facts = self.gather_facts(newvm)
        result["instance"] = facts
    return result


# Traceback (NameError)
TASK [vmware_guest] *************************************************************************************************************************************************************************************************************************************************
task path: /opt/playbooks/vmware_poweron.yml:7
Using module file /opt/ansible-devel/lib/ansible/modules/cloud/vmware/vmware_guest.py
<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root
<localhost> EXEC /bin/sh -c '( umask 77 &amp;&amp; mkdir -p "` echo ~/.ansible/tmp/ansible-tmp-1484045789.62-15924742279620 `" &amp;&amp; echo ansible-tmp-1484045789.62-15924742279620="` echo ~/.ansible/tmp/ansible-tmp-1484045789.62-15924742279620 `" ) &amp;&amp; sleep 0'
<localhost> PUT /tmp/tmpEnTUQ4 TO /root/.ansible/tmp/ansible-tmp-1484045789.62-15924742279620/vmware_guest.py
<localhost> EXEC /bin/sh -c 'chmod u+x /root/.ansible/tmp/ansible-tmp-1484045789.62-15924742279620/ /root/.ansible/tmp/ansible-tmp-1484045789.62-15924742279620/vmware_guest.py &amp;&amp; sleep 0'
<localhost> EXEC /bin/sh -c '/usr/bin/python /root/.ansible/tmp/ansible-tmp-1484045789.62-15924742279620/vmware_guest.py; rm -rf "/root/.ansible/tmp/ansible-tmp-1484045789.62-15924742279620/" > /dev/null 2>&amp;1 &amp;&amp; sleep 0'
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_oWcaJm/ansible_module_vmware_guest.py", line 1848, in <module>
main()
File "/tmp/ansible_oWcaJm/ansible_module_vmware_guest.py", line 1814, in main
tmp_result = pyv.set_powerstate(vm, module.params['state'], module.params['force'])
File "/tmp/ansible_oWcaJm/ansible_module_vmware_guest.py", line 762, in set_powerstate
'msg': get_exception()}
NameError: global name 'get_exception' is not defined

fatal: [localhost]: FAILED! => {
"changed": false,
"failed": true,
"invocation": {
"module_name": "vmware_guest"
},
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_oWcaJm/ansible_module_vmware_guest.py\", line 1848, in <module>\n    main()\n  File \"/tmp/ansible_oWcaJm/ansible_module_vmware_guest.py\", line 1814, in main\n    tmp_result = pyv.set_powerstate(vm, module.params['state'], module.params['force'])\n  File \"/tmp/ansible_oWcaJm/ansible_module_vmware_guest.py\", line 762, in set_powerstate\n    'msg': get_exception()}\nNameError: global name 'get_exception' is not defined\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 0
}

# Fixed code
def set_powerstate(self, vm, state, force):
    """
    Set the power status for a VM determined by the current and
    requested states. force is forceful
    """
    facts = self.gather_facts(vm)
    expected_state = state.replace("_", "").lower()
    current_state = facts["hw_power_status"].lower()
    result = {}

    # Need Force
    if not force and current_state not in ["poweredon", "poweredoff"]:
        return "VM is in %s power state. Force is required!" % current_state

    # State is already true
    if current_state == expected_state:
        result["changed"] = False
        result["failed"] = False
    else:
        task = None
        try:
            if expected_state == "poweredoff":
                task = vm.PowerOff()

            elif expected_state == "poweredon":
                task = vm.PowerOn()

            elif expected_state == "restarted":
                if current_state in (
                    "poweredon",
                    "poweringon",
                    "resetting",
                    "poweredoff",
                ):
                    task = vm.Reset()
                else:
                    result = {
                        "changed": False,
                        "failed": True,
                        "msg": "Cannot restart VM in the current state %s"
                        % current_state,
                    }
            elif expected_state == "suspended":
                if current_state in ("poweredon", "poweringon"):
                    task = vm.Suspend()
                else:
                    result = {
                        "changed": False,
                        "failed": True,
                        "msg": "Cannot suspend VM in the current state %s"
                        % current_state,
                    }

        except Exception:
            e = get_exception()
            result = {"changed": False, "failed": True, "msg": e}

        if task:
            self.wait_for_task(task)
            if task.info.state == "error":
                result = {"changed": False, "failed": True, "msg": task.info.error.msg}
            else:
                result = {"changed": True, "failed": False}

    # need to get new metadata if changed
    if result["changed"]:
        newvm = self.getvm(uuid=vm.config.uuid)
        facts = self.gather_facts(newvm)
        result["instance"] = facts
    return result