# Buggy code
def mod_hostname(hostname):
    """
    Modify hostname

    .. versionchanged:: 2015.8.0
        Added support for SunOS (Solaris 10, Illumos, SmartOS)

    CLI Example:

    .. code-block:: bash

        salt '*' network.mod_hostname master.saltstack.com
    """
    #
    # SunOS tested on SmartOS and OmniOS (Solaris 10 compatible)
    # Oracle Solaris 11 uses smf, currently not supported
    #
    # /etc/nodename is the hostname only, not fqdn
    # /etc/defaultdomain is the domain
    # /etc/hosts should have both fqdn and hostname entries
    #

    if hostname is None:
        return False

    hostname_cmd = salt.utils.which("hostnamectl") or salt.utils.which("hostname")
    if salt.utils.is_sunos():
        uname_cmd = (
            "/usr/bin/uname" if salt.utils.is_smartos() else salt.utils.which("uname")
        )
        check_hostname_cmd = salt.utils.which("check-hostname")

    # Grab the old hostname so we know which hostname to change and then
    # change the hostname using the hostname command
    if hostname_cmd.endswith("hostnamectl"):
        out = __salt__["cmd.run"]("{0} status".format(hostname_cmd))
        for line in out.splitlines():
            line = line.split(":")
            if "Static hostname" in line[0]:
                o_hostname = line[1].strip()
    elif not salt.utils.is_sunos():
        # don't run hostname -f because -f is not supported on all platforms
        o_hostname = socket.getfqdn()
    else:
        # output: Hostname core OK: fully qualified as core.acheron.be
        o_hostname = __salt__["cmd.run"](check_hostname_cmd).split(" ")[-1]

    if hostname_cmd.endswith("hostnamectl"):
        __salt__["cmd.run"]("{0} set-hostname {1}".format(hostname_cmd, hostname))
    elif not salt.utils.is_sunos():
        __salt__["cmd.run"]("{0} {1}".format(hostname_cmd, hostname))
    else:
        __salt__["cmd.run"]("{0} -S {1}".format(uname_cmd, hostname.split(".")[0]))

    # Modify the /etc/hosts file to replace the old hostname with the
    # new hostname
    with salt.utils.fopen("/etc/hosts", "r") as fp_:
        host_c = fp_.readlines()

    with salt.utils.fopen("/etc/hosts", "w") as fh_:
        for host in host_c:
            host = host.split()

            try:
                host[host.index(o_hostname)] = hostname
                if salt.utils.is_sunos():
                    # also set a copy of the hostname
                    host[host.index(o_hostname.split(".")[0])] = hostname.split(".")[0]
            except ValueError:
                pass

            fh_.write("\t".join(host) + "\n")

    # Modify the /etc/sysconfig/network configuration file to set the
    # new hostname
    if __grains__["os_family"] == "RedHat":
        with salt.utils.fopen("/etc/sysconfig/network", "r") as fp_:
            network_c = fp_.readlines()

        with salt.utils.fopen("/etc/sysconfig/network", "w") as fh_:
            for net in network_c:
                if net.startswith("HOSTNAME"):
                    fh_.write("HOSTNAME={0}\n".format(hostname))
                else:
                    fh_.write(net)
    elif __grains__["os_family"] in ("Debian", "NILinuxRT"):
        with salt.utils.fopen("/etc/hostname", "w") as fh_:
            fh_.write(hostname + "\n")
    elif __grains__["os_family"] == "OpenBSD":
        with salt.utils.fopen("/etc/myname", "w") as fh_:
            fh_.write(hostname + "\n")

    # Update /etc/nodename and /etc/defaultdomain on SunOS
    if salt.utils.is_sunos():
        with salt.utils.fopen("/etc/nodename", "w") as fh_:
            fh_.write(hostname.split(".")[0] + "\n")
        with salt.utils.fopen("/etc/defaultdomain", "w") as fh_:
            fh_.write(".".join(hostname.split(".")[1:]) + "\n")

    return True


# Traceback (TypeError)
# ... <elided> ...
[INFO    ] Loading fresh modules for state activity
[DEBUG   ] LazyLoaded jinja.render
[DEBUG   ] LazyLoaded yaml.render
[DEBUG   ] In saltenv 'base', looking at rel_path 'test.sls' to resolve 'salt://test.sls'
[DEBUG   ] In saltenv 'base', ** considering ** path '/var/cache/salt/minion/files/base/test.sls' to resolve 'salt://test.sls'
[DEBUG   ] compile template: /var/cache/salt/minion/files/base/test.sls
[DEBUG   ] Jinja search path: ['/var/cache/salt/minion/files/base']
[PROFILE ] Time (in seconds) to render '/var/cache/salt/minion/files/base/test.sls' using 'jinja' renderer: 0.000791072845459
[DEBUG   ] Rendered data from file: /var/cache/salt/minion/files/base/test.sls:
set hostname:
network.system:
- hostname: foo
- apply_hostname: True
- retain_settings: True

[DEBUG   ] LazyLoaded config.get
[DEBUG   ] Results of YAML rendering:
OrderedDict([('set hostname', OrderedDict([('network.system', [OrderedDict([('hostname', 'foo')]), OrderedDict([('apply_hostname', True)]), OrderedDict([('retain_settings', True)])])]))])
[PROFILE ] Time (in seconds) to render '/var/cache/salt/minion/files/base/test.sls' using 'yaml' renderer: 0.0252919197083
[DEBUG   ] LazyLoaded ip.get_interface
[DEBUG   ] LazyLoaded network.system
[INFO    ] Running state [set hostname] at time 12:20:55.473338
[INFO    ] Executing state network.system for set hostname
[INFO    ] Using existing setting -- Setting: networking Value: "yes"
[ERROR   ] 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 1704, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/network.py", line 528, in system
new = __salt__['ip.build_network_settings'](**kwargs)
File "/usr/lib/python2.6/site-packages/salt/modules/rh_ip.py", line 1209, in build_network_settings
opts = _parse_network_settings(settings, current_network_settings)
File "/usr/lib/python2.6/site-packages/salt/modules/rh_ip.py", line 806, in _parse_network_settings
_raise_error_network('networking', valid)
File "/usr/lib/python2.6/site-packages/salt/modules/rh_ip.py", line 848, in _raise_error_network
msg = _error_msg_network(option, expected)
File "/usr/lib/python2.6/site-packages/salt/modules/rh_ip.py", line 105, in _error_msg_network
return msg.format(option, '|'.join(expected))
TypeError: sequence item 4: expected string, bool found

[INFO    ] Completed state [set hostname] at time 12:20:55.475410 duration_in_ms=2.073
[DEBUG   ] File /var/cache/salt/minion/accumulator/52678352 does not exist, no need to cleanup.
[DEBUG   ] LazyLoaded config.option
[DEBUG   ] LazyLoaded highstate.output
local:
----------
ID: set hostname
Function: network.system
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 1704, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.6/site-packages/salt/states/network.py", line 528, in system
new = __salt__['ip.build_network_settings'](**kwargs)
File "/usr/lib/python2.6/site-packages/salt/modules/rh_ip.py", line 1209, in build_network_settings
opts = _parse_network_settings(settings, current_network_settings)
File "/usr/lib/python2.6/site-packages/salt/modules/rh_ip.py", line 806, in _parse_network_settings
_raise_error_network('networking', valid)
File "/usr/lib/python2.6/site-packages/salt/modules/rh_ip.py", line 848, in _raise_error_network
msg = _error_msg_network(option, expected)
File "/usr/lib/python2.6/site-packages/salt/modules/rh_ip.py", line 105, in _error_msg_network
return msg.format(option, '|'.join(expected))
TypeError: sequence item 4: expected string, bool found
Started: 12:20:55.473337
Duration: 2.073 ms
Changes:

Summary for local
------------
Succeeded: 0
Failed:    1
------------
Total states run:     1
Total run time:   2.073 ms

# Fixed code
def mod_hostname(hostname):
    """
    Modify hostname

    .. versionchanged:: 2015.8.0
        Added support for SunOS (Solaris 10, Illumos, SmartOS)

    CLI Example:

    .. code-block:: bash

        salt '*' network.mod_hostname master.saltstack.com
    """
    #
    # SunOS tested on SmartOS and OmniOS (Solaris 10 compatible)
    # Oracle Solaris 11 uses smf, currently not supported
    #
    # /etc/nodename is the hostname only, not fqdn
    # /etc/defaultdomain is the domain
    # /etc/hosts should have both fqdn and hostname entries
    #

    if hostname is None:
        return False

    hostname_cmd = salt.utils.which("hostnamectl") or salt.utils.which("hostname")
    if salt.utils.is_sunos():
        uname_cmd = (
            "/usr/bin/uname" if salt.utils.is_smartos() else salt.utils.which("uname")
        )
        check_hostname_cmd = salt.utils.which("check-hostname")

    # Grab the old hostname so we know which hostname to change and then
    # change the hostname using the hostname command
    if hostname_cmd.endswith("hostnamectl"):
        out = __salt__["cmd.run"]("{0} status".format(hostname_cmd))
        for line in out.splitlines():
            line = line.split(":")
            if "Static hostname" in line[0]:
                o_hostname = line[1].strip()
    elif not salt.utils.is_sunos():
        # don't run hostname -f because -f is not supported on all platforms
        o_hostname = socket.getfqdn()
    else:
        # output: Hostname core OK: fully qualified as core.acheron.be
        o_hostname = __salt__["cmd.run"](check_hostname_cmd).split(" ")[-1]

    if hostname_cmd.endswith("hostnamectl"):
        __salt__["cmd.run"]("{0} set-hostname {1}".format(hostname_cmd, hostname))
    elif not salt.utils.is_sunos():
        __salt__["cmd.run"]("{0} {1}".format(hostname_cmd, hostname))
    else:
        __salt__["cmd.run"]("{0} -S {1}".format(uname_cmd, hostname.split(".")[0]))

    # Modify the /etc/hosts file to replace the old hostname with the
    # new hostname
    with salt.utils.fopen("/etc/hosts", "r") as fp_:
        host_c = fp_.readlines()

    with salt.utils.fopen("/etc/hosts", "w") as fh_:
        for host in host_c:
            host = host.split()

            try:
                host[host.index(o_hostname)] = hostname
                if salt.utils.is_sunos():
                    # also set a copy of the hostname
                    host[host.index(o_hostname.split(".")[0])] = hostname.split(".")[0]
            except ValueError:
                pass

            fh_.write("\t".join(host) + "\n")

    # Modify the /etc/sysconfig/network configuration file to set the
    # new hostname
    if __grains__["os_family"] == "RedHat":
        with salt.utils.fopen("/etc/sysconfig/network", "r") as fp_:
            network_c = fp_.readlines()

        with salt.utils.fopen("/etc/sysconfig/network", "w") as fh_:
            for net in network_c:
                if net.startswith("HOSTNAME"):
                    old_hostname = net.split("=", 1)[1].rstrip()
                    quote_type = salt.utils.is_quoted(old_hostname)
                    fh_.write(
                        "HOSTNAME={1}{0}{1}\n".format(
                            salt.utils.dequote(hostname), quote_type
                        )
                    )
                else:
                    fh_.write(net)
    elif __grains__["os_family"] in ("Debian", "NILinuxRT"):
        with salt.utils.fopen("/etc/hostname", "w") as fh_:
            fh_.write(hostname + "\n")
    elif __grains__["os_family"] == "OpenBSD":
        with salt.utils.fopen("/etc/myname", "w") as fh_:
            fh_.write(hostname + "\n")

    # Update /etc/nodename and /etc/defaultdomain on SunOS
    if salt.utils.is_sunos():
        with salt.utils.fopen("/etc/nodename", "w") as fh_:
            fh_.write(hostname.split(".")[0] + "\n")
        with salt.utils.fopen("/etc/defaultdomain", "w") as fh_:
            fh_.write(".".join(hostname.split(".")[1:]) + "\n")

    return True