# Buggy code
def render_tmpl(
    tmplsrc, from_str=False, to_str=False, context=None, tmplpath=None, **kws
):
    if context is None:
        context = {}
    # We want explicit context to overwrite the **kws
    kws.update(context)
    context = kws
    assert "opts" in context
    assert "env" in context

    if isinstance(tmplsrc, basestring):
        if from_str:
            tmplstr = tmplsrc
        else:
            with codecs.open(tmplsrc, "r", SLS_ENCODING) as tmplsrc:
                tmplstr = tmplsrc.read()
    else:  # assume tmplsrc is file-like.
        tmplstr = tmplsrc.read()
        tmplsrc.close()
    try:
        output = render_str(tmplstr, context, tmplpath)
        if salt.utils.is_windows():
            # Write out with Windows newlines
            output = os.linesep.join(output.splitlines())

    except SaltTemplateRenderError as exc:
        return dict(result=False, data=str(exc))
    except Exception:
        return dict(result=False, data=traceback.format_exc())
    else:
        if to_str:  # then render as string
            return dict(result=True, data=output)
        with tempfile.NamedTemporaryFile("wb", delete=False) as outf:
            outf.write(SLS_ENCODER(output)[0])
            # Note: If nothing is replaced or added by the rendering
            #       function, then the contents of the output file will
            #       be exactly the same as the input.
        return dict(result=True, data=outf.name)


# Traceback (UnicodeDecodeError)
ns2:
----------
State: - file
Name:      /etc/powerdns/zones
Function:  recurse
Result:    False
Comment:   An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/salt/state.py", line 1201, in call
*cdata['args'], **cdata['kwargs'])
File "/usr/lib/pymodules/python2.7/salt/states/file.py", line 1317, in recurse
manage_file(dest, src)
File "/usr/lib/pymodules/python2.7/salt/states/file.py", line 1240, in manage_file
**pass_kwargs)
File "/usr/lib/pymodules/python2.7/salt/states/file.py", line 787, in managed
**kwargs
File "/usr/lib/pymodules/python2.7/salt/modules/file.py", line 1340, in check_managed
**kwargs)
File "/usr/lib/pymodules/python2.7/salt/modules/file.py", line 1153, in get_managed
**kwargs
File "/usr/lib/pymodules/python2.7/salt/utils/templates.py", line 53, in render_tmpl
tmplstr = tmplsrc.read()
File "/usr/lib/python2.7/codecs.py", line 671, in read
return self.reader.read(size)
File "/usr/lib/python2.7/codecs.py", line 477, in read
newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x86 in position 16: invalid start byte

# Fixed code
def render_tmpl(
    tmplsrc, from_str=False, to_str=False, context=None, tmplpath=None, **kws
):
    if context is None:
        context = {}
    # We want explicit context to overwrite the **kws
    kws.update(context)
    context = kws
    assert "opts" in context
    assert "env" in context

    if isinstance(tmplsrc, basestring):
        if from_str:
            tmplstr = tmplsrc
        else:
            try:
                with codecs.open(tmplsrc, "r", SLS_ENCODING) as _tmplsrc:
                    tmplstr = _tmplsrc.read()
            except Exception as exc:
                log.error(
                    "Exception ocurred while reading file {0}: {1}".format(tmplsrc, exc)
                )
                raise exc
    else:  # assume tmplsrc is file-like.
        tmplstr = tmplsrc.read()
        tmplsrc.close()
    try:
        output = render_str(tmplstr, context, tmplpath)
        if salt.utils.is_windows():
            # Write out with Windows newlines
            output = os.linesep.join(output.splitlines())

    except SaltTemplateRenderError as exc:
        return dict(result=False, data=str(exc))
    except Exception:
        return dict(result=False, data=traceback.format_exc())
    else:
        if to_str:  # then render as string
            return dict(result=True, data=output)
        with tempfile.NamedTemporaryFile("wb", delete=False) as outf:
            outf.write(SLS_ENCODER(output)[0])
            # Note: If nothing is replaced or added by the rendering
            #       function, then the contents of the output file will
            #       be exactly the same as the input.
        return dict(result=True, data=outf.name)