From 7099657dd7279ef2989d601251f46e7407a86fa6 Mon Sep 17 00:00:00 2001 From: Logistic Bot Date: Wed, 28 Apr 2021 10:17:03 +0200 Subject: [PATCH] Basic: don't call lstat when check_mode (#64279) While mode is specified in check_mode, don't call lstat. Since file may not present. Fixes: #61185 --- changelogs/fragments/61185-basic.py-fix-check_mode.yaml | 2 ++ lib/ansible/module_utils/basic.py | 3 ++- .../units/module_utils/basic/test_set_mode_if_different.py | 7 +++++++ 3 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 changelogs/fragments/61185-basic.py-fix-check_mode.yaml 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 37086e360a3..84d6081e5cf 100644 --- a/lib/ansible/module_utils/basic.py +++ b/lib/ansible/module_utils/basic.py @@ -890,11 +890,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'])