From f7880850dc20fed97600a840d8b814a0bb822b18 Mon Sep 17 00:00:00 2001 From: Sebastian Tobie Date: Sun, 23 Apr 2023 09:23:15 +0200 Subject: [PATCH] added map_param to ease the generation simple parameters for systemd. it reduces the boilerplate for simple key-value parameters --- plugins/module_utils/module.py | 37 +++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/plugins/module_utils/module.py b/plugins/module_utils/module.py index e2d7594..3a4f7d0 100644 --- a/plugins/module_utils/module.py +++ b/plugins/module_utils/module.py @@ -230,22 +230,31 @@ class SystemdUnitModule(AnsibleModule): def header(self) -> str: header = "[Unit]\n" - if self.get("description", False): - header += "Description={}\n".format(self.get("description")) - if self.get("documentation", False): - header += "Documentation={}\n".format(" ".join(self.get("documentation"))) - if self.get("requires", False): - header += "Requires={}\n".format(" ".join(self.get("requires"))) - if self.get("wants", False): - header += "Wants={}\n".format(" ".join(self.get("wants"))) - if self.get("partof", False): - header += "PartOf={}\n".format(" ".join(self.get("partof"))) - if self.get("before", False): - header += "Before={}\n".format(" ".join(self.get("before"))) - if self.get("after", False): - header += "After={}\n".format(" ".join(self.get("after"))) + header += "\n".join( + self.map_param( + description="Description", + documentation="Documentation", + requires="Requires", + wants="Wants", + partof="PartOf", + before="Before", + after="After", + ) + ) return header + def map_param(self, **parammap: str): + """maps an dict with keys for an section with given params. The key of the dictionary is the parameter and the value is the key in the unitfile. If an parameter has multiple values it adds multiple entries""" + output: list[str] = [] + for param, key in parammap: + if self.params[param] is not None: + params = self.params[param] + if isinstance(params, list): + output.extend(("{}={}".format(key, p) for p in params)) + else: + output.append("{}={}".format(key, self.params[param])) + return output + def unitfile_gen(self): path = self.tmpdir / "newunit" with open(path, "w") as unit: