diff --git a/changelog/62044.added b/changelog/62044.added new file mode 100644 index 000000000000..9a96045d8abc --- /dev/null +++ b/changelog/62044.added @@ -0,0 +1 @@ +Add ignore_missing parameter to file.comment state diff --git a/salt/states/file.py b/salt/states/file.py index 3534b2459500..b29a07058248 100644 --- a/salt/states/file.py +++ b/salt/states/file.py @@ -6004,8 +6004,11 @@ def blockreplace( return ret -def comment(name, regex, char="#", backup=".bak"): +def comment(name, regex, char="#", backup=".bak", ignore_missing=False): """ + .. versionadded:: 0.9.5 + .. versionchanged:: 3005 + Comment out specified lines in a file. name @@ -6030,6 +6033,12 @@ def comment(name, regex, char="#", backup=".bak"): after the first invocation. Set to False/None to not keep a backup. + ignore_missing + Ignore a failure to find the regex in the file. This is useful for + scenarios where a line must only be commented if it is found in the + file. + + .. versionadded:: 3005 Usage: @@ -6039,7 +6048,6 @@ def comment(name, regex, char="#", backup=".bak"): file.comment: - regex: ^bind 127.0.0.1 - .. versionadded:: 0.9.5 """ name = os.path.expanduser(name) @@ -6062,6 +6070,10 @@ def comment(name, regex, char="#", backup=".bak"): ret["comment"] = "Pattern already commented" ret["result"] = True return ret + elif ignore_missing: + ret["comment"] = "Pattern not found and ignore_missing set to True" + ret["result"] = True + return ret else: return _error(ret, "{}: Pattern not found".format(unanchor_regex)) @@ -6070,6 +6082,7 @@ def comment(name, regex, char="#", backup=".bak"): ret["comment"] = "File {} is set to be updated".format(name) ret["result"] = None return ret + with salt.utils.files.fopen(name, "rb") as fp_: slines = fp_.read() slines = slines.decode(__salt_system_encoding__) diff --git a/tests/pytests/unit/states/file/test_comment.py b/tests/pytests/unit/states/file/test_comment.py index 8c655621baee..3ec4ee2bc4bb 100644 --- a/tests/pytests/unit/states/file/test_comment.py +++ b/tests/pytests/unit/states/file/test_comment.py @@ -65,12 +65,20 @@ def test_comment(): with patch.object(os.path, "isabs", mock_t): with patch.dict( filestate.__salt__, - {"file.search": MagicMock(side_effect=[False, True, False, False])}, + { + "file.search": MagicMock( + side_effect=[False, True, False, False, False, False] + ) + }, ): comt = "Pattern already commented" ret.update({"comment": comt, "result": True}) assert filestate.comment(name, regex) == ret + comt = "Pattern not found and ignore_missing set to True" + ret.update({"comment": comt, "result": True}) + assert filestate.comment(name, regex, ignore_missing=True) == ret + comt = "{}: Pattern not found".format(regex) ret.update({"comment": comt, "result": False}) assert filestate.comment(name, regex) == ret