From 328e58c4391ced65b8cde966c7d3e204772bfb52 Mon Sep 17 00:00:00 2001 From: Sebastian Tobie Date: Mon, 17 Mar 2025 21:10:59 +0100 Subject: [PATCH] improved the filemoving of AnsibleModules and SystemdUnitModule I wrapped the file stuff in an function that is available in AnsibleModule. --- plugins/module_utils/module.py | 70 ++++++++++++++-------------------- 1 file changed, 29 insertions(+), 41 deletions(-) diff --git a/plugins/module_utils/module.py b/plugins/module_utils/module.py index 5d6a6ed..71baaaf 100644 --- a/plugins/module_utils/module.py +++ b/plugins/module_utils/module.py @@ -1,9 +1,9 @@ import pathlib from copy import deepcopy -from typing import (Any, Callable, ClassVar, Dict, NoReturn, Optional, Type, - TypedDict, TypeVar, Union, overload) - +from typing import Any, Callable, ClassVar, Dict, NoReturn, Optional, Type, TypedDict, TypeVar, Union, overload, Generic import ansible.module_utils.basic as basic +import os +import shutil from .generic import AnsibleParameter, Types, systemdbool @@ -18,11 +18,11 @@ __all__ = ( T = TypeVar("T") -class TypedDiff(TypedDict): - before: str - after: str - before_header: Optional[str] - after_header: Optional[str] +class TypedDiff(Generic[T], TypedDict, total=False): + before: T + after: T + before_header: str + after_header: str def docify(input: Union[dict, AnsibleParameter]) -> dict: @@ -78,6 +78,7 @@ class AnsibleModule(object): specs["argument_spec"].update(modspec["argument_spec"]) del modspec["argument_spec"] specs.update(modspec) + self.modspec = specs self.module = basic.AnsibleModule(**specs) self.tmpdir = pathlib.Path(self.module.tmpdir) @@ -114,7 +115,7 @@ class AnsibleModule(object): if diff is not None and not any((before is not None, after is not None)): pass elif all((before is not None, after is not None, diff is None)): - diff = dict( + diff = TypedDiff( before=before, after=after, ) @@ -206,6 +207,24 @@ class AnsibleModule(object): """Wrapper for AnsibleModule.exit_json""" self.module.exit_json(**self.result) + def move_file(self, path: pathlib.Path, dest: pathlib.Path, backup: bool = False, unsafe_writes: bool = False): + """Moves an Temporary file to an destination it uses the args from add_file_common_args when used + + Args: + path: The Path that the file currently is + dest: the location the file should be + backup: should an backup be made before the file is moved + """ + + if backup: + shutil.copy2(dest, dest.with_suffix(dest.suffix + ".bak"), follow_symlinks=False) + self.module.atomic_move(path, dest, unsafe_writes=unsafe_writes, keep_dest_attrs=True) + if "add_file_common_args" in self.modspec and self.modspec["add_file_common_args"]: + file_args = self.module.load_file_common_arguments(self.params, path=dest) + diff = TypedDiff() + self.changed |= self.module.set_fs_attributes_if_different(file_args, diff=diff) + self.diff(diff) + class SystemdUnitModule(AnsibleModule): #: path of the unitfile managed by this module @@ -286,34 +305,6 @@ class SystemdUnitModule(AnsibleModule): path = self.tmpdir / "newunit" with open(path, "w") as unit: unit.write(self.unit()) - self.module.set_owner_if_different(path.as_posix(), "root", False) - self.module.set_group_if_different(path.as_posix(), "root", False) - self.module.set_mode_if_different(path.as_posix(), "0644", False) - if self.unitfile.exists(): - diff = TypedDiff() # type:ignore[reportCallIssue] - self.changed = self.changed | self.module.set_owner_if_different( - self.unitfile.as_posix(), - "root", - self.result["changed"], - diff, - ) - self.diff(diff) - diff = TypedDiff() # type:ignore[reportCallIssue] - self.changed = self.changed | self.module.set_group_if_different( - self.unitfile.as_posix(), - "root", - self.result["changed"], - diff, - ) - self.diff(diff) - diff = TypedDiff() # type:ignore[reportCallIssue] - self.changed = self.changed | self.module.set_mode_if_different( - self.unitfile.as_posix(), - "0644", - self.result["changed"], - diff, - ) - self.diff(diff) def check(self): # pragma: nocover self.set("unitfile", self.unitfile.as_posix()) @@ -334,10 +325,7 @@ class SystemdUnitModule(AnsibleModule): self.check() if not self.changed: return - self.module.atomic_move( - src=(self.tmpdir / "newunit").as_posix(), - dest=self.unitfile.as_posix(), - ) + self.move_file(self.tmpdir / "newunit", self.unitfile) if hasattr(self, "post") and self.post is not None: self.post()