From f2e813671a8ce1d776a129e7c8f4ce1f22e94531 Mon Sep 17 00:00:00 2001 From: Sergey <6213510+sshnaidm@users.noreply.github.com> Date: Thu, 26 Jun 2025 13:24:44 +0300 Subject: [PATCH] Run black -l 120 on all files, again (#943) Signed-off-by: Sagi Shnaidman --- plugins/become/podman_unshare.py | 4 +- plugins/connection/buildah.py | 25 +-- plugins/connection/podman.py | 32 +--- plugins/module_utils/podman/common.py | 87 ++------- .../podman/podman_container_lib.py | 174 ++++-------------- plugins/module_utils/podman/podman_pod_lib.py | 84 ++------- plugins/module_utils/podman/quadlet.py | 103 +++-------- plugins/modules/podman_container.py | 4 +- plugins/modules/podman_container_copy.py | 12 +- plugins/modules/podman_container_exec.py | 4 +- plugins/modules/podman_container_info.py | 5 +- plugins/modules/podman_containers.py | 5 +- plugins/modules/podman_export.py | 5 +- plugins/modules/podman_generate_systemd.py | 4 +- plugins/modules/podman_image.py | 137 ++++---------- plugins/modules/podman_image_info.py | 4 +- plugins/modules/podman_import.py | 12 +- plugins/modules/podman_login.py | 6 +- plugins/modules/podman_logout.py | 4 +- plugins/modules/podman_network.py | 91 ++------- plugins/modules/podman_network_info.py | 4 +- plugins/modules/podman_play.py | 44 ++--- plugins/modules/podman_pod_info.py | 4 +- plugins/modules/podman_prune.py | 23 +-- plugins/modules/podman_runlabel.py | 5 +- plugins/modules/podman_save.py | 4 +- plugins/modules/podman_search.py | 6 +- plugins/modules/podman_secret.py | 16 +- plugins/modules/podman_secret_info.py | 4 +- plugins/modules/podman_tag.py | 4 +- plugins/modules/podman_volume.py | 59 ++---- plugins/modules/podman_volume_info.py | 8 +- 32 files changed, 221 insertions(+), 762 deletions(-) diff --git a/plugins/become/podman_unshare.py b/plugins/become/podman_unshare.py index 02d6fd9..3d0ca36 100644 --- a/plugins/become/podman_unshare.py +++ b/plugins/become/podman_unshare.py @@ -137,9 +137,7 @@ class BecomeModule(BecomeBase): # podman unshare should be executed in a login shell to avoid chdir permission errors cmdlist.append("-iu %s" % user) if self.get_option("become_pass"): - self.prompt = ( - "[sudo podman unshare via ansible, key=%s] password:" % self._id - ) + self.prompt = "[sudo podman unshare via ansible, key=%s] password:" % self._id cmdlist.append('-p "%s"' % self.prompt) cmdlist.append("-- %s" % becomecmd) becomecmd = " ".join(cmdlist) diff --git a/plugins/connection/buildah.py b/plugins/connection/buildah.py index ad6ab54..51a77b3 100644 --- a/plugins/connection/buildah.py +++ b/plugins/connection/buildah.py @@ -78,9 +78,7 @@ class Connection(ConnectionBase): display.vvvv("Using buildah connection from collection") def _set_user(self): - self._buildah( - b"config", [b"--user=" + to_bytes(self.user, errors="surrogate_or_strict")] - ) + self._buildah(b"config", [b"--user=" + to_bytes(self.user, errors="surrogate_or_strict")]) def _buildah(self, cmd, cmd_args=None, in_data=None, outfile_stdout=None): """ @@ -143,17 +141,10 @@ class Connection(ConnectionBase): super(Connection, self)._connect() rc, self._mount_point, stderr = self._buildah("mount") if rc != 0: - display.v( - "Failed to mount container %s: %s" - % (self._container_id, stderr.strip()) - ) + display.v("Failed to mount container %s: %s" % (self._container_id, stderr.strip())) else: - self._mount_point = self._mount_point.strip() + to_bytes( - os.path.sep, errors="surrogate_or_strict" - ) - display.vvvv( - "MOUNTPOINT %s RC %s STDERR %r" % (self._mount_point, rc, stderr) - ) + self._mount_point = self._mount_point.strip() + to_bytes(os.path.sep, errors="surrogate_or_strict") + display.vvvv("MOUNTPOINT %s RC %s STDERR %r" % (self._mount_point, rc, stderr)) self._connected = True @ensure_connect @@ -181,9 +172,7 @@ class Connection(ConnectionBase): % (in_path, out_path, self._container_id, stderr) ) else: - real_out_path = self._mount_point + to_bytes( - out_path, errors="surrogate_or_strict" - ) + real_out_path = self._mount_point + to_bytes(out_path, errors="surrogate_or_strict") shutil.copyfile( to_bytes(in_path, errors="surrogate_or_strict"), to_bytes(real_out_path, errors="surrogate_or_strict"), @@ -205,9 +194,7 @@ class Connection(ConnectionBase): % (in_path, out_path, self._container_id, stderr) ) else: - real_in_path = self._mount_point + to_bytes( - in_path, errors="surrogate_or_strict" - ) + real_in_path = self._mount_point + to_bytes(in_path, errors="surrogate_or_strict") shutil.copyfile( to_bytes(real_in_path, errors="surrogate_or_strict"), to_bytes(out_path, errors="surrogate_or_strict"), diff --git a/plugins/connection/podman.py b/plugins/connection/podman.py index 3f351d7..837032c 100644 --- a/plugins/connection/podman.py +++ b/plugins/connection/podman.py @@ -114,11 +114,7 @@ class Connection(ConnectionBase): raise AnsibleError("%s command not found in PATH" % podman_exec) local_cmd = [podman_cmd] if self.get_option("podman_extra_args"): - local_cmd += shlex.split( - to_native( - self.get_option("podman_extra_args"), errors="surrogate_or_strict" - ) - ) + local_cmd += shlex.split(to_native(self.get_option("podman_extra_args"), errors="surrogate_or_strict")) if isinstance(cmd, str): local_cmd.append(cmd) else: @@ -155,21 +151,13 @@ class Connection(ConnectionBase): super(Connection, self)._connect() rc, self._mount_point, stderr = self._podman("mount") if rc != 0: - display.vvvv( - "Failed to mount container %s: %s" - % (self._container_id, stderr.strip()) - ) + display.vvvv("Failed to mount container %s: %s" % (self._container_id, stderr.strip())) elif not os.listdir(self._mount_point.strip()): - display.vvvv( - "Failed to mount container with CGroups2: empty dir %s" - % self._mount_point.strip() - ) + display.vvvv("Failed to mount container with CGroups2: empty dir %s" % self._mount_point.strip()) self._mount_point = None else: self._mount_point = self._mount_point.strip() - display.vvvvv( - "MOUNTPOINT %s RC %s STDERR %r" % (self._mount_point, rc, stderr) - ) + display.vvvvv("MOUNTPOINT %s RC %s STDERR %r" % (self._mount_point, rc, stderr)) self._connected = True @ensure_connect @@ -210,18 +198,14 @@ class Connection(ConnectionBase): % (in_path, out_path, self._container_id, stderr) ) if self.user: - rc, stdout, stderr = self._podman( - "exec", ["chown", self.user, out_path] - ) + rc, stdout, stderr = self._podman("exec", ["chown", self.user, out_path]) if rc != 0: raise AnsibleError( "Failed to chown file %s for user %s in container %s\n%s" % (out_path, self.user, self._container_id, stderr) ) else: - real_out_path = self._mount_point + to_bytes( - out_path, errors="surrogate_or_strict" - ) + real_out_path = self._mount_point + to_bytes(out_path, errors="surrogate_or_strict") shutil.copyfile( to_bytes(in_path, errors="surrogate_or_strict"), to_bytes(real_out_path, errors="surrogate_or_strict"), @@ -243,9 +227,7 @@ class Connection(ConnectionBase): % (in_path, out_path, self._container_id, stderr) ) else: - real_in_path = self._mount_point + to_bytes( - in_path, errors="surrogate_or_strict" - ) + real_in_path = self._mount_point + to_bytes(in_path, errors="surrogate_or_strict") shutil.copyfile( to_bytes(real_in_path, errors="surrogate_or_strict"), to_bytes(out_path, errors="surrogate_or_strict"), diff --git a/plugins/module_utils/podman/common.py b/plugins/module_utils/podman/common.py index 5747a62..03ecbf5 100644 --- a/plugins/module_utils/podman/common.py +++ b/plugins/module_utils/podman/common.py @@ -46,20 +46,14 @@ ARGUMENTS_OPTS_DICT = { } -def run_podman_command( - module, executable="podman", args=None, expected_rc=0, ignore_errors=False -): +def run_podman_command(module, executable="podman", args=None, expected_rc=0, ignore_errors=False): if not isinstance(executable, list): command = [executable] if args is not None: command.extend(args) rc, out, err = module.run_command(command) if not ignore_errors and rc != expected_rc: - module.fail_json( - msg="Failed to run {command} {args}: {err}".format( - command=command, args=args, err=err - ) - ) + module.fail_json(msg="Failed to run {command} {args}: {err}".format(command=command, args=args, err=err)) return rc, out, err @@ -96,11 +90,7 @@ def run_generate_systemd_command(module, module_params, name, version): if (sysconf.get("stop_timeout") is not None) or (sysconf.get("time") is not None): # Select correct parameter name based on version arg_name = "stop-timeout" if gt4ver else "time" - arg_value = ( - sysconf.get("stop_timeout") - if sysconf.get("stop_timeout") is not None - else sysconf.get("time") - ) + arg_value = sysconf.get("stop_timeout") if sysconf.get("stop_timeout") is not None else sysconf.get("time") command.extend(["--%s=%s" % (arg_name, arg_value)]) if sysconf.get("start_timeout") is not None: command.extend(["--start-timeout=%s" % sysconf["start_timeout"]]) @@ -158,9 +148,7 @@ def compare_systemd_file_content(file_path, file_content): # Function to remove comments from file content def remove_comments(content): - return "\n".join( - [line for line in content.splitlines() if not line.startswith("#")] - ) + return "\n".join([line for line in content.splitlines() if not line.startswith("#")]) # Remove comments from both file contents before comparison current_unit_file_content_nocmnt = remove_comments(current_unit_file_content) @@ -170,14 +158,10 @@ def compare_systemd_file_content(file_path, file_content): # Get the different lines between the two contents diff_in_file = [ - line - for line in unit_content_nocmnt.splitlines() - if line not in current_unit_file_content_nocmnt.splitlines() + line for line in unit_content_nocmnt.splitlines() if line not in current_unit_file_content_nocmnt.splitlines() ] diff_in_string = [ - line - for line in current_unit_file_content_nocmnt.splitlines() - if line not in unit_content_nocmnt.splitlines() + line for line in current_unit_file_content_nocmnt.splitlines() if line not in unit_content_nocmnt.splitlines() ] return diff_in_string, diff_in_file @@ -190,9 +174,7 @@ def generate_systemd(module, module_params, name, version): "diff": {}, } sysconf = module_params["generate_systemd"] - rc, systemd, err = run_generate_systemd_command( - module, module_params, name, version - ) + rc, systemd, err = run_generate_systemd_command(module, module_params, name, version) if rc != 0: module.log("PODMAN-CONTAINER-DEBUG: Error generating systemd: %s" % err) if sysconf: @@ -209,8 +191,7 @@ def generate_systemd(module, module_params, name, version): result["changed"] = True if not os.path.isdir(full_path): module.fail_json( - "Path %s is not a directory! " - "Can not save systemd unit files there!" % full_path + "Path %s is not a directory! " "Can not save systemd unit files there!" % full_path ) for file_name, file_content in data.items(): file_name += ".service" @@ -218,42 +199,22 @@ def generate_systemd(module, module_params, name, version): result["changed"] = True if result["diff"].get("before") is None: result["diff"] = {"before": {}, "after": {}} - result["diff"]["before"].update( - { - "systemd_{file_name}.service".format( - file_name=file_name - ): "" - } - ) + result["diff"]["before"].update({"systemd_{file_name}.service".format(file_name=file_name): ""}) result["diff"]["after"].update( - { - "systemd_{file_name}.service".format( - file_name=file_name - ): file_content - } + {"systemd_{file_name}.service".format(file_name=file_name): file_content} ) else: - diff_ = compare_systemd_file_content( - os.path.join(full_path, file_name), file_content - ) + diff_ = compare_systemd_file_content(os.path.join(full_path, file_name), file_content) if diff_: result["changed"] = True if result["diff"].get("before") is None: result["diff"] = {"before": {}, "after": {}} result["diff"]["before"].update( - { - "systemd_{file_name}.service".format( - file_name=file_name - ): "\n".join(diff_[0]) - } + {"systemd_{file_name}.service".format(file_name=file_name): "\n".join(diff_[0])} ) result["diff"]["after"].update( - { - "systemd_{file_name}.service".format( - file_name=file_name - ): "\n".join(diff_[1]) - } + {"systemd_{file_name}.service".format(file_name=file_name): "\n".join(diff_[1])} ) with open(os.path.join(full_path, file_name), "w") as f: f.write(file_content) @@ -290,9 +251,7 @@ def delete_systemd(module, module_params, name, version): # We don't know where systemd files are located, nothing to delete module.log("PODMAN-CONTAINER-DEBUG: Not deleting systemd file - no path!") return - rc, systemd, err = run_generate_systemd_command( - module, module_params, name, version - ) + rc, systemd, err = run_generate_systemd_command(module, module_params, name, version) if rc != 0: module.log("PODMAN-CONTAINER-DEBUG: Error generating systemd: %s" % err) return @@ -390,15 +349,11 @@ def normalize_signal(signal_name_or_number): def get_podman_version(module, fail=True): - executable = ( - module.params["executable"] if module.params["executable"] else "podman" - ) + executable = module.params["executable"] if module.params["executable"] else "podman" rc, out, err = module.run_command([executable, b"--version"]) if rc != 0 or not out or "version" not in out: if fail: - module.fail_json( - msg="'%s --version' run failed! Error: %s" % (executable, err) - ) + module.fail_json(msg="'%s --version' run failed! Error: %s" % (executable, err)) return None return out.split("version")[1].strip() @@ -477,15 +432,7 @@ def diff_generic(params, info_config, module_arg, cmd_arg, boolean_type=False): elif isinstance(after, dict): if module_arg == "log_opt" and "max_size" in after: after["max-size"] = after.pop("max_size") - after = ",".join( - sorted( - [ - str(k).lower() + "=" + str(v).lower() - for k, v in after.items() - if v is not None - ] - ) - ) + after = ",".join(sorted([str(k).lower() + "=" + str(v).lower() for k, v in after.items() if v is not None])) if before: before = ",".join(sorted([j.lower() for j in before])) else: diff --git a/plugins/module_utils/podman/podman_container_lib.py b/plugins/module_utils/podman/podman_container_lib.py index 02f6b12..5f82333 100644 --- a/plugins/module_utils/podman/podman_container_lib.py +++ b/plugins/module_utils/podman/podman_container_lib.py @@ -128,15 +128,11 @@ ARGUMENTS_SPEC_CONTAINER = dict( label=dict(type="dict", aliases=["labels"]), label_file=dict(type="str"), log_driver=dict(type="str", choices=["k8s-file", "journald", "json-file"]), - log_level=dict( - type="str", choices=["debug", "info", "warn", "error", "fatal", "panic"] - ), + log_level=dict(type="str", choices=["debug", "info", "warn", "error", "fatal", "panic"]), log_opt=dict( type="dict", aliases=["log_options"], - options=dict( - max_size=dict(type="str"), path=dict(type="str"), tag=dict(type="str") - ), + options=dict(max_size=dict(type="str"), path=dict(type="str"), tag=dict(type="str")), ), mac_address=dict(type="str"), memory=dict(type="str"), @@ -163,9 +159,7 @@ ARGUMENTS_SPEC_CONTAINER = dict( preserve_fd=dict(type="list", elements="str"), preserve_fds=dict(type="str"), privileged=dict(type="bool"), - publish=dict( - type="list", elements="str", aliases=["ports", "published", "published_ports"] - ), + publish=dict(type="list", elements="str", aliases=["ports", "published", "published_ports"]), publish_all=dict(type="bool"), pull=dict(type="str", choices=["always", "missing", "never", "newer"]), quadlet_dir=dict(type="path"), @@ -244,17 +238,11 @@ def update_options(opts_dict, container): container[key] = container.pop(k) else: key = k - if ARGUMENTS_SPEC_CONTAINER[key]["type"] == "list" and not isinstance( - container[key], list - ): + if ARGUMENTS_SPEC_CONTAINER[key]["type"] == "list" and not isinstance(container[key], list): opts_dict[key] = [container[key]] - elif ARGUMENTS_SPEC_CONTAINER[key]["type"] == "bool" and not isinstance( - container[key], bool - ): + elif ARGUMENTS_SPEC_CONTAINER[key]["type"] == "bool" and not isinstance(container[key], bool): opts_dict[key] = to_bool(container[key]) - elif ARGUMENTS_SPEC_CONTAINER[key]["type"] == "int" and not isinstance( - container[key], int - ): + elif ARGUMENTS_SPEC_CONTAINER[key]["type"] == "int" and not isinstance(container[key], int): opts_dict[key] = int(container[key]) else: opts_dict[key] = container[key] @@ -295,9 +283,7 @@ class PodmanModuleParams: if self.action in ["create", "run"]: cmd = [self.action, "--name", self.params["name"]] all_param_methods = [ - func - for func in dir(self) - if callable(getattr(self, func)) and func.startswith("addparam") + func for func in dir(self) if callable(getattr(self, func)) and func.startswith("addparam") ] params_set = (i for i in self.params if self.params[i] is not None) for param in params_set: @@ -317,11 +303,7 @@ class PodmanModuleParams: def complete_params(cmd): if self.params["attach"] and self.action == "start": cmd.append("--attach") - if ( - self.params["detach"] is False - and self.action == "start" - and "--attach" not in cmd - ): + if self.params["detach"] is False and self.action == "start" and "--attach" not in cmd: cmd.append("--attach") if self.params["detach_keys"] and self.action == "start": cmd += ["--detach-keys", self.params["detach_keys"]] @@ -353,14 +335,12 @@ class PodmanModuleParams: if minv and LooseVersion(minv) > LooseVersion(self.podman_version): self.module.fail_json( msg="Parameter %s is supported from podman " - "version %s only! Current version is %s" - % (param, minv, self.podman_version) + "version %s only! Current version is %s" % (param, minv, self.podman_version) ) if maxv and LooseVersion(maxv) < LooseVersion(self.podman_version): self.module.fail_json( msg="Parameter %s is supported till podman " - "version %s only! Current version is %s" - % (param, minv, self.podman_version) + "version %s only! Current version is %s" % (param, minv, self.podman_version) ) def addparam_annotation(self, c): @@ -504,9 +484,7 @@ class PodmanModuleParams: for env_value in self.params["env"].items(): c += [ "--env", - b"=".join( - [to_bytes(k, errors="surrogate_or_strict") for k in env_value] - ), + b"=".join([to_bytes(k, errors="surrogate_or_strict") for k in env_value]), ] return c @@ -529,9 +507,7 @@ class PodmanModuleParams: for env_merge in self.params["env_merge"].items(): c += [ "--env-merge", - b"=".join( - [to_bytes(k, errors="surrogate_or_strict") for k in env_merge] - ), + b"=".join([to_bytes(k, errors="surrogate_or_strict") for k in env_merge]), ] return c @@ -941,9 +917,7 @@ class PodmanDefaults: def default_dict(self): # make here any changes to self.defaults related to podman version # https://github.com/containers/libpod/pull/5669 - if LooseVersion(self.version) >= LooseVersion("1.8.0") and LooseVersion( - self.version - ) < LooseVersion("1.9.0"): + if LooseVersion(self.version) >= LooseVersion("1.8.0") and LooseVersion(self.version) < LooseVersion("1.9.0"): self.defaults["cpu_shares"] = 1024 if LooseVersion(self.version) >= LooseVersion("3.0.0"): self.defaults["log_level"] = "warning" @@ -994,9 +968,7 @@ class PodmanContainerDiff: """ info_config = self.info["config"] - before, after = diff_generic( - self.params, info_config, module_arg, cmd_arg, boolean_type - ) + before, after = diff_generic(self.params, info_config, module_arg, cmd_arg, boolean_type) return self._diff_update_and_compare(module_arg, before, after) def diffparam_annotation(self): @@ -1174,9 +1146,7 @@ class PodmanContainerDiff: def diffparam_etc_hosts(self): if self.info["hostconfig"]["extrahosts"]: - before = dict( - [i.split(":", 1) for i in self.info["hostconfig"]["extrahosts"]] - ) + before = dict([i.split(":", 1) for i in self.info["hostconfig"]["extrahosts"]]) else: before = {} after = self.params["etc_hosts"] or {} @@ -1215,9 +1185,7 @@ class PodmanContainerDiff: else: before = "" after = self.params["healthcheck_failure_action"] or before - return self._diff_update_and_compare( - "healthcheckonfailureaction", before, after - ) + return self._diff_update_and_compare("healthcheckonfailureaction", before, after) def diffparam_healthcheck_interval(self): return self._diff_generic("healthcheck_interval", "--healthcheck-interval") @@ -1226,17 +1194,13 @@ class PodmanContainerDiff: return self._diff_generic("healthcheck_retries", "--healthcheck-retries") def diffparam_healthcheck_start_period(self): - return self._diff_generic( - "healthcheck_start_period", "--healthcheck-start-period" - ) + return self._diff_generic("healthcheck_start_period", "--healthcheck-start-period") def diffparam_health_startup_cmd(self): return self._diff_generic("health_startup_cmd", "--health-startup-cmd") def diffparam_health_startup_interval(self): - return self._diff_generic( - "health_startup_interval", "--health-startup-interval" - ) + return self._diff_generic("health_startup_interval", "--health-startup-interval") def diffparam_health_startup_retries(self): return self._diff_generic("health_startup_retries", "--health-startup-retries") @@ -1309,9 +1273,7 @@ class PodmanContainerDiff: before = self.info["config"]["labels"] or {} after = self.image_info.get("labels") or {} if self.params["label"]: - after.update( - {str(k).lower(): str(v) for k, v in self.params["label"].items()} - ) + after.update({str(k).lower(): str(v) for k, v in self.params["label"].items()}) # Strip out labels that are coming from systemd files # https://github.com/containers/ansible-podman-collections/issues/276 if "podman_systemd_unit" in before: @@ -1353,9 +1315,7 @@ class PodmanContainerDiff: return self._diff_generic("network_aliases", "--network-alias") def diffparam_no_healthcheck(self): - return self._diff_generic( - "no_healthcheck", "--no-healthcheck", boolean_type=True - ) + return self._diff_generic("no_healthcheck", "--no-healthcheck", boolean_type=True) def diffparam_no_hosts(self): return self._diff_generic("no_hosts", "--no-hosts") @@ -1505,15 +1465,7 @@ class PodmanContainerDiff: if before is None and after is None: return self._diff_update_and_compare("tmpfs", before, after) if after is not None: - after = ",".join( - sorted( - [ - str(k).lower() + ":" + str(v).lower() - for k, v in after.items() - if v is not None - ] - ) - ) + after = ",".join(sorted([str(k).lower() + ":" + str(v).lower() for k, v in after.items() if v is not None])) if before: before = ",".join(sorted([j.lower() for j in before])) else: @@ -1559,14 +1511,9 @@ class PodmanContainerDiff: before = None after = self.params["volume"] if after is not None: - after = [ - ":".join([clean_volume(i) for i in v.split(":")[:3]]) - for v in self.params["volume"] - ] + after = [":".join([clean_volume(i) for i in v.split(":")[:3]]) for v in self.params["volume"]] if before is not None: - before = [ - ":".join([clean_volume(i) for i in v.split(":")[:3]]) for v in before - ] + before = [":".join([clean_volume(i) for i in v.split(":")[:3]]) for v in before] if before is None and after is None: return self._diff_update_and_compare("volume", before, after) if after is not None: @@ -1582,11 +1529,7 @@ class PodmanContainerDiff: return self._diff_generic("workdir", "--workdir") def is_different(self): - diff_func_list = [ - func - for func in dir(self) - if callable(getattr(self, func)) and func.startswith("diffparam") - ] + diff_func_list = [func for func in dir(self) if callable(getattr(self, func)) and func.startswith("diffparam")] fail_fast = not bool(self.module._diff) different = False for func_name in diff_func_list: @@ -1695,18 +1638,8 @@ class PodmanContainer: is_different = diffcheck.is_different() diffs = diffcheck.diff if self.module._diff and is_different and diffs["before"] and diffs["after"]: - self.diff["before"] = ( - "\n".join( - ["%s - %s" % (k, v) for k, v in sorted(diffs["before"].items())] - ) - + "\n" - ) - self.diff["after"] = ( - "\n".join( - ["%s - %s" % (k, v) for k, v in sorted(diffs["after"].items())] - ) - + "\n" - ) + self.diff["before"] = "\n".join(["%s - %s" % (k, v) for k, v in sorted(diffs["before"].items())]) + "\n" + self.diff["after"] = "\n".join(["%s - %s" % (k, v) for k, v in sorted(diffs["after"].items())]) + "\n" return is_different @property @@ -1722,9 +1655,7 @@ class PodmanContainer: def get_info(self): """Inspect container and gather info about it.""" # pylint: disable=unused-variable - rc, out, err = self.module.run_command( - [self.module_params["executable"], b"container", b"inspect", self.name] - ) + rc, out, err = self.module.run_command([self.module_params["executable"], b"container", b"inspect", self.name]) return json.loads(out)[0] if rc == 0 else {} def get_image_info(self): @@ -1741,20 +1672,14 @@ class PodmanContainer: self.module_params["image"].replace("docker://", ""), ] ) - self.module.log( - "PODMAN-CONTAINER-DEBUG: %s: %s" % (out, self.module_params["image"]) - ) + self.module.log("PODMAN-CONTAINER-DEBUG: %s: %s" % (out, self.module_params["image"])) return json.loads(out)[0] if rc == 0 else {} def _get_podman_version(self): # pylint: disable=unused-variable - rc, out, err = self.module.run_command( - [self.module_params["executable"], b"--version"] - ) + rc, out, err = self.module.run_command([self.module_params["executable"], b"--version"]) if rc != 0 or not out or "version" not in out: - self.module.fail_json( - msg="%s run failed!" % self.module_params["executable"] - ) + self.module.fail_json(msg="%s run failed!" % self.module_params["executable"]) return out.split("version")[1].strip() def _perform_action(self, action): @@ -1770,9 +1695,7 @@ class PodmanContainer: self.version, self.module, ).construct_command_from_params() - full_cmd = " ".join( - [self.module_params["executable"]] + [to_native(i) for i in b_command] - ) + full_cmd = " ".join([self.module_params["executable"]] + [to_native(i) for i in b_command]) self.actions.append(full_cmd) if self.module.check_mode: self.module.log("PODMAN-CONTAINER-DEBUG (check_mode): %s" % full_cmd) @@ -1790,8 +1713,7 @@ class PodmanContainer: self.stderr = err if rc != 0: self.module.fail_json( - msg="Container %s exited with code %s when %sed" - % (self.name, rc, action), + msg="Container %s exited with code %s when %sed" % (self.name, rc, action), stdout=out, stderr=err, ) @@ -1858,18 +1780,12 @@ class PodmanManager: } self.module_params = params self.name = self.module_params["name"] - self.executable = self.module.get_bin_path( - self.module_params["executable"], required=True - ) + self.executable = self.module.get_bin_path(self.module_params["executable"], required=True) self.image = self.module_params["image"] self.state = self.module_params["state"] - disable_image_pull = ( - self.state in ("quadlet", "absent") or self.module_params["pull"] == "never" - ) + disable_image_pull = self.state in ("quadlet", "absent") or self.module_params["pull"] == "never" image_actions = ( - ensure_image_exists(self.module, self.image, self.module_params) - if not disable_image_pull - else [] + ensure_image_exists(self.module, self.image, self.module_params) if not disable_image_pull else [] ) self.results["actions"] += image_actions @@ -1903,9 +1819,7 @@ class PodmanManager: self.results.update({"diff": self.container.diff}) if self.module.params["debug"] or self.module_params["debug"]: self.results.update({"podman_version": self.container.version}) - sysd = generate_systemd( - self.module, self.module_params, self.name, self.container.version - ) + sysd = generate_systemd(self.module, self.module_params, self.name, self.container.version) self.results["changed"] = changed or sysd["changed"] self.results.update({"podman_systemd": sysd["systemd"]}) if sysd["diff"]: @@ -1922,9 +1836,7 @@ class PodmanManager: """Run actions if desired state is 'started'.""" if not self.image: if not self.container.exists: - self.module.fail_json( - msg="Cannot start container when image" " is not specified!" - ) + self.module.fail_json(msg="Cannot start container when image" " is not specified!") if self.restart: self.container.restart() self.results["actions"].append("restarted %s" % self.container.name) @@ -1974,9 +1886,7 @@ class PodmanManager: def make_created(self): """Run actions if desired state is 'created'.""" if not self.container.exists and not self.image: - self.module.fail_json( - msg="Cannot create container when image" " is not specified!" - ) + self.module.fail_json(msg="Cannot create container when image" " is not specified!") if not self.container.exists: self.container.create() self.results["actions"].append("created %s" % self.container.name) @@ -2006,9 +1916,7 @@ class PodmanManager: def make_stopped(self): """Run actions if desired state is 'stopped'.""" if not self.container.exists and not self.image: - self.module.fail_json( - msg="Cannot create container when image" " is not specified!" - ) + self.module.fail_json(msg="Cannot create container when image" " is not specified!") if not self.container.exists: self.container.create() self.results["actions"].append("created %s" % self.container.name) @@ -2028,9 +1936,7 @@ class PodmanManager: if not self.container.exists: self.results.update({"changed": False}) elif self.container.exists: - delete_systemd( - self.module, self.module_params, self.name, self.container.version - ) + delete_systemd(self.module, self.module_params, self.name, self.container.version) self.container.delete() self.results["actions"].append("deleted %s" % self.container.name) self.results.update({"changed": True}) diff --git a/plugins/module_utils/podman/podman_pod_lib.py b/plugins/module_utils/podman/podman_pod_lib.py index d9afff5..e668bc9 100644 --- a/plugins/module_utils/podman/podman_pod_lib.py +++ b/plugins/module_utils/podman/podman_pod_lib.py @@ -78,9 +78,7 @@ ARGUMENTS_SPEC_POD = dict( memory_swap=dict(type="str", required=False), name=dict(type="str", required=True), network=dict(type="list", elements="str", required=False), - network_alias=dict( - type="list", elements="str", required=False, aliases=["network_aliases"] - ), + network_alias=dict(type="list", elements="str", required=False, aliases=["network_aliases"]), no_hosts=dict(type="bool", required=False), pid=dict(type="str", required=False), pod_id_file=dict(type="str", required=False), @@ -157,9 +155,7 @@ class PodmanPodModuleParams: def _create_action(self): cmd = [self.action] all_param_methods = [ - func - for func in dir(self) - if callable(getattr(self, func)) and func.startswith("addparam") + func for func in dir(self) if callable(getattr(self, func)) and func.startswith("addparam") ] params_set = (i for i in self.params if self.params[i] is not None) for param in params_set: @@ -172,14 +168,12 @@ class PodmanPodModuleParams: if minv and LooseVersion(minv) > LooseVersion(self.podman_version): self.module.fail_json( msg="Parameter %s is supported from podman " - "version %s only! Current version is %s" - % (param, minv, self.podman_version) + "version %s only! Current version is %s" % (param, minv, self.podman_version) ) if maxv and LooseVersion(maxv) < LooseVersion(self.podman_version): self.module.fail_json( msg="Parameter %s is supported till podman " - "version %s only! Current version is %s" - % (param, minv, self.podman_version) + "version %s only! Current version is %s" % (param, minv, self.podman_version) ) def addparam_add_host(self, c): @@ -459,9 +453,7 @@ class PodmanPodDiff: """ info_config = self.info - before, after = diff_generic( - self.params, info_config, module_arg, cmd_arg, boolean_type - ) + before, after = diff_generic(self.params, info_config, module_arg, cmd_arg, boolean_type) return self._diff_update_and_compare(module_arg, before, after) def diffparam_add_host(self): @@ -643,14 +635,9 @@ class PodmanPodDiff: before = None after = self.params["volume"] if after is not None: - after = [ - ":".join([clean_volume(i) for i in v.split(":")[:2]]) - for v in self.params["volume"] - ] + after = [":".join([clean_volume(i) for i in v.split(":")[:2]]) for v in self.params["volume"]] if before is not None: - before = [ - ":".join([clean_volume(i) for i in v.split(":")[:2]]) for v in before - ] + before = [":".join([clean_volume(i) for i in v.split(":")[:2]]) for v in before] self.module.log("PODMAN Before: %s and After: %s" % (before, after)) if before is None and after is None: return self._diff_update_and_compare("volume", before, after) @@ -664,11 +651,7 @@ class PodmanPodDiff: return self._diff_generic("volumes_from", "--volumes-from") def is_different(self): - diff_func_list = [ - func - for func in dir(self) - if callable(getattr(self, func)) and func.startswith("diffparam") - ] + diff_func_list = [func for func in dir(self) if callable(getattr(self, func)) and func.startswith("diffparam")] fail_fast = not bool(self.module._diff) different = False for func_name in diff_func_list: @@ -720,24 +703,12 @@ class PodmanPod: @property def different(self): """Check if pod is different.""" - diffcheck = PodmanPodDiff( - self.module, self.module_params, self.info, self.infra_info, self.version - ) + diffcheck = PodmanPodDiff(self.module, self.module_params, self.info, self.infra_info, self.version) is_different = diffcheck.is_different() diffs = diffcheck.diff if self.module._diff and is_different and diffs["before"] and diffs["after"]: - self.diff["before"] = ( - "\n".join( - ["%s - %s" % (k, v) for k, v in sorted(diffs["before"].items())] - ) - + "\n" - ) - self.diff["after"] = ( - "\n".join( - ["%s - %s" % (k, v) for k, v in sorted(diffs["after"].items())] - ) - + "\n" - ) + self.diff["before"] = "\n".join(["%s - %s" % (k, v) for k, v in sorted(diffs["before"].items())]) + "\n" + self.diff["after"] = "\n".join(["%s - %s" % (k, v) for k, v in sorted(diffs["after"].items())]) + "\n" return is_different @property @@ -771,9 +742,7 @@ class PodmanPod: def get_info(self): """Inspect pod and gather info about it.""" # pylint: disable=unused-variable - rc, out, err = self.module.run_command( - [self.module_params["executable"], b"pod", b"inspect", self.name] - ) + rc, out, err = self.module.run_command([self.module_params["executable"], b"pod", b"inspect", self.name]) if rc == 0: info = json.loads(out) # from podman 5 onwards, this is a list of dicts, @@ -812,20 +781,14 @@ class PodmanPod: else: return {} # pylint: disable=unused-variable - rc, out, err = self.module.run_command( - [self.module_params["executable"], b"inspect", infra_container_id] - ) + rc, out, err = self.module.run_command([self.module_params["executable"], b"inspect", infra_container_id]) return json.loads(out)[0] if rc == 0 else {} def _get_podman_version(self): # pylint: disable=unused-variable - rc, out, err = self.module.run_command( - [self.module_params["executable"], b"--version"] - ) + rc, out, err = self.module.run_command([self.module_params["executable"], b"--version"]) if rc != 0 or not out or "version" not in out: - self.module.fail_json( - msg="%s run failed!" % self.module_params["executable"] - ) + self.module.fail_json(msg="%s run failed!" % self.module_params["executable"]) return out.split("version")[1].strip() def _perform_action(self, action): @@ -841,10 +804,7 @@ class PodmanPod: self.version, self.module, ).construct_command_from_params() - full_cmd = " ".join( - [self.module_params["executable"], "pod"] - + [to_native(i) for i in b_command] - ) + full_cmd = " ".join([self.module_params["executable"], "pod"] + [to_native(i) for i in b_command]) self.module.log("PODMAN-POD-DEBUG: %s" % full_cmd) self.actions.append(full_cmd) if not self.module.check_mode: @@ -855,9 +815,7 @@ class PodmanPod: self.stdout = out self.stderr = err if rc != 0: - self.module.fail_json( - msg="Can't %s pod %s" % (action, self.name), stdout=out, stderr=err - ) + self.module.fail_json(msg="Can't %s pod %s" % (action, self.name), stdout=out, stderr=err) def delete(self): """Delete the pod.""" @@ -918,9 +876,7 @@ class PodmanPodManager: "pod": {}, } self.name = self.module_params["name"] - self.executable = self.module.get_bin_path( - self.module_params["executable"], required=True - ) + self.executable = self.module.get_bin_path(self.module_params["executable"], required=True) self.state = self.module_params["state"] self.recreate = self.module_params["recreate"] self.pod = PodmanPod(self.module, self.name, self.module_params) @@ -945,9 +901,7 @@ class PodmanPodManager: self.results.update({"diff": self.pod.diff}) if self.module.params["debug"] or self.module_params["debug"]: self.results.update({"podman_version": self.pod.version}) - sysd = generate_systemd( - self.module, self.module_params, self.name, self.pod.version - ) + sysd = generate_systemd(self.module, self.module_params, self.name, self.pod.version) self.results["changed"] = changed or sysd["changed"] self.results.update({"podman_systemd": sysd["systemd"]}) if sysd["diff"]: diff --git a/plugins/module_utils/podman/quadlet.py b/plugins/module_utils/podman/quadlet.py index dd4285a..8d1080e 100644 --- a/plugins/module_utils/podman/quadlet.py +++ b/plugins/module_utils/podman/quadlet.py @@ -55,14 +55,9 @@ class Quadlet: Construct the quadlet content as a string. """ custom_user_options = self.custom_params.get("quadlet_options") - custom_text = ( - "\n" + "\n".join(custom_user_options) if custom_user_options else "" - ) + custom_text = "\n" + "\n".join(custom_user_options) if custom_user_options else "" return ( - f"[{self.section}]\n" - + "\n".join(f"{key}={value}" for key, value in self.dict_params) - + custom_text - + "\n" + f"[{self.section}]\n" + "\n".join(f"{key}={value}" for key, value in self.dict_params) + custom_text + "\n" ) def write_to_file(self, path: str): @@ -167,9 +162,7 @@ class ContainerQuadlet(Quadlet): """ # Work on params in params_map and convert them to a right form if params["annotation"]: - params["annotation"] = [ - "%s=%s" % (k, v) for k, v in params["annotation"].items() - ] + params["annotation"] = ["%s=%s" % (k, v) for k, v in params["annotation"].items()] if params["cap_add"]: params["cap_add"] = " ".join(params["cap_add"]) if params["cap_drop"]: @@ -181,22 +174,16 @@ class ContainerQuadlet(Quadlet): else params["command"] ) if params["label"]: - params["label"] = [ - shlex.quote("%s=%s" % (k, v)) for k, v in params["label"].items() - ] + params["label"] = [shlex.quote("%s=%s" % (k, v)) for k, v in params["label"].items()] if params["env"]: - params["env"] = [ - shlex.quote("%s=%s" % (k, v)) for k, v in params["env"].items() - ] + params["env"] = [shlex.quote("%s=%s" % (k, v)) for k, v in params["env"].items()] if params["rootfs"]: params["rootfs"] = params["image"] params["image"] = None if params["sysctl"]: params["sysctl"] = ["%s=%s" % (k, v) for k, v in params["sysctl"].items()] if params["tmpfs"]: - params["tmpfs"] = [ - "%s:%s" % (k, v) if v else k for k, v in params["tmpfs"].items() - ] + params["tmpfs"] = ["%s:%s" % (k, v) if v else k for k, v in params["tmpfs"].items()] # Work on params which are not in the param_map but can be calculated params["global_args"] = [] @@ -227,10 +214,7 @@ class ContainerQuadlet(Quadlet): if params["blkio_weight_device"]: params["podman_args"].append( " ".join( - [ - f"--blkio-weight-device {':'.join(blkio)}" - for blkio in params["blkio_weight_device"].items() - ] + [f"--blkio-weight-device {':'.join(blkio)}" for blkio in params["blkio_weight_device"].items()] ) ) if params["cgroupns"]: @@ -265,9 +249,7 @@ class ContainerQuadlet(Quadlet): if params["decryption_key"]: params["podman_args"].append(f"--decryption-key {params['decryption_key']}") if params["device_cgroup_rule"]: - params["podman_args"].append( - f"--device-cgroup-rule {params['device_cgroup_rule']}" - ) + params["podman_args"].append(f"--device-cgroup-rule {params['device_cgroup_rule']}") if params["device_read_bps"]: for i in params["device_read_bps"]: params["podman_args"].append(f"--device-read-bps {i}") @@ -281,9 +263,7 @@ class ContainerQuadlet(Quadlet): for i in params["device_write_iops"]: params["podman_args"].append(f"--device-write-iops {i}") if params["etc_hosts"]: - params["etc_hosts"] = [ - "%s:%s" % (k, v) for k, v in params["etc_hosts"].items() - ] + params["etc_hosts"] = ["%s:%s" % (k, v) for k, v in params["etc_hosts"].items()] if params["env_merge"]: for k, v in params["env_merge"].items(): params["podman_args"].append(f"--env {k}={v}") @@ -314,32 +294,24 @@ class ContainerQuadlet(Quadlet): params["podman_args"].append(f"--label-file {params['label_file']}") if params["log_opt"]: params["log_opt"] = [ - "%s=%s" % (k.replace("max_size", "max-size"), v) - for k, v in params["log_opt"].items() - if v is not None + "%s=%s" % (k.replace("max_size", "max-size"), v) for k, v in params["log_opt"].items() if v is not None ] if params["mac_address"]: params["podman_args"].append(f"--mac-address {params['mac_address']}") if params["memory"]: params["podman_args"].append(f"--memory {params['memory']}") if params["memory_reservation"]: - params["podman_args"].append( - f"--memory-reservation {params['memory_reservation']}" - ) + params["podman_args"].append(f"--memory-reservation {params['memory_reservation']}") if params["memory_swap"]: params["podman_args"].append(f"--memory-swap {params['memory_swap']}") if params["memory_swappiness"]: - params["podman_args"].append( - f"--memory-swappiness {params['memory_swappiness']}" - ) + params["podman_args"].append(f"--memory-swappiness {params['memory_swappiness']}") if params["no_healthcheck"]: params["podman_args"].append("--no-healthcheck") if params["no_hosts"] is not None: params["podman_args"].append(f"--no-hosts={params['no_hosts']}") if params["oom_kill_disable"]: - params["podman_args"].append( - f"--oom-kill-disable={params['oom_kill_disable']}" - ) + params["podman_args"].append(f"--oom-kill-disable={params['oom_kill_disable']}") if params["oom_score_adj"]: params["podman_args"].append(f"--oom-score-adj {params['oom_score_adj']}") if params["os"]: @@ -385,9 +357,7 @@ class ContainerQuadlet(Quadlet): for security_opt in params["security_opt"]: params["podman_args"].append(f"--security-opt {security_opt}") if params["shm_size_systemd"]: - params["podman_args"].append( - f"--shm-size-systemd {params['shm_size_systemd']}" - ) + params["podman_args"].append(f"--shm-size-systemd {params['shm_size_systemd']}") if params["sig_proxy"]: params["podman_args"].append(f"--sig-proxy {params['sig_proxy']}") if params["systemd"]: @@ -395,9 +365,7 @@ class ContainerQuadlet(Quadlet): if params["timeout"]: params["podman_args"].append(f"--timeout {params['timeout']}") if params["tls_verify"]: - params["podman_args"].append( - f"--tls-verify={str(params['tls_verify']).lower()}" - ) + params["podman_args"].append(f"--tls-verify={str(params['tls_verify']).lower()}") if params["tty"]: params["podman_args"].append("--tty") if params["umask"]: @@ -493,10 +461,7 @@ class PodQuadlet(Quadlet): if params["blkio_weight_device"]: params["podman_args"].append( " ".join( - [ - f"--blkio-weight-device {':'.join(blkio)}" - for blkio in params["blkio_weight_device"].items() - ] + [f"--blkio-weight-device {':'.join(blkio)}" for blkio in params["blkio_weight_device"].items()] ) ) if params["cpuset_cpus"]: @@ -539,9 +504,7 @@ class PodQuadlet(Quadlet): if params["infra_command"]: params["podman_args"].append(f"--infra-command {params['infra_command']}") if params["infra_conmon_pidfile"]: - params["podman_args"].append( - f"--infra-conmon-pidfile {params['infra_conmon_pidfile']}" - ) + params["podman_args"].append(f"--infra-conmon-pidfile {params['infra_conmon_pidfile']}") if params["infra_image"]: params["podman_args"].append(f"--infra-image {params['infra_image']}") if params["infra_name"]: @@ -575,15 +538,11 @@ class PodQuadlet(Quadlet): if params["share"]: params["podman_args"].append(f"--share {params['share']}") if params["share_parent"] is not None: - params["podman_args"].append( - f"--share-parent={str(params['share_parent']).lower()}" - ) + params["podman_args"].append(f"--share-parent={str(params['share_parent']).lower()}") if params["shm_size"]: params["podman_args"].append(f"--shm-size {params['shm_size']}") if params["shm_size_systemd"]: - params["podman_args"].append( - f"--shm-size-systemd {params['shm_size_systemd']}" - ) + params["podman_args"].append(f"--shm-size-systemd {params['shm_size_systemd']}") if params["subgidname"]: params["podman_args"].append(f"--subgidname {params['subgidname']}") if params["subuidname"]: @@ -722,9 +681,7 @@ def check_quadlet_directory(module, quadlet_dir): except Exception as e: module.fail_json(msg="Directory for quadlet_file can't be created: %s" % e) if not os.access(quadlet_dir, os.W_OK): - module.fail_json( - msg="Directory for quadlet_file is not writable: %s" % quadlet_dir - ) + module.fail_json(msg="Directory for quadlet_file is not writable: %s" % quadlet_dir) def create_quadlet_state(module, issuer): @@ -747,9 +704,7 @@ def create_quadlet_state(module, issuer): quadlet_dir = os.path.expanduser(QUADLET_NON_ROOT_PATH) # Create a filename based on the issuer if not module.params.get("name") and not module.params.get("quadlet_filename"): - module.fail_json( - msg=f"Filename for {issuer} is required for creating a quadlet file." - ) + module.fail_json(msg=f"Filename for {issuer} is required for creating a quadlet file.") if issuer == "image": name = module.params["name"].split("/")[-1].split(":")[0] else: @@ -779,24 +734,14 @@ def create_quadlet_state(module, issuer): results_update = { "changed": True, "diff": { - "before": ( - "\n".join(file_diff[0]) - if isinstance(file_diff[0], list) - else file_diff[0] + "\n" - ), - "after": ( - "\n".join(file_diff[1]) - if isinstance(file_diff[1], list) - else file_diff[1] + "\n" - ), + "before": ("\n".join(file_diff[0]) if isinstance(file_diff[0], list) else file_diff[0] + "\n"), + "after": ("\n".join(file_diff[1]) if isinstance(file_diff[1], list) else file_diff[1] + "\n"), }, } else: # adjust file permissions diff = {} - if mode is not None and module.set_mode_if_different( - quadlet_file_path, mode, False, diff - ): + if mode is not None and module.set_mode_if_different(quadlet_file_path, mode, False, diff): results_update = {"changed": True, "diff": diff} else: results_update = {} diff --git a/plugins/modules/podman_container.py b/plugins/modules/podman_container.py index 4029952..922b8df 100644 --- a/plugins/modules/podman_container.py +++ b/plugins/modules/podman_container.py @@ -1540,9 +1540,7 @@ def main(): and not module.params["force_restart"] and not module.params["image"] ): - module.fail_json( - msg="State '%s' required image to be configured!" % module.params["state"] - ) + module.fail_json(msg="State '%s' required image to be configured!" % module.params["state"]) results = PodmanManager(module, module.params).execute() module.exit_json(**results) diff --git a/plugins/modules/podman_container_copy.py b/plugins/modules/podman_container_copy.py index 6dc7eb7..37ba2f3 100644 --- a/plugins/modules/podman_container_copy.py +++ b/plugins/modules/podman_container_copy.py @@ -74,9 +74,7 @@ EXAMPLES = r""" from ansible.module_utils.basic import AnsibleModule -def copy_file( - module, executable, src, dest, container, from_container, archive, overwrite -): +def copy_file(module, executable, src, dest, container, from_container, archive, overwrite): if from_container: command = [executable, "cp", "{0}:{1}".format(container, src), dest] else: @@ -91,9 +89,7 @@ def copy_file( rc, out, err = module.run_command(command) if rc != 0: - module.fail_json( - msg="Unable to copy file to/from container - {out}".format(out=err) - ) + module.fail_json(msg="Unable to copy file to/from container - {out}".format(out=err)) else: changed = True return changed, out, err @@ -123,9 +119,7 @@ def main(): executable = module.get_bin_path(executable, required=True) - changed, out, err = copy_file( - module, executable, src, dest, container, from_container, archive, overwrite - ) + changed, out, err = copy_file(module, executable, src, dest, container, from_container, archive, overwrite) results = dict(changed=changed) diff --git a/plugins/modules/podman_container_exec.py b/plugins/modules/podman_container_exec.py index a00d655..8d92642 100644 --- a/plugins/modules/podman_container_exec.py +++ b/plugins/modules/podman_container_exec.py @@ -160,9 +160,7 @@ def run_container_exec(module: AnsibleModule) -> dict: if env is not None: for key, value in env.items(): if not isinstance(value, string_types): - module.fail_json( - msg="Specify string value %s on the env field" % (value) - ) + module.fail_json(msg="Specify string value %s on the env field" % (value)) to_text(value, errors="surrogate_or_strict") exec_options += ["--env", "%s=%s" % (key, value)] diff --git a/plugins/modules/podman_container_info.py b/plugins/modules/podman_container_info.py index bb2ea40..1693f74 100644 --- a/plugins/modules/podman_container_info.py +++ b/plugins/modules/podman_container_info.py @@ -349,10 +349,7 @@ def get_containers_facts(module, executable, name): retry += 1 rc, out, err = module.run_command(all_names) if rc != 0: - module.fail_json( - msg="Unable to get list of containers during" - " %s retries" % retry_limit - ) + module.fail_json(msg="Unable to get list of containers during" " %s retries" % retry_limit) name = out.split() if not name: return [], out, err diff --git a/plugins/modules/podman_containers.py b/plugins/modules/podman_containers.py index 1b7bc8a..e8c4d4a 100644 --- a/plugins/modules/podman_containers.py +++ b/plugins/modules/podman_containers.py @@ -117,10 +117,7 @@ def main(): options_dict["debug"] = module.params["debug"] or options_dict["debug"] test_input = check_input_strict(options_dict) if test_input: - module.fail_json( - msg="Failed to run container %s because: %s" - % (options_dict["name"], test_input) - ) + module.fail_json(msg="Failed to run container %s because: %s" % (options_dict["name"], test_input)) res = PodmanManager(module, options_dict).execute() results.append(res) total_results = combine(results) diff --git a/plugins/modules/podman_export.py b/plugins/modules/podman_export.py index 11e04d4..d430d45 100644 --- a/plugins/modules/podman_export.py +++ b/plugins/modules/podman_export.py @@ -89,10 +89,7 @@ def export(module, executable): return changed, "", "" rc, out, err = module.run_command(command) if rc != 0: - module.fail_json( - msg="Error exporting %s %s: %s" - % (export_type, module.params["container"], err) - ) + module.fail_json(msg="Error exporting %s %s: %s" % (export_type, module.params["container"], err)) return changed, out, err diff --git a/plugins/modules/podman_generate_systemd.py b/plugins/modules/podman_generate_systemd.py index 7894a2d..5733582 100644 --- a/plugins/modules/podman_generate_systemd.py +++ b/plugins/modules/podman_generate_systemd.py @@ -463,9 +463,7 @@ def generate_systemd(module): need_to_write_file = True else: # See if we need to write the unit file, default yes - need_to_write_file = bool( - compare_systemd_file_content(unit_file_full_path, unit_content) - ) + need_to_write_file = bool(compare_systemd_file_content(unit_file_full_path, unit_content)) # Write the file, if needed if need_to_write_file: diff --git a/plugins/modules/podman_image.py b/plugins/modules/podman_image.py index 106e64e..0fc25ff 100644 --- a/plugins/modules/podman_image.py +++ b/plugins/modules/podman_image.py @@ -454,9 +454,7 @@ class PodmanImageManager(object): self.module = module self.results = results self.name = self.module.params.get("name") - self.executable = self.module.get_bin_path( - module.params.get("executable"), required=True - ) + self.executable = self.module.get_bin_path(module.params.get("executable"), required=True) self.tag = self.module.params.get("tag") self.pull = self.module.params.get("pull") self.pull_extra_args = self.module.params.get("pull_extra_args") @@ -479,9 +477,7 @@ class PodmanImageManager(object): self.tag = repo_tag delimiter = ":" if "sha256" not in self.tag else "@" - self.image_name = "{name}{d}{tag}".format( - name=self.name, d=delimiter, tag=self.tag - ) + self.image_name = "{name}{d}{tag}".format(name=self.name, d=delimiter, tag=self.tag) if self.state in ["present", "build"]: self.present() @@ -504,17 +500,10 @@ class PodmanImageManager(object): ignore_errors=ignore_errors, ) - def _get_id_from_output( - self, lines, startswith=None, contains=None, split_on=" ", maxsplit=1 - ): + def _get_id_from_output(self, lines, startswith=None, contains=None, split_on=" ", maxsplit=1): layer_ids = [] for line in lines.splitlines(): - if ( - startswith - and line.startswith(startswith) - or contains - and contains in line - ): + if startswith and line.startswith(startswith) or contains and contains in line: splitline = line.rsplit(split_on, maxsplit) layer_ids.append(splitline[1]) @@ -531,9 +520,7 @@ class PodmanImageManager(object): """ containerfile_path = None - for filename in [ - os.path.join(self.path, fname) for fname in ["Containerfile", "Dockerfile"] - ]: + for filename in [os.path.join(self.path, fname) for fname in ["Containerfile", "Dockerfile"]]: if os.path.exists(filename): containerfile_path = filename break @@ -553,9 +540,7 @@ class PodmanImageManager(object): """ build_file_arg = self.build.get("file") if self.build else None - containerfile_contents = ( - self.build.get("container_file") if self.build else None - ) + containerfile_contents = self.build.get("container_file") if self.build else None container_filename = None if build_file_arg: @@ -583,9 +568,7 @@ class PodmanImageManager(object): containerfile_contents.encode(), ).hexdigest() else: - return hashlib.sha256( - containerfile_contents.encode(), usedforsecurity=False - ).hexdigest() + return hashlib.sha256(containerfile_contents.encode(), usedforsecurity=False).hexdigest() def _get_args_containerfile_hash(self): """ @@ -597,9 +580,7 @@ class PodmanImageManager(object): args_containerfile_hash = None - context_has_containerfile = ( - self.path and self._find_containerfile_from_context() - ) + context_has_containerfile = self.path and self._find_containerfile_from_context() should_hash_args_containerfile = ( context_has_containerfile @@ -608,9 +589,7 @@ class PodmanImageManager(object): ) if should_hash_args_containerfile: - args_containerfile_hash = self._hash_containerfile_contents( - self._get_containerfile_contents() - ) + args_containerfile_hash = self._hash_containerfile_contents(self._get_containerfile_contents()) return args_containerfile_hash def present(self): @@ -637,34 +616,24 @@ class PodmanImageManager(object): if self.state == "build" or self.path: # Build the image build_file = self.build.get("file") if self.build else None - container_file_txt = ( - self.build.get("container_file") if self.build else None - ) + container_file_txt = self.build.get("container_file") if self.build else None if build_file and container_file_txt: - self.module.fail_json( - msg="Cannot specify both build file and container file content!" - ) + self.module.fail_json(msg="Cannot specify both build file and container file content!") if not self.path and build_file: self.path = os.path.dirname(build_file) elif not self.path and not build_file and not container_file_txt: - self.module.fail_json( - msg="Path to build context or file is required when building an image" - ) + self.module.fail_json(msg="Path to build context or file is required when building an image") self.results["actions"].append( "Built image {image_name} from {path}".format( image_name=self.image_name, path=self.path or "default context" ) ) if not self.module.check_mode: - self.results["image"], self.results["stdout"] = self.build_image( - args_containerfile_hash - ) + self.results["image"], self.results["stdout"] = self.build_image(args_containerfile_hash) image = self.results["image"] else: # Pull the image - self.results["actions"].append( - "Pulled image {image_name}".format(image_name=self.image_name) - ) + self.results["actions"].append("Pulled image {image_name}".format(image_name=self.image_name)) if not self.module.check_mode: image = self.results["image"] = self.pull_image() @@ -687,17 +656,13 @@ class PodmanImageManager(object): image_id = self.find_image_id() if image: - self.results["actions"].append( - "Removed image {name}".format(name=self.name) - ) + self.results["actions"].append("Removed image {name}".format(name=self.name)) self.results["changed"] = True self.results["image"]["state"] = "Deleted" if not self.module.check_mode: self.remove_image() elif image_id: - self.results["actions"].append( - "Removed image with id {id}".format(id=self.image_name) - ) + self.results["actions"].append("Removed image with id {id}".format(id=self.image_name)) self.results["changed"] = True self.results["image"]["state"] = "Deleted" if not self.module.check_mode: @@ -722,11 +687,7 @@ class PodmanImageManager(object): try: images = json.loads(images) except json.decoder.JSONDecodeError: - self.module.fail_json( - msg="Failed to parse JSON output from podman image ls: {out}".format( - out=images - ) - ) + self.module.fail_json(msg="Failed to parse JSON output from podman image ls: {out}".format(out=images)) if len(images) == 0: return None inspect_json = self.inspect_image(image_name) @@ -757,11 +718,7 @@ class PodmanImageManager(object): try: image_data = json.loads(image_data) except json.decoder.JSONDecodeError: - self.module.fail_json( - msg="Failed to parse JSON output from podman inspect: {out}".format( - out=image_data - ) - ) + self.module.fail_json(msg="Failed to parse JSON output from podman inspect: {out}".format(out=image_data)) if len(image_data) > 0: return image_data else: @@ -780,9 +737,7 @@ class PodmanImageManager(object): args.extend(["--authfile", self.auth_file]) if self.username and self.password: - cred_string = "{user}:{password}".format( - user=self.username, password=self.password - ) + cred_string = "{user}:{password}".format(user=self.username, password=self.password) args.extend(["--creds", cred_string]) if self.validate_certs is not None: @@ -806,11 +761,7 @@ class PodmanImageManager(object): ) ) else: - self.module.fail_json( - msg="Failed to pull image {image_name}".format( - image_name=image_name - ) - ) + self.module.fail_json(msg="Failed to pull image {image_name}".format(image_name=image_name)) return self.inspect_image(out.strip()) def build_image(self, containerfile_hash): @@ -854,9 +805,7 @@ class PodmanImageManager(object): if container_file_txt: # create a temporarly file with the content of the Containerfile if self.path: - container_file_path = os.path.join( - self.path, "Containerfile.generated_by_ansible_%s" % time.time() - ) + container_file_path = os.path.join(self.path, "Containerfile.generated_by_ansible_%s" % time.time()) else: container_file_path = os.path.join( tempfile.gettempdir(), @@ -879,9 +828,7 @@ class PodmanImageManager(object): args.extend(["--authfile", self.auth_file]) if self.username and self.password: - cred_string = "{user}:{password}".format( - user=self.username, password=self.password - ) + cred_string = "{user}:{password}".format(user=self.username, password=self.password) args.extend(["--creds", cred_string]) extra_args = self.build.get("extra_args") @@ -897,9 +844,7 @@ class PodmanImageManager(object): rc, out, err = self._run(args, ignore_errors=True) if rc != 0: self.module.fail_json( - msg="Failed to build image {image}: {out} {err}".format( - image=self.image_name, out=out, err=err - ) + msg="Failed to build image {image}: {out} {err}".format(image=self.image_name, out=out, err=err) ) # remove the temporary file if it was created if container_file_txt: @@ -920,9 +865,7 @@ class PodmanImageManager(object): args.extend(["--cert-dir", self.ca_cert_dir]) if self.username and self.password: - cred_string = "{user}:{password}".format( - user=self.username, password=self.password - ) + cred_string = "{user}:{password}".format(user=self.username, password=self.password) args.extend(["--creds", cred_string]) if self.auth_file: @@ -964,27 +907,15 @@ class PodmanImageManager(object): dest_format_string = "{transport}:{dest}" if transport == "docker-daemon" and ":" not in dest: dest_format_string = "{transport}:{dest}:latest" - dest_string = dest_format_string.format( - transport=transport, name=self.name, dest=dest - ) + dest_string = dest_format_string.format(transport=transport, name=self.name, dest=dest) else: dest_string = dest # In case of dest as a repository with org name only, append image name to it - if ( - ":" not in dest - and "@" not in dest - and len(dest.rstrip("/").split("/")) == 2 - ): + if ":" not in dest and "@" not in dest and len(dest.rstrip("/").split("/")) == 2: dest_string = dest.rstrip("/") + "/" + self.image_name - if ( - "/" not in dest_string - and "@" not in dest_string - and "docker-daemon" not in dest_string - ): - self.module.fail_json( - msg="Destination must be a full URL or path to a directory with image name and tag." - ) + if "/" not in dest_string and "@" not in dest_string and "docker-daemon" not in dest_string: + self.module.fail_json(msg="Destination must be a full URL or path to a directory with image name and tag.") args.append(dest_string) self.module.log( @@ -999,9 +930,7 @@ class PodmanImageManager(object): rc, out, err = self._run(args, ignore_errors=True) if rc != 0: self.module.fail_json( - msg="Failed to push image {image_name}".format( - image_name=self.image_name - ), + msg="Failed to push image {image_name}".format(image_name=self.image_name), stdout=out, stderr=err, actions=self.results["actions"], @@ -1020,9 +949,7 @@ class PodmanImageManager(object): rc, out, err = self._run(args, ignore_errors=True) if rc != 0: self.module.fail_json( - msg="Failed to remove image {image_name}. {err}".format( - image_name=image_name, err=err - ) + msg="Failed to remove image {image_name}. {err}".format(image_name=image_name, err=err) ) return out @@ -1036,9 +963,7 @@ class PodmanImageManager(object): rc, out, err = self._run(args, ignore_errors=True) if rc != 0: self.module.fail_json( - msg="Failed to remove image with id {image_id}. {err}".format( - image_id=image_id, err=err - ) + msg="Failed to remove image with id {image_id}. {err}".format(image_id=image_id, err=err) ) return out diff --git a/plugins/modules/podman_image_info.py b/plugins/modules/podman_image_info.py index f269a4c..167aad8 100644 --- a/plugins/modules/podman_image_info.py +++ b/plugins/modules/podman_image_info.py @@ -164,9 +164,7 @@ def get_image_info(module, executable, name): rc, out, err = module.run_command(command) if rc != 0: - module.fail_json( - msg="Unable to gather info for '{0}': {1}".format(", ".join(names), err) - ) + module.fail_json(msg="Unable to gather info for '{0}': {1}".format(", ".join(names), err)) return out else: diff --git a/plugins/modules/podman_import.py b/plugins/modules/podman_import.py index ccfd76d..9d54216 100644 --- a/plugins/modules/podman_import.py +++ b/plugins/modules/podman_import.py @@ -150,19 +150,13 @@ def volume_load(module, executable): rc, out, err = module.run_command(command) if rc != 0: module.fail_json(msg="Error importing volume %s: %s" % (src, err)) - rc, out2, err2 = module.run_command( - [executable, "volume", "inspect", module.params["volume"]] - ) + rc, out2, err2 = module.run_command([executable, "volume", "inspect", module.params["volume"]]) if rc != 0: - module.fail_json( - msg="Volume %s inspection failed: %s" % (module.params["volume"], err2) - ) + module.fail_json(msg="Volume %s inspection failed: %s" % (module.params["volume"], err2)) try: info = json.loads(out2)[0] except Exception as e: - module.fail_json( - msg="Could not parse JSON from volume %s: %s" % (module.params["volume"], e) - ) + module.fail_json(msg="Could not parse JSON from volume %s: %s" % (module.params["volume"], e)) return changed, out, err, info, command diff --git a/plugins/modules/podman_login.py b/plugins/modules/podman_login.py index d075323..ce9bc21 100644 --- a/plugins/modules/podman_login.py +++ b/plugins/modules/podman_login.py @@ -199,11 +199,7 @@ def main(): podman_version = get_podman_version(module, fail=False) - if ( - (podman_version is not None) - and (LooseVersion(podman_version) < LooseVersion("4.7.0")) - and secret - ): + if (podman_version is not None) and (LooseVersion(podman_version) < LooseVersion("4.7.0")) and secret: module.fail_json(msg="secret option may not be used with podman < 4.7.0") if username and ((not password) and (not secret)): diff --git a/plugins/modules/podman_logout.py b/plugins/modules/podman_logout.py index 81eb947..21ef4ff 100644 --- a/plugins/modules/podman_logout.py +++ b/plugins/modules/podman_logout.py @@ -88,9 +88,7 @@ EXAMPLES = r""" from ansible.module_utils.basic import AnsibleModule -def logout( - module, executable, registry, authfile, all_registries, ignore_docker_credentials -): +def logout(module, executable, registry, authfile, all_registries, ignore_docker_credentials): command = [executable, "logout"] changed = False if authfile: diff --git a/plugins/modules/podman_network.py b/plugins/modules/podman_network.py index 4a79901..e7c99c7 100644 --- a/plugins/modules/podman_network.py +++ b/plugins/modules/podman_network.py @@ -352,9 +352,7 @@ class PodmanNetworkModuleParams: def _create_action(self): cmd = [self.action, self.params["name"]] all_param_methods = [ - func - for func in dir(self) - if callable(getattr(self, func)) and func.startswith("addparam") + func for func in dir(self) if callable(getattr(self, func)) and func.startswith("addparam") ] params_set = (i for i in self.params if self.params[i] is not None) for param in params_set: @@ -367,14 +365,12 @@ class PodmanNetworkModuleParams: if minv and LooseVersion(minv) > LooseVersion(self.podman_version): self.module.fail_json( msg="Parameter %s is supported from podman " - "version %s only! Current version is %s" - % (param, minv, self.podman_version) + "version %s only! Current version is %s" % (param, minv, self.podman_version) ) if maxv and LooseVersion(maxv) < LooseVersion(self.podman_version): self.module.fail_json( msg="Parameter %s is supported till podman " - "version %s only! Current version is %s" - % (param, minv, self.podman_version) + "version %s only! Current version is %s" % (param, minv, self.podman_version) ) def addparam_gateway(self, c): @@ -464,9 +460,7 @@ class PodmanNetworkDiff: def defaultize(self): params_with_defaults = {} - self.default_dict = PodmanNetworkDefaults( - self.module, self.version - ).default_dict() + self.default_dict = PodmanNetworkDefaults(self.module, self.version).default_dict() for p in self.module.params: if self.module.params[p] is None and p in self.default_dict: params_with_defaults[p] = self.default_dict[p] @@ -564,30 +558,16 @@ class PodmanNetworkDiff: return self._diff_update_and_compare("net_config", "", "") before_subs = self.info.get("subnets", []) if before_subs: - before = ":".join( - sorted( - [ - ",".join([i["subnet"], i["gateway"]]).rstrip(",") - for i in before_subs - ] - ) - ) + before = ":".join(sorted([",".join([i["subnet"], i["gateway"]]).rstrip(",") for i in before_subs])) else: before = "" - after = ":".join( - sorted([",".join([i["subnet"], i["gateway"]]).rstrip(",") for i in after]) - ) + after = ":".join(sorted([",".join([i["subnet"], i["gateway"]]).rstrip(",") for i in after])) return self._diff_update_and_compare("net_config", before, after) def diffparam_route(self): routes = self.info.get("routes", []) if routes: - before = [ - ",".join( - [r["destination"], r["gateway"], str(r.get("metric", ""))] - ).rstrip(",") - for r in routes - ] + before = [",".join([r["destination"], r["gateway"], str(r.get("metric", ""))]).rstrip(",") for r in routes] else: before = [] after = self.params["route"] or [] @@ -617,9 +597,7 @@ class PodmanNetworkDiff: before = self.info.get("subnets") if before: if len(before) > 1 and after: - return self._diff_update_and_compare( - "subnet", ",".join([i["subnet"] for i in before]), after - ) + return self._diff_update_and_compare("subnet", ",".join([i["subnet"] for i in before]), after) before = [i["subnet"] for i in before][0] return self._diff_update_and_compare("subnet", before, after) @@ -654,11 +632,7 @@ class PodmanNetworkDiff: return self._diff_update_and_compare("opt", before, after) def is_different(self): - diff_func_list = [ - func - for func in dir(self) - if callable(getattr(self, func)) and func.startswith("diffparam") - ] + diff_func_list = [func for func in dir(self) if callable(getattr(self, func)) and func.startswith("diffparam")] fail_fast = not bool(self.module._diff) different = False for func_name in diff_func_list: @@ -713,37 +687,21 @@ class PodmanNetwork: is_different = diffcheck.is_different() diffs = diffcheck.diff if self.module._diff and is_different and diffs["before"] and diffs["after"]: - self.diff["before"] = ( - "\n".join( - ["%s - %s" % (k, v) for k, v in sorted(diffs["before"].items())] - ) - + "\n" - ) - self.diff["after"] = ( - "\n".join( - ["%s - %s" % (k, v) for k, v in sorted(diffs["after"].items())] - ) - + "\n" - ) + self.diff["before"] = "\n".join(["%s - %s" % (k, v) for k, v in sorted(diffs["before"].items())]) + "\n" + self.diff["after"] = "\n".join(["%s - %s" % (k, v) for k, v in sorted(diffs["after"].items())]) + "\n" return is_different def get_info(self): """Inspect network and gather info about it.""" # pylint: disable=unused-variable - rc, out, err = self.module.run_command( - [self.module.params["executable"], b"network", b"inspect", self.name] - ) + rc, out, err = self.module.run_command([self.module.params["executable"], b"network", b"inspect", self.name]) return json.loads(out)[0] if rc == 0 else {} def _get_podman_version(self): # pylint: disable=unused-variable - rc, out, err = self.module.run_command( - [self.module.params["executable"], b"--version"] - ) + rc, out, err = self.module.run_command([self.module.params["executable"], b"--version"]) if rc != 0 or not out or "version" not in out: - self.module.fail_json( - msg="%s run failed!" % self.module.params["executable"] - ) + self.module.fail_json(msg="%s run failed!" % self.module.params["executable"]) return out.split("version")[1].strip() def _perform_action(self, action): @@ -758,10 +716,7 @@ class PodmanNetwork: self.version, self.module, ).construct_command_from_params() - full_cmd = " ".join( - [self.module.params["executable"], "network"] - + [to_native(i) for i in b_command] - ) + full_cmd = " ".join([self.module.params["executable"], "network"] + [to_native(i) for i in b_command]) self.module.log("PODMAN-NETWORK-DEBUG: %s" % full_cmd) self.actions.append(full_cmd) if not self.module.check_mode: @@ -814,9 +769,7 @@ class PodmanNetworkManager: "network": {}, } self.name = self.module.params["name"] - self.executable = self.module.get_bin_path( - self.module.params["executable"], required=True - ) + self.executable = self.module.get_bin_path(self.module.params["executable"], required=True) self.state = self.module.params["state"] self.recreate = self.module.params["recreate"] self.network = PodmanNetwork(self.module, self.name) @@ -854,9 +807,7 @@ class PodmanNetworkManager: } process_action = states_map[self.state] process_action() - self.module.fail_json( - msg="Unexpected logic error happened, " "please contact maintainers ASAP!" - ) + self.module.fail_json(msg="Unexpected logic error happened, " "please contact maintainers ASAP!") def make_present(self): """Run actions if desired state is 'started'.""" @@ -891,9 +842,7 @@ class PodmanNetworkManager: def main(): module = AnsibleModule( argument_spec=dict( - state=dict( - type="str", default="present", choices=["present", "absent", "quadlet"] - ), + state=dict(type="str", default="present", choices=["present", "absent", "quadlet"]), name=dict(type="str", required=True), disable_dns=dict(type="bool", required=False), dns=dict(type="list", elements="str", required=False), @@ -903,9 +852,7 @@ def main(): interface_name=dict(type="str", required=False), internal=dict(type="bool", required=False), ip_range=dict(type="str", required=False), - ipam_driver=dict( - type="str", required=False, choices=["host-local", "dhcp", "none"] - ), + ipam_driver=dict(type="str", required=False, choices=["host-local", "dhcp", "none"]), ipv6=dict(type="bool", required=False), subnet=dict(type="str", required=False), macvlan=dict(type="str", required=False), diff --git a/plugins/modules/podman_network_info.py b/plugins/modules/podman_network_info.py index 7695869..adf8a24 100644 --- a/plugins/modules/podman_network_info.py +++ b/plugins/modules/podman_network_info.py @@ -105,9 +105,7 @@ def get_network_info(module, executable, name): def main(): module = AnsibleModule( - argument_spec=dict( - executable=dict(type="str", default="podman"), name=dict(type="str") - ), + argument_spec=dict(executable=dict(type="str", default="podman"), name=dict(type="str")), supports_check_mode=True, ) diff --git a/plugins/modules/podman_play.py b/plugins/modules/podman_play.py index 0dc8288..644fe2b 100644 --- a/plugins/modules/podman_play.py +++ b/plugins/modules/podman_play.py @@ -276,9 +276,7 @@ class PodmanKubeManagement: self.command.extend(["--configmap=%s" % configmaps]) if self.module.params["log_opt"]: for k, v in self.module.params["log_opt"].items(): - self.command.extend( - ["--log-opt", "{k}={v}".format(k=k.replace("_", "-"), v=v)] - ) + self.command.extend(["--log-opt", "{k}={v}".format(k=k.replace("_", "-"), v=v)]) start = self.module.params["state"] == "started" self.command.extend(["--start=%s" % str(start).lower()]) for arg, param in { @@ -302,9 +300,7 @@ class PodmanKubeManagement: def _command_run(self, cmd): if self.module.params["kube_file_content"]: - rc, out, err = self.module.run_command( - cmd, data=self.module.params["kube_file_content"] - ) + rc, out, err = self.module.run_command(cmd, data=self.module.params["kube_file_content"]) else: rc, out, err = self.module.run_command(cmd) self.actions.append(" ".join(cmd)) @@ -324,20 +320,15 @@ class PodmanKubeManagement: kube_file = self.module.params["kube_file"] kube_file_content = self.module.params["kube_file_content"] if kube_file: - rc, out, err = self._command_run( - [self.executable, "kube", "play", "--down", kube_file] - ) + rc, out, err = self._command_run([self.executable, "kube", "play", "--down", kube_file]) elif kube_file_content: - rc, out, err = self._command_run( - [self.executable, "kube", "play", "--down", "-"] - ) + rc, out, err = self._command_run([self.executable, "kube", "play", "--down", "-"]) if rc != 0 and "no such pod" in err: changed = False return changed, out, err if rc != 0: self.module.fail_json( - msg="Failed to delete Pod with %s: %s %s" - % (kube_file if kube_file else "YAML content", out, err) + msg="Failed to delete Pod with %s: %s %s" % (kube_file if kube_file else "YAML content", out, err) ) # hack to check if no resources are deleted @@ -386,9 +377,7 @@ class PodmanKubeManagement: out_all, err_all = "", "" # Delete all pods for pod_id in pods: - rc, out, err = self._command_run( - [self.executable, "pod", "rm", "-f", pod_id] - ) + rc, out, err = self._command_run([self.executable, "pod", "rm", "-f", pod_id]) if rc != 0: self.module.fail_json("Can NOT delete Pod %s" % pod_id) else: @@ -398,9 +387,7 @@ class PodmanKubeManagement: return changed, out_all, err_all def pod_recreate(self): - if self.version is not None and LooseVersion(self.version) >= LooseVersion( - "3.4.0" - ): + if self.version is not None and LooseVersion(self.version) >= LooseVersion("3.4.0"): self.tear_down_pods() else: pods = self.discover_pods() @@ -420,9 +407,7 @@ class PodmanKubeManagement: changed = True else: changed = False - err = "\n".join( - [i for i in err.splitlines() if "pod already exists" not in i] - ) + err = "\n".join([i for i in err.splitlines() if "pod already exists" not in i]) elif rc != 0: self.module.fail_json(msg="Output: %s\nError=%s" % (out, err)) else: @@ -472,9 +457,7 @@ def main(): quiet=dict(type="bool"), recreate=dict(type="bool"), userns=dict(type="str"), - log_level=dict( - type="str", choices=["debug", "info", "warn", "error", "fatal", "panic"] - ), + log_level=dict(type="str", choices=["debug", "info", "warn", "error", "fatal", "panic"]), quadlet_dir=dict(type="path", required=False), quadlet_filename=dict(type="str", required=False), quadlet_file_mode=dict(type="raw", required=False), @@ -494,13 +477,8 @@ def main(): changed = False out = err = "" if module.params["state"] == "absent": - if manage.version is not None and LooseVersion(manage.version) > LooseVersion( - "3.4.0" - ): - manage.module.log( - msg="version: %s, kube file %s" - % (manage.version, manage.module.params["kube_file"]) - ) + if manage.version is not None and LooseVersion(manage.version) > LooseVersion("3.4.0"): + manage.module.log(msg="version: %s, kube file %s" % (manage.version, manage.module.params["kube_file"])) changed, out, err = manage.tear_down_pods() else: pods = manage.discover_pods() diff --git a/plugins/modules/podman_pod_info.py b/plugins/modules/podman_pod_info.py index ab1495c..d3b9e2e 100644 --- a/plugins/modules/podman_pod_info.py +++ b/plugins/modules/podman_pod_info.py @@ -185,9 +185,7 @@ def get_pod_info(module, executable, name): def main(): module = AnsibleModule( - argument_spec=dict( - executable=dict(type="str", default="podman"), name=dict(type="str") - ), + argument_spec=dict(executable=dict(type="str", default="podman"), name=dict(type="str")), supports_check_mode=True, ) diff --git a/plugins/modules/podman_prune.py b/plugins/modules/podman_prune.py index ab936a3..99b9a36 100644 --- a/plugins/modules/podman_prune.py +++ b/plugins/modules/podman_prune.py @@ -182,21 +182,14 @@ def filtersPrepare(target, filters): ) ) else: - if target == "image" and ( - common_filter in ("dangling_only", "external") - ): - if ( - common_filter == "dangling_only" - and not filters["dangling_only"] - ): + if target == "image" and (common_filter in ("dangling_only", "external")): + if common_filter == "dangling_only" and not filters["dangling_only"]: filter_out.append("-a") if common_filter == "external" and filters["external"]: filter_out.append("--external") else: filter_out.append( - "--filter={label}={value}".format( - label=common_filter, value=filters[common_filter] - ) + "--filter={label}={value}".format(label=common_filter, value=filters[common_filter]) ) return filter_out @@ -210,11 +203,7 @@ def podmanExec(module, target, filters, executable): changed = bool(out) if rc != 0: - module.fail_json( - msg="Error executing prune on {target}: {err}".format( - target=target, err=err - ) - ) + module.fail_json(msg="Error executing prune on {target}: {err}".format(target=target, err=err)) return { "changed": changed, @@ -251,9 +240,7 @@ def main(): ("volume", "volume_filters"), ): if module.params[target]: - results[target] = podmanExec( - module, target, module.params[filters], executable - ) + results[target] = podmanExec(module, target, module.params[filters], executable) if module.params["system"]: target = "system" diff --git a/plugins/modules/podman_runlabel.py b/plugins/modules/podman_runlabel.py index 0e76ab0..15d8ca4 100644 --- a/plugins/modules/podman_runlabel.py +++ b/plugins/modules/podman_runlabel.py @@ -56,10 +56,7 @@ def runlabel(module, executable): if rc == 0: changed = True else: - module.fail_json( - msg="Error running the runlabel from image %s: %s" - % (module.params["image"], err) - ) + module.fail_json(msg="Error running the runlabel from image %s: %s" % (module.params["image"], err)) return changed, out, err diff --git a/plugins/modules/podman_save.py b/plugins/modules/podman_save.py index 32a1eaf..ffd6320 100644 --- a/plugins/modules/podman_save.py +++ b/plugins/modules/podman_save.py @@ -140,9 +140,7 @@ def main(): "oci-dir", "docker-dir", ]: - module.fail_json( - msg="Compression is only supported for oci-dir and docker-dir format" - ) + module.fail_json(msg="Compression is only supported for oci-dir and docker-dir format") executable = module.get_bin_path(module.params["executable"], required=True) changed, out, err = save(module, executable) diff --git a/plugins/modules/podman_search.py b/plugins/modules/podman_search.py index 0fdd22b..e06b5b4 100644 --- a/plugins/modules/podman_search.py +++ b/plugins/modules/podman_search.py @@ -119,11 +119,7 @@ def main(): try: results = json.loads(result_str) except json.decoder.JSONDecodeError: - module.fail_json( - msg="Failed to parse JSON output from podman search: {out}".format( - out=result_str - ) - ) + module.fail_json(msg="Failed to parse JSON output from podman search: {out}".format(out=result_str)) results = dict( changed=False, diff --git a/plugins/modules/podman_secret.py b/plugins/modules/podman_secret.py index 0a5d8a6..f9468d7 100644 --- a/plugins/modules/podman_secret.py +++ b/plugins/modules/podman_secret.py @@ -126,17 +126,13 @@ diff = {"before": "", "after": ""} def podman_secret_exists(module, executable, name, version): if version is None or LooseVersion(version) < LooseVersion("4.5.0"): - rc, out, err = module.run_command( - [executable, "secret", "ls", "--format", "{{.Name}}"] - ) + rc, out, err = module.run_command([executable, "secret", "ls", "--format", "{{.Name}}"]) return name in [i.strip() for i in out.splitlines()] rc, out, err = module.run_command([executable, "secret", "exists", name]) return rc == 0 -def need_update( - module, executable, name, data, path, env, skip, driver, driver_opts, debug, labels -): +def need_update(module, executable, name, data, path, env, skip, driver, driver_opts, debug, labels): cmd = [executable, "secret", "inspect", "--showsecret", name] rc, out, err = module.run_command(cmd) if rc != 0: @@ -186,9 +182,7 @@ def need_update( for k, v in driver_opts.items(): if secret["Spec"]["Driver"]["Options"].get(k) != v: diff["after"] = "=".join([k, v]) - diff["before"] = "=".join( - [k, secret["Spec"]["Driver"]["Options"].get(k)] - ) + diff["before"] = "=".join([k, secret["Spec"]["Driver"]["Options"].get(k)]) return True if labels: for k, v in labels.items(): @@ -216,9 +210,7 @@ def podman_secret_create( labels, ): podman_version = get_podman_version(module, fail=False) - if podman_version is not None and LooseVersion(podman_version) >= LooseVersion( - "4.7.0" - ): + if podman_version is not None and LooseVersion(podman_version) >= LooseVersion("4.7.0"): if need_update( module, executable, diff --git a/plugins/modules/podman_secret_info.py b/plugins/modules/podman_secret_info.py index 646b6a3..81575d9 100644 --- a/plugins/modules/podman_secret_info.py +++ b/plugins/modules/podman_secret_info.py @@ -87,9 +87,7 @@ def get_secret_info(module, executable, show, name): command.extend(name) rc, out, err = module.run_command(command) if rc != 0 or "no secret with name or id" in err: - module.fail_json( - msg="Unable to gather info for %s: %s" % (name or "all secrets", err) - ) + module.fail_json(msg="Unable to gather info for %s: %s" % (name or "all secrets", err)) if not out or json.loads(out) is None: return [], out, err return json.loads(out), out, err diff --git a/plugins/modules/podman_tag.py b/plugins/modules/podman_tag.py index 92fd042..1c6536e 100644 --- a/plugins/modules/podman_tag.py +++ b/plugins/modules/podman_tag.py @@ -61,9 +61,7 @@ def tag(module, executable): if rc == 0: changed = True else: - module.fail_json( - msg="Error tagging local image %s: %s" % (module.params["image"], err) - ) + module.fail_json(msg="Error tagging local image %s: %s" % (module.params["image"], err)) return changed, out, err diff --git a/plugins/modules/podman_volume.py b/plugins/modules/podman_volume.py index 85bd1ea..5c2f41f 100644 --- a/plugins/modules/podman_volume.py +++ b/plugins/modules/podman_volume.py @@ -206,9 +206,7 @@ class PodmanVolumeModuleParams: def _create_action(self): cmd = [self.action, self.params["name"]] all_param_methods = [ - func - for func in dir(self) - if callable(getattr(self, func)) and func.startswith("addparam") + func for func in dir(self) if callable(getattr(self, func)) and func.startswith("addparam") ] params_set = (i for i in self.params if self.params[i] is not None) for param in params_set: @@ -221,14 +219,12 @@ class PodmanVolumeModuleParams: if minv and LooseVersion(minv) > LooseVersion(self.podman_version): self.module.fail_json( msg="Parameter %s is supported from podman " - "version %s only! Current version is %s" - % (param, minv, self.podman_version) + "version %s only! Current version is %s" % (param, minv, self.podman_version) ) if maxv and LooseVersion(maxv) < LooseVersion(self.podman_version): self.module.fail_json( msg="Parameter %s is supported till podman " - "version %s only! Current version is %s" - % (param, minv, self.podman_version) + "version %s only! Current version is %s" % (param, minv, self.podman_version) ) def addparam_label(self, c): @@ -271,9 +267,7 @@ class PodmanVolumeDiff: def defaultize(self): params_with_defaults = {} - self.default_dict = PodmanVolumeDefaults( - self.module, self.version - ).default_dict() + self.default_dict = PodmanVolumeDefaults(self.module, self.version).default_dict() for p in self.module.params: if self.module.params[p] is None and p in self.default_dict: params_with_defaults[p] = self.default_dict[p] @@ -325,11 +319,7 @@ class PodmanVolumeDiff: return self._diff_update_and_compare("options", before, after) def is_different(self): - diff_func_list = [ - func - for func in dir(self) - if callable(getattr(self, func)) and func.startswith("diffparam") - ] + diff_func_list = [func for func in dir(self) if callable(getattr(self, func)) and func.startswith("diffparam")] fail_fast = not bool(self.module._diff) different = False for func_name in diff_func_list: @@ -386,26 +376,14 @@ class PodmanVolume: is_different = diffcheck.is_different() diffs = diffcheck.diff if self.module._diff and is_different and diffs["before"] and diffs["after"]: - self.diff["before"] = ( - "\n".join( - ["%s - %s" % (k, v) for k, v in sorted(diffs["before"].items())] - ) - + "\n" - ) - self.diff["after"] = ( - "\n".join( - ["%s - %s" % (k, v) for k, v in sorted(diffs["after"].items())] - ) - + "\n" - ) + self.diff["before"] = "\n".join(["%s - %s" % (k, v) for k, v in sorted(diffs["before"].items())]) + "\n" + self.diff["after"] = "\n".join(["%s - %s" % (k, v) for k, v in sorted(diffs["after"].items())]) + "\n" return is_different def get_info(self): """Inspect volume and gather info about it.""" # pylint: disable=unused-variable - rc, out, err = self.module.run_command( - [self.module.params["executable"], b"volume", b"inspect", self.name] - ) + rc, out, err = self.module.run_command([self.module.params["executable"], b"volume", b"inspect", self.name]) if rc == 0: data = json.loads(out) if data: @@ -416,13 +394,9 @@ class PodmanVolume: def _get_podman_version(self): # pylint: disable=unused-variable - rc, out, err = self.module.run_command( - [self.module.params["executable"], b"--version"] - ) + rc, out, err = self.module.run_command([self.module.params["executable"], b"--version"]) if rc != 0 or not out or "version" not in out: - self.module.fail_json( - msg="%s run failed!" % self.module.params["executable"] - ) + self.module.fail_json(msg="%s run failed!" % self.module.params["executable"]) return out.split("version")[1].strip() def _perform_action(self, action): @@ -437,10 +411,7 @@ class PodmanVolume: self.version, self.module, ).construct_command_from_params() - full_cmd = " ".join( - [self.module.params["executable"], "volume"] - + [to_native(i) for i in b_command] - ) + full_cmd = " ".join([self.module.params["executable"], "volume"] + [to_native(i) for i in b_command]) # check if running not from root if os.getuid() != 0 and action == "mount": full_cmd = f"{self.module.params['executable']} unshare {full_cmd}" @@ -504,9 +475,7 @@ class PodmanVolumeManager: "volume": {}, } self.name = self.module.params["name"] - self.executable = self.module.get_bin_path( - self.module.params["executable"], required=True - ) + self.executable = self.module.get_bin_path(self.module.params["executable"], required=True) self.state = self.module.params["state"] self.recreate = self.module.params["recreate"] self.volume = PodmanVolume(self.module, self.name) @@ -546,9 +515,7 @@ class PodmanVolumeManager: } process_action = states_map[self.state] process_action() - self.module.fail_json( - msg="Unexpected logic error happened, " "please contact maintainers ASAP!" - ) + self.module.fail_json(msg="Unexpected logic error happened, " "please contact maintainers ASAP!") def make_present(self): """Run actions if desired state is 'started'.""" diff --git a/plugins/modules/podman_volume_info.py b/plugins/modules/podman_volume_info.py index 6b72e06..f810a35 100644 --- a/plugins/modules/podman_volume_info.py +++ b/plugins/modules/podman_volume_info.py @@ -73,9 +73,7 @@ def get_volume_info(module, executable, name): command.append("--all") rc, out, err = module.run_command(command) if rc != 0 or "no such volume" in err: - module.fail_json( - msg="Unable to gather info for %s: %s" % (name or "all volumes", err) - ) + module.fail_json(msg="Unable to gather info for %s: %s" % (name or "all volumes", err)) if not out or json.loads(out) is None: return [], out, err return json.loads(out), out, err @@ -83,9 +81,7 @@ def get_volume_info(module, executable, name): def main(): module = AnsibleModule( - argument_spec=dict( - executable=dict(type="str", default="podman"), name=dict(type="str") - ), + argument_spec=dict(executable=dict(type="str", default="podman"), name=dict(type="str")), supports_check_mode=True, )