diff --git a/salt/modules/cmdmod.py b/salt/modules/cmdmod.py index 2b3278124b94..23391925a7f0 100644 --- a/salt/modules/cmdmod.py +++ b/salt/modules/cmdmod.py @@ -446,7 +446,9 @@ def _get_stripped(cmd): # Ensure the login is simulated correctly (note: su runs sh, not bash, # which causes the environment to be initialised incorrectly, which is # fixed by the previous line of code) - cmd = "su -l {0} -c {1}".format(_cmd_quote(runas), _cmd_quote(cmd)) + cmd = 'su -l {0} -c "cd {1}; {2}"'.format( + _cmd_quote(runas), _cmd_quote(cwd), _cmd_quote(cmd) + ) # Set runas to None, because if you try to run `su -l` after changing # user, su will prompt for the password of the user and cause salt to diff --git a/tests/unit/modules/test_cmdmod.py b/tests/unit/modules/test_cmdmod.py index 5fbf8c893e30..04b63c788c44 100644 --- a/tests/unit/modules/test_cmdmod.py +++ b/tests/unit/modules/test_cmdmod.py @@ -452,8 +452,6 @@ def test_run_cwd_doesnt_exist_issue_7154(self): else: raise RuntimeError - @skipIf(salt.utils.platform.is_windows(), "Do not run on Windows") - @skipIf(salt.utils.platform.is_darwin(), "Do not run on MacOS") def test_run_cwd_in_combination_with_runas(self): """ cmd.run executes command in the cwd directory @@ -461,9 +459,11 @@ def test_run_cwd_in_combination_with_runas(self): """ cmd = "pwd" cwd = "/tmp" - runas = os.getlogin() + runas = "foobar" - with patch.dict(cmdmod.__grains__, {"os": "Darwin", "os_family": "Solaris"}): + with patch("pwd.getpwnam") as getpwnam_mock, patch.dict( + cmdmod.__grains__, {"os": "Darwin", "os_family": "Solaris"} + ): stdout = cmdmod._run(cmd, cwd=cwd, runas=runas).get("stdout") self.assertEqual(stdout, cwd) @@ -626,11 +626,13 @@ def test_run_chroot_runas(self): """ Test run_chroot when a runas parameter is provided """ - with patch.dict( + expected_shell = "/bin/sh" + patch_salt = patch.dict( cmdmod.__salt__, {"mount.mount": MagicMock(), "mount.umount": MagicMock()} - ): - with patch("salt.modules.cmdmod.run_all") as run_all_mock: - cmdmod.run_chroot("/mnt", "ls", runas="foobar") + ) + patch_run_all = patch("salt.modules.cmdmod.run_all") + with patch_salt, patch_run_all as run_all_mock: + cmdmod.run_chroot("/mnt", "ls", shell=expected_shell, runas="foobar") run_all_mock.assert_called_with( "chroot --userspec foobar: /mnt /bin/sh -c ls", bg=False, @@ -647,7 +649,7 @@ def test_run_chroot_runas(self): reset_system_locale=True, rstrip=True, saltenv="base", - shell="/bin/bash", + shell=expected_shell, stdin=None, success_retcodes=None, template=None,