# Buggy code
def _exec_ssh_cmd(cmd, error_msg=None, allow_failure=False, **kwargs):
    if error_msg is None:
        error_msg = "A wrong password has been issued while establishing ssh session."
    password_retries = kwargs.get("password_retries", 3)
    try:
        stdout, stderr = None, None
        proc = vt.Terminal(
            cmd,
            shell=True,
            log_stdout=True,
            log_stderr=True,
            stream_stdout=kwargs.get("display_ssh_output", True),
            stream_stderr=kwargs.get("display_ssh_output", True),
        )
        sent_password = 0
        while proc.has_unread_data:
            stdout, stderr = proc.recv()
            if stdout and SSH_PASSWORD_PROMP_RE.search(stdout):
                # if authenticating with an SSH key and 'sudo' is found
                # in the password prompt
                if (
                    "key_filename" in kwargs
                    and kwargs["key_filename"]
                    and SSH_PASSWORD_PROMP_SUDO_RE.search(stdout)
                ):
                    proc.sendline(kwargs["sudo_password", None])
                # elif authenticating via password and haven't exhausted our
                # password_retires
                elif kwargs.get("password", None) and (
                    sent_password < password_retries
                ):
                    sent_password += 1
                    proc.sendline(kwargs["password"])
                # else raise an error as we are not authenticating properly
                #  * not authenticating with an SSH key
                #  * not authenticating with a Password
                else:
                    raise SaltCloudPasswordError(error_msg)
            # 0.0125 is really too fast on some systems
            time.sleep(0.5)
        if proc.exitstatus != 0 and allow_failure is False:
            raise SaltCloudSystemExit(
                "Command '{0}' failed. Exit code: {1}".format(cmd, proc.exitstatus)
            )
        return proc.exitstatus
    except vt.TerminalException as err:
        trace = traceback.format_exc()
        log.error(error_msg.format(cmd, err, trace))
    finally:
        proc.close(terminate=True, kill=True)
    # Signal an error
    return 1


# Traceback (KeyError)
[DEBUG   ] Logging into 10.138.136.234:4910 as tools
[DEBUG   ] Using /root/.ssh/id_rsa as the key_filename
[DEBUG   ] Using sudo to run command sudo -S "XXX-REDACTED-XXX" test -e '/tmp/.saltcloud-4ba4b02e-5a85-40ae-8192-cf2dcb527c9d'
[DEBUG   ] SSH command: 'ssh -t -t -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oControlPath=none -oPasswordAuthentication=no -oChallengeResponseAuthentication=no -oPubkeyAuthentication=yes -oIdentitiesOnly=yes -oKbdInteractiveAuthentication=no -i /root/.ssh/id_rsa -p 4910 tools@10.138.136.234 sudo -S "XXX-REDACTED-XXX" test -e '/tmp/.saltcloud-4ba4b02e-5a85-40ae-8192-cf2dcb527c9d''
[DEBUG   ] Child Forked! PID: 4921  STDOUT_FD: 4  STDERR_FD: 8
[DEBUG   ] Terminal Command: /bin/sh -c ssh -t -t -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oControlPath=none -oPasswordAuthentication=no -oChallengeResponseAuthentication=no -oPubkeyAuthentication=yes -oIdentitiesOnly=yes -oKbdInteractiveAuthentication=no -i /root/.ssh/id_rsa -p 4910 tools@10.138.136.234 'sudo -S test -e '"'"'/tmp/.saltcloud-4ba4b02e-5a85-40ae-8192-cf2dcb527c9d'"'"''
Warning: Permanently added '[10.138.136.234]:4910' (ECDSA) to the list of known hosts.
[DEBUG   ] Warning: Permanently added '[10.138.136.234]:4910' (ECDSA) to the list of known hosts.
[sudo] password for tools: [DEBUG   ] [sudo] password for tools:
[ERROR   ] Failed to create VM lobsterman4. Configuration value ('sudo_password', None) needs to be set
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/cloud/__init__.py", line 1288, in create
output = self.clouds[func](vm_)
File "/usr/lib/python2.7/site-packages/salt/cloud/clouds/digital_ocean.py", line 510, in create
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
File "/usr/lib/python2.7/site-packages/salt/utils/cloud.py", line 532, in bootstrap
deployed = deploy_script(**deploy_kwargs)
File "/usr/lib/python2.7/site-packages/salt/utils/cloud.py", line 1267, in deploy_script
allow_failure=True, **ssh_kwargs):
File "/usr/lib/python2.7/site-packages/salt/utils/cloud.py", line 2224, in root_cmd
retcode = _exec_ssh_cmd(cmd, allow_failure=allow_failure, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/utils/cloud.py", line 1783, in _exec_ssh_cmd
proc.sendline(kwargs['sudo_password', None])
KeyError: ('sudo_password', None)
Error: There was a profile error: Failed to deploy VM

# Fixed code
def _exec_ssh_cmd(cmd, error_msg=None, allow_failure=False, **kwargs):
    if error_msg is None:
        error_msg = "A wrong password has been issued while establishing ssh session."
    password_retries = kwargs.get("password_retries", 3)
    try:
        stdout, stderr = None, None
        proc = vt.Terminal(
            cmd,
            shell=True,
            log_stdout=True,
            log_stderr=True,
            stream_stdout=kwargs.get("display_ssh_output", True),
            stream_stderr=kwargs.get("display_ssh_output", True),
        )
        sent_password = 0
        while proc.has_unread_data:
            stdout, stderr = proc.recv()
            if stdout and SSH_PASSWORD_PROMP_RE.search(stdout):
                # if authenticating with an SSH key and 'sudo' is found
                # in the password prompt
                if (
                    "key_filename" in kwargs
                    and kwargs["key_filename"]
                    and SSH_PASSWORD_PROMP_SUDO_RE.search(stdout)
                ):
                    proc.sendline(kwargs["sudo_password"])
                # elif authenticating via password and haven't exhausted our
                # password_retires
                elif kwargs.get("password", None) and (
                    sent_password < password_retries
                ):
                    sent_password += 1
                    proc.sendline(kwargs["password"])
                # else raise an error as we are not authenticating properly
                #  * not authenticating with an SSH key
                #  * not authenticating with a Password
                else:
                    raise SaltCloudPasswordError(error_msg)
            # 0.0125 is really too fast on some systems
            time.sleep(0.5)
        if proc.exitstatus != 0 and allow_failure is False:
            raise SaltCloudSystemExit(
                "Command '{0}' failed. Exit code: {1}".format(cmd, proc.exitstatus)
            )
        return proc.exitstatus
    except vt.TerminalException as err:
        trace = traceback.format_exc()
        log.error(error_msg.format(cmd, err, trace))
    finally:
        proc.close(terminate=True, kill=True)
    # Signal an error
    return 1