Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/63438.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Ensure the correct argument is passed to hostname command depending on the systemd version for both the network and system module.
5 changes: 4 additions & 1 deletion salt/modules/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import salt.utils.functools
import salt.utils.network
import salt.utils.platform
import salt.utils.systemd
import salt.utils.validate.net
from salt._compat import ipaddress
from salt.exceptions import CommandExecutionError
Expand Down Expand Up @@ -1472,9 +1473,11 @@ def mod_hostname(hostname):
o_hostname = __salt__["cmd.run"](check_hostname_cmd).split(" ")[-1]

if hostname_cmd.endswith("hostnamectl"):
verb = "hostname" if salt.utils.systemd.version() >= 249 else "set-hostname"
result = __salt__["cmd.run_all"](
"{} set-hostname {}".format(
"{} {} {}".format(
hostname_cmd,
verb,
hostname,
)
)
Expand Down
16 changes: 9 additions & 7 deletions salt/modules/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.systemd
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.utils.decorators import depends

Expand Down Expand Up @@ -67,7 +68,7 @@ def init(runlevel):

salt '*' system.init 3
"""
cmd = ["init", "{}".format(runlevel)]
cmd = ["init", f"{runlevel}"]
ret = __salt__["cmd.run"](cmd, python_shell=False)
return ret

Expand Down Expand Up @@ -100,7 +101,7 @@ def reboot(at_time=None):

salt '*' system.reboot
"""
cmd = ["shutdown", "-r", ("{}".format(at_time) if at_time else "now")]
cmd = ["shutdown", "-r", (f"{at_time}" if at_time else "now")]
ret = __salt__["cmd.run"](cmd, python_shell=False)
return ret

Expand Down Expand Up @@ -128,7 +129,7 @@ def shutdown(at_time=None):
else:
flag = "-h"

cmd = ["shutdown", flag, ("{}".format(at_time) if at_time else "now")]
cmd = ["shutdown", flag, (f"{at_time}" if at_time else "now")]
ret = __salt__["cmd.run"](cmd, python_shell=False)
return ret

Expand Down Expand Up @@ -582,8 +583,9 @@ def set_computer_desc(desc):

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

Expand All @@ -592,7 +594,7 @@ def set_computer_desc(desc):
pass

pattern = re.compile(r"^\s*PRETTY_HOSTNAME=(.*)$")
new_line = salt.utils.stringutils.to_str('PRETTY_HOSTNAME="{}"'.format(desc))
new_line = salt.utils.stringutils.to_str(f'PRETTY_HOSTNAME="{desc}"')
try:
with salt.utils.files.fopen("/etc/machine-info", "r+") as mach_info:
lines = mach_info.readlines()
Expand Down Expand Up @@ -669,10 +671,10 @@ def set_reboot_required_witnessed():
os.makedirs(dir_path)
except OSError as ex:
raise SaltInvocationError(
"Error creating {} (-{}): {}".format(dir_path, ex.errno, ex.strerror)
f"Error creating {dir_path} (-{ex.errno}): {ex.strerror}"
)

rdict = __salt__["cmd.run_all"]("touch {}".format(NILRT_REBOOT_WITNESS_PATH))
rdict = __salt__["cmd.run_all"](f"touch {NILRT_REBOOT_WITNESS_PATH}")
errcode = rdict["retcode"]

return errcode == 0
Expand Down
29 changes: 28 additions & 1 deletion tests/pytests/unit/modules/test_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import salt.utils.path
from salt._compat import ipaddress
from salt.exceptions import CommandExecutionError
from tests.support.mock import MagicMock, mock_open, patch
from tests.support.mock import MagicMock, call, mock_open, patch

log = logging.getLogger(__name__)

Expand Down Expand Up @@ -378,6 +378,33 @@ def test_mod_hostname():
assert networkmod.mod_hostname("hostname")


def test_mod_hostname_hostnamectl():
"""
Test for Modify hostname when hostnamectl is used
"""
assert not networkmod.mod_hostname(None)
file_d = "\n".join(["#", "A B C D,E,F G H"])

mock_run_all = MagicMock(
return_value={"retcode": 0, "stdout": "Static hostname: testhostname"}
)
patch_run_all = patch.dict(networkmod.__salt__, {"cmd.run_all": mock_run_all})
cmd = "hostname" if salt.utils.systemd.version() >= 249 else "set-hostname"
with patch.dict(
networkmod.__utils__,
{
"path.which": MagicMock(return_value="hostnamectl"),
"files.fopen": mock_open(read_data=file_d),
},
), patch.dict(
networkmod.__salt__, {"cmd.run": MagicMock(return_value=None)}
), patch.dict(
networkmod.__grains__, {"os_family": "A"}
), patch_run_all:
assert networkmod.mod_hostname("hostname")
assert mock_run_all.call_args_list[1] == call(f"hostnamectl {cmd} hostname")


def test_mod_hostname_quoted():
"""
Test for correctly quoted hostname on rh-style distro
Expand Down
Loading