diff --git a/salt/modules/cmdmod.py b/salt/modules/cmdmod.py index 9bb9a4219f25..d27a98d8b8cb 100644 --- a/salt/modules/cmdmod.py +++ b/salt/modules/cmdmod.py @@ -413,7 +413,7 @@ def _get_stripped(cmd): if isinstance(cmd, (list, tuple)): cmd = ' '.join(map(_cmd_quote, cmd)) - cmd = 'su -l {0} -c "{1}"'.format(runas, cmd) + cmd = 'su -l {0} -c "cd {1}; {2}"'.format(runas, cwd, cmd) # set runas to None, because if you try to run `su -l` as well as # simulate the environment macOS will prompt for the password of the # user and will cause salt to hang. diff --git a/tests/unit/modules/test_cmdmod.py b/tests/unit/modules/test_cmdmod.py index 8da672dd229c..dc588e0adc08 100644 --- a/tests/unit/modules/test_cmdmod.py +++ b/tests/unit/modules/test_cmdmod.py @@ -344,6 +344,20 @@ def test_run_cwd_doesnt_exist_issue_7154(self): else: raise RuntimeError + def test_run_cwd_in_combination_with_runas(self): + ''' + cmd.run executes command in the cwd directory + when the runas parameter is specified + ''' + cmd = 'pwd' + cwd = '/tmp' + runas = 'foobar' + + 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) + def test_run_all_binary_replace(self): ''' Test for failed decoding of binary data, for instance when doing