Merge pull request #64028 from nicholasmhughes/add-keyvalue-create_if_missing

[master] file.keyvalue should allow creating a file if it doesn't exist
This commit is contained in:
Megan Wilhite 2023-06-14 19:02:07 +00:00 committed by GitHub
commit 9ab90fdc63
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 42 additions and 2 deletions

1
changelog/63545.added.md Normal file
View file

@ -0,0 +1 @@
Add ability for file.keyvalue to create a file if it doesn't exist

View file

@ -5418,6 +5418,7 @@ def keyvalue(
uncomment=None,
key_ignore_case=False,
value_ignore_case=False,
create_if_missing=False,
):
"""
Key/Value based editing of a file.
@ -5491,6 +5492,11 @@ def keyvalue(
the current value is 'yes', will not result in changes when
``value_ignore_case`` is set to True.
create_if_missing
Create the file if the destination file is not found.
.. versionadded:: 3007.0
An example of using ``file.keyvalue`` to ensure sshd does not allow
for root to login with a password and at the same time setting the
login-gracetime to 1 minute and disabling all forwarding:
@ -5564,6 +5570,14 @@ def keyvalue(
try:
with salt.utils.files.fopen(name, "r") as fd:
file_contents = fd.readlines()
except FileNotFoundError:
if create_if_missing:
append_if_not_found = True
file_contents = []
else:
ret["comment"] = f"unable to open {name}"
ret["result"] = True if ignore_if_missing else False
return ret
except OSError:
ret["comment"] = f"unable to open {name}"
ret["result"] = True if ignore_if_missing else False
@ -5692,8 +5706,6 @@ def keyvalue(
# keys needed searching), the line can be added to the content to be
# written once the last checks have been performed
content.append(line)
# finally, close the file
fd.close()
# if append_if_not_found was requested, then append any key/value pairs
# still having a count left on them

View file

@ -120,3 +120,30 @@ def test_file_keyvalue_not_dict(tmp_path):
f_contents = tempfile.read_text()
assert "PermitRootLogin yes" not in f_contents
assert "#StrictMode yes" in f_contents
def test_file_keyvalue_create_if_missing(tmp_path):
tempfile = tmp_path / "tempfile"
assert not tempfile.exists()
ret = filestate.keyvalue(
name=str(tempfile),
key="myKey",
value="likesIt",
create_if_missing=False,
)
assert ret["result"] is False
assert not tempfile.exists()
ret = filestate.keyvalue(
name=str(tempfile),
key="myKey",
value="likesIt",
create_if_missing=True,
)
assert ret["result"] is True
assert tempfile.exists()
f_contents = tempfile.read_text()
assert "myKey=likesIt" in f_contents
tempfile.unlink()