diff --git a/changelogs/fragments/61185-basic.py-fix-check_mode.yaml b/changelogs/fragments/61185-basic.py-fix-check_mode.yaml new file mode 100644 index 00000000000..b05c689b2f1 --- /dev/null +++ b/changelogs/fragments/61185-basic.py-fix-check_mode.yaml @@ -0,0 +1,2 @@ +bugfixes: +- AnsibleModule.set_mode_if_different - don't check file existence when check_mode is activated (https://github.com/ansible/ansible/issues/61185). diff --git a/lib/ansible/module_utils/basic.py b/lib/ansible/module_utils/basic.py index cd2a0553341..3810dc22a32 100644 --- a/lib/ansible/module_utils/basic.py +++ b/lib/ansible/module_utils/basic.py @@ -882,11 +882,12 @@ class AnsibleModule(object): b_path = to_bytes(path, errors='surrogate_or_strict') if expand: b_path = os.path.expanduser(os.path.expandvars(b_path)) - path_stat = os.lstat(b_path) if self.check_file_absent_if_check_mode(b_path): return True + path_stat = os.lstat(b_path) + if not isinstance(mode, int): try: mode = int(mode, 8) diff --git a/test/units/module_utils/basic/test_set_mode_if_different.py b/test/units/module_utils/basic/test_set_mode_if_different.py index 93fe2467f18..5fec331c2e9 100644 --- a/test/units/module_utils/basic/test_set_mode_if_different.py +++ b/test/units/module_utils/basic/test_set_mode_if_different.py @@ -100,6 +100,13 @@ def test_mode_unchanged_when_already_0660(am, mock_stats, mocker, mode, check_mo assert not m_lchmod.called +@pytest.mark.parametrize('mode, stdin', product(SYNONYMS_0660, ({},)), indirect=['stdin']) +def test_mode_changed_to_0660_check_mode_no_file(am, mocker, mode): + am.check_mode = True + mocker.patch('os.path.exists', return_value=False) + assert am.set_mode_if_different('/path/to/file', mode, False) + + @pytest.mark.parametrize('check_mode, stdin', product((True, False), ({},)), indirect=['stdin'])