# Buggy code
def set_computer_desc(desc):
    """
    Set PRETTY_HOSTNAME value stored in /etc/machine-info
    This will create the file if it does not exist. If
    it is unable to create or modify this file returns False.

    :param str desc: The computer description
    :return: False on failure. True if successful.

    CLI Example:

    .. code-block:: bash

        salt '*' system.set_computer_desc "Michael's laptop"
    """
    if six.PY3:
        desc = desc.replace('"', '\\"')
    else:
        desc = desc.encode("string_escape").replace('"', '\\"')
    hostname_cmd = salt.utils.path.which("hostnamectl")
    if hostname_cmd:
        result = __salt__["cmd.retcode"](
            [hostname_cmd, "set-hostname", "--pretty", desc], python_shell=False
        )
        return True if result == 0 else False

    if not os.path.isfile("/etc/machine-info"):
        with salt.utils.files.fopen("/etc/machine-info", "w"):
            pass

    is_pretty_hostname_found = False
    pattern = re.compile(r"^\s*PRETTY_HOSTNAME=(.*)$")
    new_line = 'PRETTY_HOSTNAME="{0}"'.format(desc)
    try:
        with salt.utils.files.fopen("/etc/machine-info", "r+") as mach_info:
            lines = mach_info.readlines()
            for i, line in enumerate(lines):
                if pattern.match(line):
                    is_pretty_hostname_found = True
                    lines[i] = new_line
            if not is_pretty_hostname_found:
                lines.append(new_line)
            # time to write our changes to the file
            mach_info.seek(0, 0)
            mach_info.truncate()
            mach_info.write(salt.utils.stringutils.to_str("".join(lines)))
            mach_info.write(salt.utils.stringutils.to_str("\n"))
            return True
    except IOError:
        return False


# Traceback (UnicodeEncodeError)
ID: test1
Function: file.recurse
Name: /root/group2test
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/salt/state.py", line 1746, in call
**cdata['kwargs'])
File "/usr/lib/python2.6/site-packages/salt/loader.py", line 1703, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 2807, in recurse
manage_file(dest, src)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 2685, in manage_file
**pass_kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/file.py", line 1814, in managed
__env__
File "/usr/lib/python2.6/site-packages/salt/modules/file.py", line 3490, in source_list
contextkey = '{0}_|-{1}_|-{2}'.format(source, source_hash, saltenv)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-34: ordinal not in range(128)
Started: 20:08:21.608398
Duration: 1467.811 ms
Changes:

# Fixed code
def set_computer_desc(desc):
    """
    Set PRETTY_HOSTNAME value stored in /etc/machine-info
    This will create the file if it does not exist. If
    it is unable to create or modify this file returns False.

    :param str desc: The computer description
    :return: False on failure. True if successful.

    CLI Example:

    .. code-block:: bash

        salt '*' system.set_computer_desc "Michael's laptop"
    """
    desc = (
        salt.utils.stringutils.to_unicode(desc)
        .replace('"', r"\"")
        .replace("\n", r"\n")
        .replace("\t", r"\t")
    )

    hostname_cmd = salt.utils.path.which("hostnamectl")
    if hostname_cmd:
        result = __salt__["cmd.retcode"](
            [hostname_cmd, "set-hostname", "--pretty", desc], python_shell=False
        )
        return True if result == 0 else False

    if not os.path.isfile("/etc/machine-info"):
        with salt.utils.files.fopen("/etc/machine-info", "w"):
            pass

    pattern = re.compile(r"^\s*PRETTY_HOSTNAME=(.*)$")
    new_line = salt.utils.stringutils.to_str('PRETTY_HOSTNAME="{0}"'.format(desc))
    try:
        with salt.utils.files.fopen("/etc/machine-info", "r+") as mach_info:
            lines = mach_info.readlines()
            for i, line in enumerate(lines):
                if pattern.match(salt.utils.stringutils.to_unicode(line)):
                    lines[i] = new_line
                    break
            else:
                # PRETTY_HOSTNAME line was not found, add it to the end
                lines.append(new_line)
            # time to write our changes to the file
            mach_info.seek(0, 0)
            mach_info.truncate()
            mach_info.writelines(lines)
            return True
    except IOError:
        return False