1
0
Fork 0
mirror of https://github.com/containers/ansible-podman-collections.git synced 2026-02-04 07:11:49 +00:00

Run black -l 120 on all files, again (#943)

Signed-off-by: Sagi Shnaidman <sshnaidm@redhat.com>
This commit is contained in:
Sergey 2025-06-26 13:24:44 +03:00 committed by GitHub
parent aa20ede71e
commit f2e813671a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
32 changed files with 221 additions and 762 deletions

View file

@ -137,9 +137,7 @@ class BecomeModule(BecomeBase):
# podman unshare should be executed in a login shell to avoid chdir permission errors # podman unshare should be executed in a login shell to avoid chdir permission errors
cmdlist.append("-iu %s" % user) cmdlist.append("-iu %s" % user)
if self.get_option("become_pass"): if self.get_option("become_pass"):
self.prompt = ( self.prompt = "[sudo podman unshare via ansible, key=%s] password:" % self._id
"[sudo podman unshare via ansible, key=%s] password:" % self._id
)
cmdlist.append('-p "%s"' % self.prompt) cmdlist.append('-p "%s"' % self.prompt)
cmdlist.append("-- %s" % becomecmd) cmdlist.append("-- %s" % becomecmd)
becomecmd = " ".join(cmdlist) becomecmd = " ".join(cmdlist)

View file

@ -78,9 +78,7 @@ class Connection(ConnectionBase):
display.vvvv("Using buildah connection from collection") display.vvvv("Using buildah connection from collection")
def _set_user(self): def _set_user(self):
self._buildah( self._buildah(b"config", [b"--user=" + to_bytes(self.user, errors="surrogate_or_strict")])
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): def _buildah(self, cmd, cmd_args=None, in_data=None, outfile_stdout=None):
""" """
@ -143,17 +141,10 @@ class Connection(ConnectionBase):
super(Connection, self)._connect() super(Connection, self)._connect()
rc, self._mount_point, stderr = self._buildah("mount") rc, self._mount_point, stderr = self._buildah("mount")
if rc != 0: if rc != 0:
display.v( display.v("Failed to mount container %s: %s" % (self._container_id, stderr.strip()))
"Failed to mount container %s: %s"
% (self._container_id, stderr.strip())
)
else: else:
self._mount_point = self._mount_point.strip() + to_bytes( self._mount_point = self._mount_point.strip() + to_bytes(os.path.sep, errors="surrogate_or_strict")
os.path.sep, errors="surrogate_or_strict" display.vvvv("MOUNTPOINT %s RC %s STDERR %r" % (self._mount_point, rc, stderr))
)
display.vvvv(
"MOUNTPOINT %s RC %s STDERR %r" % (self._mount_point, rc, stderr)
)
self._connected = True self._connected = True
@ensure_connect @ensure_connect
@ -181,9 +172,7 @@ class Connection(ConnectionBase):
% (in_path, out_path, self._container_id, stderr) % (in_path, out_path, self._container_id, stderr)
) )
else: else:
real_out_path = self._mount_point + to_bytes( real_out_path = self._mount_point + to_bytes(out_path, errors="surrogate_or_strict")
out_path, errors="surrogate_or_strict"
)
shutil.copyfile( shutil.copyfile(
to_bytes(in_path, errors="surrogate_or_strict"), to_bytes(in_path, errors="surrogate_or_strict"),
to_bytes(real_out_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) % (in_path, out_path, self._container_id, stderr)
) )
else: else:
real_in_path = self._mount_point + to_bytes( real_in_path = self._mount_point + to_bytes(in_path, errors="surrogate_or_strict")
in_path, errors="surrogate_or_strict"
)
shutil.copyfile( shutil.copyfile(
to_bytes(real_in_path, errors="surrogate_or_strict"), to_bytes(real_in_path, errors="surrogate_or_strict"),
to_bytes(out_path, errors="surrogate_or_strict"), to_bytes(out_path, errors="surrogate_or_strict"),

View file

@ -114,11 +114,7 @@ class Connection(ConnectionBase):
raise AnsibleError("%s command not found in PATH" % podman_exec) raise AnsibleError("%s command not found in PATH" % podman_exec)
local_cmd = [podman_cmd] local_cmd = [podman_cmd]
if self.get_option("podman_extra_args"): if self.get_option("podman_extra_args"):
local_cmd += shlex.split( local_cmd += shlex.split(to_native(self.get_option("podman_extra_args"), errors="surrogate_or_strict"))
to_native(
self.get_option("podman_extra_args"), errors="surrogate_or_strict"
)
)
if isinstance(cmd, str): if isinstance(cmd, str):
local_cmd.append(cmd) local_cmd.append(cmd)
else: else:
@ -155,21 +151,13 @@ class Connection(ConnectionBase):
super(Connection, self)._connect() super(Connection, self)._connect()
rc, self._mount_point, stderr = self._podman("mount") rc, self._mount_point, stderr = self._podman("mount")
if rc != 0: if rc != 0:
display.vvvv( display.vvvv("Failed to mount container %s: %s" % (self._container_id, stderr.strip()))
"Failed to mount container %s: %s"
% (self._container_id, stderr.strip())
)
elif not os.listdir(self._mount_point.strip()): elif not os.listdir(self._mount_point.strip()):
display.vvvv( display.vvvv("Failed to mount container with CGroups2: empty dir %s" % self._mount_point.strip())
"Failed to mount container with CGroups2: empty dir %s"
% self._mount_point.strip()
)
self._mount_point = None self._mount_point = None
else: else:
self._mount_point = self._mount_point.strip() self._mount_point = self._mount_point.strip()
display.vvvvv( display.vvvvv("MOUNTPOINT %s RC %s STDERR %r" % (self._mount_point, rc, stderr))
"MOUNTPOINT %s RC %s STDERR %r" % (self._mount_point, rc, stderr)
)
self._connected = True self._connected = True
@ensure_connect @ensure_connect
@ -210,18 +198,14 @@ class Connection(ConnectionBase):
% (in_path, out_path, self._container_id, stderr) % (in_path, out_path, self._container_id, stderr)
) )
if self.user: if self.user:
rc, stdout, stderr = self._podman( rc, stdout, stderr = self._podman("exec", ["chown", self.user, out_path])
"exec", ["chown", self.user, out_path]
)
if rc != 0: if rc != 0:
raise AnsibleError( raise AnsibleError(
"Failed to chown file %s for user %s in container %s\n%s" "Failed to chown file %s for user %s in container %s\n%s"
% (out_path, self.user, self._container_id, stderr) % (out_path, self.user, self._container_id, stderr)
) )
else: else:
real_out_path = self._mount_point + to_bytes( real_out_path = self._mount_point + to_bytes(out_path, errors="surrogate_or_strict")
out_path, errors="surrogate_or_strict"
)
shutil.copyfile( shutil.copyfile(
to_bytes(in_path, errors="surrogate_or_strict"), to_bytes(in_path, errors="surrogate_or_strict"),
to_bytes(real_out_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) % (in_path, out_path, self._container_id, stderr)
) )
else: else:
real_in_path = self._mount_point + to_bytes( real_in_path = self._mount_point + to_bytes(in_path, errors="surrogate_or_strict")
in_path, errors="surrogate_or_strict"
)
shutil.copyfile( shutil.copyfile(
to_bytes(real_in_path, errors="surrogate_or_strict"), to_bytes(real_in_path, errors="surrogate_or_strict"),
to_bytes(out_path, errors="surrogate_or_strict"), to_bytes(out_path, errors="surrogate_or_strict"),

View file

@ -46,20 +46,14 @@ ARGUMENTS_OPTS_DICT = {
} }
def run_podman_command( def run_podman_command(module, executable="podman", args=None, expected_rc=0, ignore_errors=False):
module, executable="podman", args=None, expected_rc=0, ignore_errors=False
):
if not isinstance(executable, list): if not isinstance(executable, list):
command = [executable] command = [executable]
if args is not None: if args is not None:
command.extend(args) command.extend(args)
rc, out, err = module.run_command(command) rc, out, err = module.run_command(command)
if not ignore_errors and rc != expected_rc: if not ignore_errors and rc != expected_rc:
module.fail_json( module.fail_json(msg="Failed to run {command} {args}: {err}".format(command=command, args=args, err=err))
msg="Failed to run {command} {args}: {err}".format(
command=command, args=args, err=err
)
)
return rc, out, 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): if (sysconf.get("stop_timeout") is not None) or (sysconf.get("time") is not None):
# Select correct parameter name based on version # Select correct parameter name based on version
arg_name = "stop-timeout" if gt4ver else "time" arg_name = "stop-timeout" if gt4ver else "time"
arg_value = ( arg_value = sysconf.get("stop_timeout") if sysconf.get("stop_timeout") is not None else sysconf.get("time")
sysconf.get("stop_timeout")
if sysconf.get("stop_timeout") is not None
else sysconf.get("time")
)
command.extend(["--%s=%s" % (arg_name, arg_value)]) command.extend(["--%s=%s" % (arg_name, arg_value)])
if sysconf.get("start_timeout") is not None: if sysconf.get("start_timeout") is not None:
command.extend(["--start-timeout=%s" % sysconf["start_timeout"]]) 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 # Function to remove comments from file content
def remove_comments(content): def remove_comments(content):
return "\n".join( return "\n".join([line for line in content.splitlines() if not line.startswith("#")])
[line for line in content.splitlines() if not line.startswith("#")]
)
# Remove comments from both file contents before comparison # Remove comments from both file contents before comparison
current_unit_file_content_nocmnt = remove_comments(current_unit_file_content) 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 # Get the different lines between the two contents
diff_in_file = [ diff_in_file = [
line line for line in unit_content_nocmnt.splitlines() if line not in current_unit_file_content_nocmnt.splitlines()
for line in unit_content_nocmnt.splitlines()
if line not in current_unit_file_content_nocmnt.splitlines()
] ]
diff_in_string = [ diff_in_string = [
line line for line in current_unit_file_content_nocmnt.splitlines() if line not in unit_content_nocmnt.splitlines()
for line in current_unit_file_content_nocmnt.splitlines()
if line not in unit_content_nocmnt.splitlines()
] ]
return diff_in_string, diff_in_file return diff_in_string, diff_in_file
@ -190,9 +174,7 @@ def generate_systemd(module, module_params, name, version):
"diff": {}, "diff": {},
} }
sysconf = module_params["generate_systemd"] sysconf = module_params["generate_systemd"]
rc, systemd, err = run_generate_systemd_command( rc, systemd, err = run_generate_systemd_command(module, module_params, name, version)
module, module_params, name, version
)
if rc != 0: if rc != 0:
module.log("PODMAN-CONTAINER-DEBUG: Error generating systemd: %s" % err) module.log("PODMAN-CONTAINER-DEBUG: Error generating systemd: %s" % err)
if sysconf: if sysconf:
@ -209,8 +191,7 @@ def generate_systemd(module, module_params, name, version):
result["changed"] = True result["changed"] = True
if not os.path.isdir(full_path): if not os.path.isdir(full_path):
module.fail_json( module.fail_json(
"Path %s is not a directory! " "Path %s is not a directory! " "Can not save systemd unit files there!" % full_path
"Can not save systemd unit files there!" % full_path
) )
for file_name, file_content in data.items(): for file_name, file_content in data.items():
file_name += ".service" file_name += ".service"
@ -218,42 +199,22 @@ def generate_systemd(module, module_params, name, version):
result["changed"] = True result["changed"] = True
if result["diff"].get("before") is None: if result["diff"].get("before") is None:
result["diff"] = {"before": {}, "after": {}} result["diff"] = {"before": {}, "after": {}}
result["diff"]["before"].update( result["diff"]["before"].update({"systemd_{file_name}.service".format(file_name=file_name): ""})
{
"systemd_{file_name}.service".format(
file_name=file_name
): ""
}
)
result["diff"]["after"].update( 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: else:
diff_ = compare_systemd_file_content( diff_ = compare_systemd_file_content(os.path.join(full_path, file_name), file_content)
os.path.join(full_path, file_name), file_content
)
if diff_: if diff_:
result["changed"] = True result["changed"] = True
if result["diff"].get("before") is None: if result["diff"].get("before") is None:
result["diff"] = {"before": {}, "after": {}} result["diff"] = {"before": {}, "after": {}}
result["diff"]["before"].update( 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( 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: with open(os.path.join(full_path, file_name), "w") as f:
f.write(file_content) 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 # We don't know where systemd files are located, nothing to delete
module.log("PODMAN-CONTAINER-DEBUG: Not deleting systemd file - no path!") module.log("PODMAN-CONTAINER-DEBUG: Not deleting systemd file - no path!")
return return
rc, systemd, err = run_generate_systemd_command( rc, systemd, err = run_generate_systemd_command(module, module_params, name, version)
module, module_params, name, version
)
if rc != 0: if rc != 0:
module.log("PODMAN-CONTAINER-DEBUG: Error generating systemd: %s" % err) module.log("PODMAN-CONTAINER-DEBUG: Error generating systemd: %s" % err)
return return
@ -390,15 +349,11 @@ def normalize_signal(signal_name_or_number):
def get_podman_version(module, fail=True): def get_podman_version(module, fail=True):
executable = ( executable = module.params["executable"] if module.params["executable"] else "podman"
module.params["executable"] if module.params["executable"] else "podman"
)
rc, out, err = module.run_command([executable, b"--version"]) rc, out, err = module.run_command([executable, b"--version"])
if rc != 0 or not out or "version" not in out: if rc != 0 or not out or "version" not in out:
if fail: if fail:
module.fail_json( module.fail_json(msg="'%s --version' run failed! Error: %s" % (executable, err))
msg="'%s --version' run failed! Error: %s" % (executable, err)
)
return None return None
return out.split("version")[1].strip() 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): elif isinstance(after, dict):
if module_arg == "log_opt" and "max_size" in after: if module_arg == "log_opt" and "max_size" in after:
after["max-size"] = after.pop("max_size") after["max-size"] = after.pop("max_size")
after = ",".join( after = ",".join(sorted([str(k).lower() + "=" + str(v).lower() for k, v in after.items() if v is not None]))
sorted(
[
str(k).lower() + "=" + str(v).lower()
for k, v in after.items()
if v is not None
]
)
)
if before: if before:
before = ",".join(sorted([j.lower() for j in before])) before = ",".join(sorted([j.lower() for j in before]))
else: else:

View file

@ -128,15 +128,11 @@ ARGUMENTS_SPEC_CONTAINER = dict(
label=dict(type="dict", aliases=["labels"]), label=dict(type="dict", aliases=["labels"]),
label_file=dict(type="str"), label_file=dict(type="str"),
log_driver=dict(type="str", choices=["k8s-file", "journald", "json-file"]), log_driver=dict(type="str", choices=["k8s-file", "journald", "json-file"]),
log_level=dict( log_level=dict(type="str", choices=["debug", "info", "warn", "error", "fatal", "panic"]),
type="str", choices=["debug", "info", "warn", "error", "fatal", "panic"]
),
log_opt=dict( log_opt=dict(
type="dict", type="dict",
aliases=["log_options"], aliases=["log_options"],
options=dict( options=dict(max_size=dict(type="str"), path=dict(type="str"), tag=dict(type="str")),
max_size=dict(type="str"), path=dict(type="str"), tag=dict(type="str")
),
), ),
mac_address=dict(type="str"), mac_address=dict(type="str"),
memory=dict(type="str"), memory=dict(type="str"),
@ -163,9 +159,7 @@ ARGUMENTS_SPEC_CONTAINER = dict(
preserve_fd=dict(type="list", elements="str"), preserve_fd=dict(type="list", elements="str"),
preserve_fds=dict(type="str"), preserve_fds=dict(type="str"),
privileged=dict(type="bool"), privileged=dict(type="bool"),
publish=dict( publish=dict(type="list", elements="str", aliases=["ports", "published", "published_ports"]),
type="list", elements="str", aliases=["ports", "published", "published_ports"]
),
publish_all=dict(type="bool"), publish_all=dict(type="bool"),
pull=dict(type="str", choices=["always", "missing", "never", "newer"]), pull=dict(type="str", choices=["always", "missing", "never", "newer"]),
quadlet_dir=dict(type="path"), quadlet_dir=dict(type="path"),
@ -244,17 +238,11 @@ def update_options(opts_dict, container):
container[key] = container.pop(k) container[key] = container.pop(k)
else: else:
key = k key = k
if ARGUMENTS_SPEC_CONTAINER[key]["type"] == "list" and not isinstance( if ARGUMENTS_SPEC_CONTAINER[key]["type"] == "list" and not isinstance(container[key], list):
container[key], list
):
opts_dict[key] = [container[key]] opts_dict[key] = [container[key]]
elif ARGUMENTS_SPEC_CONTAINER[key]["type"] == "bool" and not isinstance( elif ARGUMENTS_SPEC_CONTAINER[key]["type"] == "bool" and not isinstance(container[key], bool):
container[key], bool
):
opts_dict[key] = to_bool(container[key]) opts_dict[key] = to_bool(container[key])
elif ARGUMENTS_SPEC_CONTAINER[key]["type"] == "int" and not isinstance( elif ARGUMENTS_SPEC_CONTAINER[key]["type"] == "int" and not isinstance(container[key], int):
container[key], int
):
opts_dict[key] = int(container[key]) opts_dict[key] = int(container[key])
else: else:
opts_dict[key] = container[key] opts_dict[key] = container[key]
@ -295,9 +283,7 @@ class PodmanModuleParams:
if self.action in ["create", "run"]: if self.action in ["create", "run"]:
cmd = [self.action, "--name", self.params["name"]] cmd = [self.action, "--name", self.params["name"]]
all_param_methods = [ all_param_methods = [
func func for func in dir(self) if callable(getattr(self, func)) and func.startswith("addparam")
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) params_set = (i for i in self.params if self.params[i] is not None)
for param in params_set: for param in params_set:
@ -317,11 +303,7 @@ class PodmanModuleParams:
def complete_params(cmd): def complete_params(cmd):
if self.params["attach"] and self.action == "start": if self.params["attach"] and self.action == "start":
cmd.append("--attach") cmd.append("--attach")
if ( if self.params["detach"] is False and self.action == "start" and "--attach" not in cmd:
self.params["detach"] is False
and self.action == "start"
and "--attach" not in cmd
):
cmd.append("--attach") cmd.append("--attach")
if self.params["detach_keys"] and self.action == "start": if self.params["detach_keys"] and self.action == "start":
cmd += ["--detach-keys", self.params["detach_keys"]] cmd += ["--detach-keys", self.params["detach_keys"]]
@ -353,14 +335,12 @@ class PodmanModuleParams:
if minv and LooseVersion(minv) > LooseVersion(self.podman_version): if minv and LooseVersion(minv) > LooseVersion(self.podman_version):
self.module.fail_json( self.module.fail_json(
msg="Parameter %s is supported from podman " msg="Parameter %s is supported from podman "
"version %s only! Current version is %s" "version %s only! Current version is %s" % (param, minv, self.podman_version)
% (param, minv, self.podman_version)
) )
if maxv and LooseVersion(maxv) < LooseVersion(self.podman_version): if maxv and LooseVersion(maxv) < LooseVersion(self.podman_version):
self.module.fail_json( self.module.fail_json(
msg="Parameter %s is supported till podman " msg="Parameter %s is supported till podman "
"version %s only! Current version is %s" "version %s only! Current version is %s" % (param, minv, self.podman_version)
% (param, minv, self.podman_version)
) )
def addparam_annotation(self, c): def addparam_annotation(self, c):
@ -504,9 +484,7 @@ class PodmanModuleParams:
for env_value in self.params["env"].items(): for env_value in self.params["env"].items():
c += [ c += [
"--env", "--env",
b"=".join( b"=".join([to_bytes(k, errors="surrogate_or_strict") for k in env_value]),
[to_bytes(k, errors="surrogate_or_strict") for k in env_value]
),
] ]
return c return c
@ -529,9 +507,7 @@ class PodmanModuleParams:
for env_merge in self.params["env_merge"].items(): for env_merge in self.params["env_merge"].items():
c += [ c += [
"--env-merge", "--env-merge",
b"=".join( b"=".join([to_bytes(k, errors="surrogate_or_strict") for k in env_merge]),
[to_bytes(k, errors="surrogate_or_strict") for k in env_merge]
),
] ]
return c return c
@ -941,9 +917,7 @@ class PodmanDefaults:
def default_dict(self): def default_dict(self):
# make here any changes to self.defaults related to podman version # make here any changes to self.defaults related to podman version
# https://github.com/containers/libpod/pull/5669 # https://github.com/containers/libpod/pull/5669
if LooseVersion(self.version) >= LooseVersion("1.8.0") and LooseVersion( if LooseVersion(self.version) >= LooseVersion("1.8.0") and LooseVersion(self.version) < LooseVersion("1.9.0"):
self.version
) < LooseVersion("1.9.0"):
self.defaults["cpu_shares"] = 1024 self.defaults["cpu_shares"] = 1024
if LooseVersion(self.version) >= LooseVersion("3.0.0"): if LooseVersion(self.version) >= LooseVersion("3.0.0"):
self.defaults["log_level"] = "warning" self.defaults["log_level"] = "warning"
@ -994,9 +968,7 @@ class PodmanContainerDiff:
""" """
info_config = self.info["config"] info_config = self.info["config"]
before, after = diff_generic( before, after = diff_generic(self.params, info_config, module_arg, cmd_arg, boolean_type)
self.params, info_config, module_arg, cmd_arg, boolean_type
)
return self._diff_update_and_compare(module_arg, before, after) return self._diff_update_and_compare(module_arg, before, after)
def diffparam_annotation(self): def diffparam_annotation(self):
@ -1174,9 +1146,7 @@ class PodmanContainerDiff:
def diffparam_etc_hosts(self): def diffparam_etc_hosts(self):
if self.info["hostconfig"]["extrahosts"]: if self.info["hostconfig"]["extrahosts"]:
before = dict( before = dict([i.split(":", 1) for i in self.info["hostconfig"]["extrahosts"]])
[i.split(":", 1) for i in self.info["hostconfig"]["extrahosts"]]
)
else: else:
before = {} before = {}
after = self.params["etc_hosts"] or {} after = self.params["etc_hosts"] or {}
@ -1215,9 +1185,7 @@ class PodmanContainerDiff:
else: else:
before = "" before = ""
after = self.params["healthcheck_failure_action"] or before after = self.params["healthcheck_failure_action"] or before
return self._diff_update_and_compare( return self._diff_update_and_compare("healthcheckonfailureaction", before, after)
"healthcheckonfailureaction", before, after
)
def diffparam_healthcheck_interval(self): def diffparam_healthcheck_interval(self):
return self._diff_generic("healthcheck_interval", "--healthcheck-interval") return self._diff_generic("healthcheck_interval", "--healthcheck-interval")
@ -1226,17 +1194,13 @@ class PodmanContainerDiff:
return self._diff_generic("healthcheck_retries", "--healthcheck-retries") return self._diff_generic("healthcheck_retries", "--healthcheck-retries")
def diffparam_healthcheck_start_period(self): def diffparam_healthcheck_start_period(self):
return self._diff_generic( return self._diff_generic("healthcheck_start_period", "--healthcheck-start-period")
"healthcheck_start_period", "--healthcheck-start-period"
)
def diffparam_health_startup_cmd(self): def diffparam_health_startup_cmd(self):
return self._diff_generic("health_startup_cmd", "--health-startup-cmd") return self._diff_generic("health_startup_cmd", "--health-startup-cmd")
def diffparam_health_startup_interval(self): def diffparam_health_startup_interval(self):
return self._diff_generic( return self._diff_generic("health_startup_interval", "--health-startup-interval")
"health_startup_interval", "--health-startup-interval"
)
def diffparam_health_startup_retries(self): def diffparam_health_startup_retries(self):
return self._diff_generic("health_startup_retries", "--health-startup-retries") return self._diff_generic("health_startup_retries", "--health-startup-retries")
@ -1309,9 +1273,7 @@ class PodmanContainerDiff:
before = self.info["config"]["labels"] or {} before = self.info["config"]["labels"] or {}
after = self.image_info.get("labels") or {} after = self.image_info.get("labels") or {}
if self.params["label"]: if self.params["label"]:
after.update( after.update({str(k).lower(): str(v) for k, v in self.params["label"].items()})
{str(k).lower(): str(v) for k, v in self.params["label"].items()}
)
# Strip out labels that are coming from systemd files # Strip out labels that are coming from systemd files
# https://github.com/containers/ansible-podman-collections/issues/276 # https://github.com/containers/ansible-podman-collections/issues/276
if "podman_systemd_unit" in before: if "podman_systemd_unit" in before:
@ -1353,9 +1315,7 @@ class PodmanContainerDiff:
return self._diff_generic("network_aliases", "--network-alias") return self._diff_generic("network_aliases", "--network-alias")
def diffparam_no_healthcheck(self): def diffparam_no_healthcheck(self):
return self._diff_generic( return self._diff_generic("no_healthcheck", "--no-healthcheck", boolean_type=True)
"no_healthcheck", "--no-healthcheck", boolean_type=True
)
def diffparam_no_hosts(self): def diffparam_no_hosts(self):
return self._diff_generic("no_hosts", "--no-hosts") return self._diff_generic("no_hosts", "--no-hosts")
@ -1505,15 +1465,7 @@ class PodmanContainerDiff:
if before is None and after is None: if before is None and after is None:
return self._diff_update_and_compare("tmpfs", before, after) return self._diff_update_and_compare("tmpfs", before, after)
if after is not None: if after is not None:
after = ",".join( after = ",".join(sorted([str(k).lower() + ":" + str(v).lower() for k, v in after.items() if v is not None]))
sorted(
[
str(k).lower() + ":" + str(v).lower()
for k, v in after.items()
if v is not None
]
)
)
if before: if before:
before = ",".join(sorted([j.lower() for j in before])) before = ",".join(sorted([j.lower() for j in before]))
else: else:
@ -1559,14 +1511,9 @@ class PodmanContainerDiff:
before = None before = None
after = self.params["volume"] after = self.params["volume"]
if after is not None: if after is not None:
after = [ after = [":".join([clean_volume(i) for i in v.split(":")[:3]]) for v in self.params["volume"]]
":".join([clean_volume(i) for i in v.split(":")[:3]])
for v in self.params["volume"]
]
if before is not None: if before is not None:
before = [ before = [":".join([clean_volume(i) for i in v.split(":")[:3]]) for v in before]
":".join([clean_volume(i) for i in v.split(":")[:3]]) for v in before
]
if before is None and after is None: if before is None and after is None:
return self._diff_update_and_compare("volume", before, after) return self._diff_update_and_compare("volume", before, after)
if after is not None: if after is not None:
@ -1582,11 +1529,7 @@ class PodmanContainerDiff:
return self._diff_generic("workdir", "--workdir") return self._diff_generic("workdir", "--workdir")
def is_different(self): def is_different(self):
diff_func_list = [ diff_func_list = [func for func in dir(self) if callable(getattr(self, func)) and func.startswith("diffparam")]
func
for func in dir(self)
if callable(getattr(self, func)) and func.startswith("diffparam")
]
fail_fast = not bool(self.module._diff) fail_fast = not bool(self.module._diff)
different = False different = False
for func_name in diff_func_list: for func_name in diff_func_list:
@ -1695,18 +1638,8 @@ class PodmanContainer:
is_different = diffcheck.is_different() is_different = diffcheck.is_different()
diffs = diffcheck.diff diffs = diffcheck.diff
if self.module._diff and is_different and diffs["before"] and diffs["after"]: if self.module._diff and is_different and diffs["before"] and diffs["after"]:
self.diff["before"] = ( self.diff["before"] = "\n".join(["%s - %s" % (k, v) for k, v in sorted(diffs["before"].items())]) + "\n"
"\n".join( self.diff["after"] = "\n".join(["%s - %s" % (k, v) for k, v in sorted(diffs["after"].items())]) + "\n"
["%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 return is_different
@property @property
@ -1722,9 +1655,7 @@ class PodmanContainer:
def get_info(self): def get_info(self):
"""Inspect container and gather info about it.""" """Inspect container and gather info about it."""
# pylint: disable=unused-variable # pylint: disable=unused-variable
rc, out, err = self.module.run_command( rc, out, err = self.module.run_command([self.module_params["executable"], b"container", b"inspect", self.name])
[self.module_params["executable"], b"container", b"inspect", self.name]
)
return json.loads(out)[0] if rc == 0 else {} return json.loads(out)[0] if rc == 0 else {}
def get_image_info(self): def get_image_info(self):
@ -1741,20 +1672,14 @@ class PodmanContainer:
self.module_params["image"].replace("docker://", ""), self.module_params["image"].replace("docker://", ""),
] ]
) )
self.module.log( self.module.log("PODMAN-CONTAINER-DEBUG: %s: %s" % (out, self.module_params["image"]))
"PODMAN-CONTAINER-DEBUG: %s: %s" % (out, self.module_params["image"])
)
return json.loads(out)[0] if rc == 0 else {} return json.loads(out)[0] if rc == 0 else {}
def _get_podman_version(self): def _get_podman_version(self):
# pylint: disable=unused-variable # pylint: disable=unused-variable
rc, out, err = self.module.run_command( rc, out, err = self.module.run_command([self.module_params["executable"], b"--version"])
[self.module_params["executable"], b"--version"]
)
if rc != 0 or not out or "version" not in out: if rc != 0 or not out or "version" not in out:
self.module.fail_json( self.module.fail_json(msg="%s run failed!" % self.module_params["executable"])
msg="%s run failed!" % self.module_params["executable"]
)
return out.split("version")[1].strip() return out.split("version")[1].strip()
def _perform_action(self, action): def _perform_action(self, action):
@ -1770,9 +1695,7 @@ class PodmanContainer:
self.version, self.version,
self.module, self.module,
).construct_command_from_params() ).construct_command_from_params()
full_cmd = " ".join( full_cmd = " ".join([self.module_params["executable"]] + [to_native(i) for i in b_command])
[self.module_params["executable"]] + [to_native(i) for i in b_command]
)
self.actions.append(full_cmd) self.actions.append(full_cmd)
if self.module.check_mode: if self.module.check_mode:
self.module.log("PODMAN-CONTAINER-DEBUG (check_mode): %s" % full_cmd) self.module.log("PODMAN-CONTAINER-DEBUG (check_mode): %s" % full_cmd)
@ -1790,8 +1713,7 @@ class PodmanContainer:
self.stderr = err self.stderr = err
if rc != 0: if rc != 0:
self.module.fail_json( self.module.fail_json(
msg="Container %s exited with code %s when %sed" msg="Container %s exited with code %s when %sed" % (self.name, rc, action),
% (self.name, rc, action),
stdout=out, stdout=out,
stderr=err, stderr=err,
) )
@ -1858,18 +1780,12 @@ class PodmanManager:
} }
self.module_params = params self.module_params = params
self.name = self.module_params["name"] self.name = self.module_params["name"]
self.executable = self.module.get_bin_path( self.executable = self.module.get_bin_path(self.module_params["executable"], required=True)
self.module_params["executable"], required=True
)
self.image = self.module_params["image"] self.image = self.module_params["image"]
self.state = self.module_params["state"] self.state = self.module_params["state"]
disable_image_pull = ( disable_image_pull = self.state in ("quadlet", "absent") or self.module_params["pull"] == "never"
self.state in ("quadlet", "absent") or self.module_params["pull"] == "never"
)
image_actions = ( image_actions = (
ensure_image_exists(self.module, self.image, self.module_params) ensure_image_exists(self.module, self.image, self.module_params) if not disable_image_pull else []
if not disable_image_pull
else []
) )
self.results["actions"] += image_actions self.results["actions"] += image_actions
@ -1903,9 +1819,7 @@ class PodmanManager:
self.results.update({"diff": self.container.diff}) self.results.update({"diff": self.container.diff})
if self.module.params["debug"] or self.module_params["debug"]: if self.module.params["debug"] or self.module_params["debug"]:
self.results.update({"podman_version": self.container.version}) self.results.update({"podman_version": self.container.version})
sysd = generate_systemd( sysd = generate_systemd(self.module, self.module_params, self.name, self.container.version)
self.module, self.module_params, self.name, self.container.version
)
self.results["changed"] = changed or sysd["changed"] self.results["changed"] = changed or sysd["changed"]
self.results.update({"podman_systemd": sysd["systemd"]}) self.results.update({"podman_systemd": sysd["systemd"]})
if sysd["diff"]: if sysd["diff"]:
@ -1922,9 +1836,7 @@ class PodmanManager:
"""Run actions if desired state is 'started'.""" """Run actions if desired state is 'started'."""
if not self.image: if not self.image:
if not self.container.exists: if not self.container.exists:
self.module.fail_json( self.module.fail_json(msg="Cannot start container when image" " is not specified!")
msg="Cannot start container when image" " is not specified!"
)
if self.restart: if self.restart:
self.container.restart() self.container.restart()
self.results["actions"].append("restarted %s" % self.container.name) self.results["actions"].append("restarted %s" % self.container.name)
@ -1974,9 +1886,7 @@ class PodmanManager:
def make_created(self): def make_created(self):
"""Run actions if desired state is 'created'.""" """Run actions if desired state is 'created'."""
if not self.container.exists and not self.image: if not self.container.exists and not self.image:
self.module.fail_json( self.module.fail_json(msg="Cannot create container when image" " is not specified!")
msg="Cannot create container when image" " is not specified!"
)
if not self.container.exists: if not self.container.exists:
self.container.create() self.container.create()
self.results["actions"].append("created %s" % self.container.name) self.results["actions"].append("created %s" % self.container.name)
@ -2006,9 +1916,7 @@ class PodmanManager:
def make_stopped(self): def make_stopped(self):
"""Run actions if desired state is 'stopped'.""" """Run actions if desired state is 'stopped'."""
if not self.container.exists and not self.image: if not self.container.exists and not self.image:
self.module.fail_json( self.module.fail_json(msg="Cannot create container when image" " is not specified!")
msg="Cannot create container when image" " is not specified!"
)
if not self.container.exists: if not self.container.exists:
self.container.create() self.container.create()
self.results["actions"].append("created %s" % self.container.name) self.results["actions"].append("created %s" % self.container.name)
@ -2028,9 +1936,7 @@ class PodmanManager:
if not self.container.exists: if not self.container.exists:
self.results.update({"changed": False}) self.results.update({"changed": False})
elif self.container.exists: elif self.container.exists:
delete_systemd( delete_systemd(self.module, self.module_params, self.name, self.container.version)
self.module, self.module_params, self.name, self.container.version
)
self.container.delete() self.container.delete()
self.results["actions"].append("deleted %s" % self.container.name) self.results["actions"].append("deleted %s" % self.container.name)
self.results.update({"changed": True}) self.results.update({"changed": True})

View file

@ -78,9 +78,7 @@ ARGUMENTS_SPEC_POD = dict(
memory_swap=dict(type="str", required=False), memory_swap=dict(type="str", required=False),
name=dict(type="str", required=True), name=dict(type="str", required=True),
network=dict(type="list", elements="str", required=False), network=dict(type="list", elements="str", required=False),
network_alias=dict( network_alias=dict(type="list", elements="str", required=False, aliases=["network_aliases"]),
type="list", elements="str", required=False, aliases=["network_aliases"]
),
no_hosts=dict(type="bool", required=False), no_hosts=dict(type="bool", required=False),
pid=dict(type="str", required=False), pid=dict(type="str", required=False),
pod_id_file=dict(type="str", required=False), pod_id_file=dict(type="str", required=False),
@ -157,9 +155,7 @@ class PodmanPodModuleParams:
def _create_action(self): def _create_action(self):
cmd = [self.action] cmd = [self.action]
all_param_methods = [ all_param_methods = [
func func for func in dir(self) if callable(getattr(self, func)) and func.startswith("addparam")
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) params_set = (i for i in self.params if self.params[i] is not None)
for param in params_set: for param in params_set:
@ -172,14 +168,12 @@ class PodmanPodModuleParams:
if minv and LooseVersion(minv) > LooseVersion(self.podman_version): if minv and LooseVersion(minv) > LooseVersion(self.podman_version):
self.module.fail_json( self.module.fail_json(
msg="Parameter %s is supported from podman " msg="Parameter %s is supported from podman "
"version %s only! Current version is %s" "version %s only! Current version is %s" % (param, minv, self.podman_version)
% (param, minv, self.podman_version)
) )
if maxv and LooseVersion(maxv) < LooseVersion(self.podman_version): if maxv and LooseVersion(maxv) < LooseVersion(self.podman_version):
self.module.fail_json( self.module.fail_json(
msg="Parameter %s is supported till podman " msg="Parameter %s is supported till podman "
"version %s only! Current version is %s" "version %s only! Current version is %s" % (param, minv, self.podman_version)
% (param, minv, self.podman_version)
) )
def addparam_add_host(self, c): def addparam_add_host(self, c):
@ -459,9 +453,7 @@ class PodmanPodDiff:
""" """
info_config = self.info info_config = self.info
before, after = diff_generic( before, after = diff_generic(self.params, info_config, module_arg, cmd_arg, boolean_type)
self.params, info_config, module_arg, cmd_arg, boolean_type
)
return self._diff_update_and_compare(module_arg, before, after) return self._diff_update_and_compare(module_arg, before, after)
def diffparam_add_host(self): def diffparam_add_host(self):
@ -643,14 +635,9 @@ class PodmanPodDiff:
before = None before = None
after = self.params["volume"] after = self.params["volume"]
if after is not None: if after is not None:
after = [ after = [":".join([clean_volume(i) for i in v.split(":")[:2]]) for v in self.params["volume"]]
":".join([clean_volume(i) for i in v.split(":")[:2]])
for v in self.params["volume"]
]
if before is not None: if before is not None:
before = [ before = [":".join([clean_volume(i) for i in v.split(":")[:2]]) for v in 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)) self.module.log("PODMAN Before: %s and After: %s" % (before, after))
if before is None and after is None: if before is None and after is None:
return self._diff_update_and_compare("volume", before, after) return self._diff_update_and_compare("volume", before, after)
@ -664,11 +651,7 @@ class PodmanPodDiff:
return self._diff_generic("volumes_from", "--volumes-from") return self._diff_generic("volumes_from", "--volumes-from")
def is_different(self): def is_different(self):
diff_func_list = [ diff_func_list = [func for func in dir(self) if callable(getattr(self, func)) and func.startswith("diffparam")]
func
for func in dir(self)
if callable(getattr(self, func)) and func.startswith("diffparam")
]
fail_fast = not bool(self.module._diff) fail_fast = not bool(self.module._diff)
different = False different = False
for func_name in diff_func_list: for func_name in diff_func_list:
@ -720,24 +703,12 @@ class PodmanPod:
@property @property
def different(self): def different(self):
"""Check if pod is different.""" """Check if pod is different."""
diffcheck = PodmanPodDiff( diffcheck = PodmanPodDiff(self.module, self.module_params, self.info, self.infra_info, self.version)
self.module, self.module_params, self.info, self.infra_info, self.version
)
is_different = diffcheck.is_different() is_different = diffcheck.is_different()
diffs = diffcheck.diff diffs = diffcheck.diff
if self.module._diff and is_different and diffs["before"] and diffs["after"]: if self.module._diff and is_different and diffs["before"] and diffs["after"]:
self.diff["before"] = ( self.diff["before"] = "\n".join(["%s - %s" % (k, v) for k, v in sorted(diffs["before"].items())]) + "\n"
"\n".join( self.diff["after"] = "\n".join(["%s - %s" % (k, v) for k, v in sorted(diffs["after"].items())]) + "\n"
["%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 return is_different
@property @property
@ -771,9 +742,7 @@ class PodmanPod:
def get_info(self): def get_info(self):
"""Inspect pod and gather info about it.""" """Inspect pod and gather info about it."""
# pylint: disable=unused-variable # pylint: disable=unused-variable
rc, out, err = self.module.run_command( rc, out, err = self.module.run_command([self.module_params["executable"], b"pod", b"inspect", self.name])
[self.module_params["executable"], b"pod", b"inspect", self.name]
)
if rc == 0: if rc == 0:
info = json.loads(out) info = json.loads(out)
# from podman 5 onwards, this is a list of dicts, # from podman 5 onwards, this is a list of dicts,
@ -812,20 +781,14 @@ class PodmanPod:
else: else:
return {} return {}
# pylint: disable=unused-variable # pylint: disable=unused-variable
rc, out, err = self.module.run_command( rc, out, err = self.module.run_command([self.module_params["executable"], b"inspect", infra_container_id])
[self.module_params["executable"], b"inspect", infra_container_id]
)
return json.loads(out)[0] if rc == 0 else {} return json.loads(out)[0] if rc == 0 else {}
def _get_podman_version(self): def _get_podman_version(self):
# pylint: disable=unused-variable # pylint: disable=unused-variable
rc, out, err = self.module.run_command( rc, out, err = self.module.run_command([self.module_params["executable"], b"--version"])
[self.module_params["executable"], b"--version"]
)
if rc != 0 or not out or "version" not in out: if rc != 0 or not out or "version" not in out:
self.module.fail_json( self.module.fail_json(msg="%s run failed!" % self.module_params["executable"])
msg="%s run failed!" % self.module_params["executable"]
)
return out.split("version")[1].strip() return out.split("version")[1].strip()
def _perform_action(self, action): def _perform_action(self, action):
@ -841,10 +804,7 @@ class PodmanPod:
self.version, self.version,
self.module, self.module,
).construct_command_from_params() ).construct_command_from_params()
full_cmd = " ".join( full_cmd = " ".join([self.module_params["executable"], "pod"] + [to_native(i) for i in b_command])
[self.module_params["executable"], "pod"]
+ [to_native(i) for i in b_command]
)
self.module.log("PODMAN-POD-DEBUG: %s" % full_cmd) self.module.log("PODMAN-POD-DEBUG: %s" % full_cmd)
self.actions.append(full_cmd) self.actions.append(full_cmd)
if not self.module.check_mode: if not self.module.check_mode:
@ -855,9 +815,7 @@ class PodmanPod:
self.stdout = out self.stdout = out
self.stderr = err self.stderr = err
if rc != 0: if rc != 0:
self.module.fail_json( self.module.fail_json(msg="Can't %s pod %s" % (action, self.name), stdout=out, stderr=err)
msg="Can't %s pod %s" % (action, self.name), stdout=out, stderr=err
)
def delete(self): def delete(self):
"""Delete the pod.""" """Delete the pod."""
@ -918,9 +876,7 @@ class PodmanPodManager:
"pod": {}, "pod": {},
} }
self.name = self.module_params["name"] self.name = self.module_params["name"]
self.executable = self.module.get_bin_path( self.executable = self.module.get_bin_path(self.module_params["executable"], required=True)
self.module_params["executable"], required=True
)
self.state = self.module_params["state"] self.state = self.module_params["state"]
self.recreate = self.module_params["recreate"] self.recreate = self.module_params["recreate"]
self.pod = PodmanPod(self.module, self.name, self.module_params) self.pod = PodmanPod(self.module, self.name, self.module_params)
@ -945,9 +901,7 @@ class PodmanPodManager:
self.results.update({"diff": self.pod.diff}) self.results.update({"diff": self.pod.diff})
if self.module.params["debug"] or self.module_params["debug"]: if self.module.params["debug"] or self.module_params["debug"]:
self.results.update({"podman_version": self.pod.version}) self.results.update({"podman_version": self.pod.version})
sysd = generate_systemd( sysd = generate_systemd(self.module, self.module_params, self.name, self.pod.version)
self.module, self.module_params, self.name, self.pod.version
)
self.results["changed"] = changed or sysd["changed"] self.results["changed"] = changed or sysd["changed"]
self.results.update({"podman_systemd": sysd["systemd"]}) self.results.update({"podman_systemd": sysd["systemd"]})
if sysd["diff"]: if sysd["diff"]:

View file

@ -55,14 +55,9 @@ class Quadlet:
Construct the quadlet content as a string. Construct the quadlet content as a string.
""" """
custom_user_options = self.custom_params.get("quadlet_options") custom_user_options = self.custom_params.get("quadlet_options")
custom_text = ( custom_text = "\n" + "\n".join(custom_user_options) if custom_user_options else ""
"\n" + "\n".join(custom_user_options) if custom_user_options else ""
)
return ( return (
f"[{self.section}]\n" f"[{self.section}]\n" + "\n".join(f"{key}={value}" for key, value in self.dict_params) + custom_text + "\n"
+ "\n".join(f"{key}={value}" for key, value in self.dict_params)
+ custom_text
+ "\n"
) )
def write_to_file(self, path: str): 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 # Work on params in params_map and convert them to a right form
if params["annotation"]: if params["annotation"]:
params["annotation"] = [ params["annotation"] = ["%s=%s" % (k, v) for k, v in params["annotation"].items()]
"%s=%s" % (k, v) for k, v in params["annotation"].items()
]
if params["cap_add"]: if params["cap_add"]:
params["cap_add"] = " ".join(params["cap_add"]) params["cap_add"] = " ".join(params["cap_add"])
if params["cap_drop"]: if params["cap_drop"]:
@ -181,22 +174,16 @@ class ContainerQuadlet(Quadlet):
else params["command"] else params["command"]
) )
if params["label"]: if params["label"]:
params["label"] = [ params["label"] = [shlex.quote("%s=%s" % (k, v)) for k, v in params["label"].items()]
shlex.quote("%s=%s" % (k, v)) for k, v in params["label"].items()
]
if params["env"]: if params["env"]:
params["env"] = [ params["env"] = [shlex.quote("%s=%s" % (k, v)) for k, v in params["env"].items()]
shlex.quote("%s=%s" % (k, v)) for k, v in params["env"].items()
]
if params["rootfs"]: if params["rootfs"]:
params["rootfs"] = params["image"] params["rootfs"] = params["image"]
params["image"] = None params["image"] = None
if params["sysctl"]: if params["sysctl"]:
params["sysctl"] = ["%s=%s" % (k, v) for k, v in params["sysctl"].items()] params["sysctl"] = ["%s=%s" % (k, v) for k, v in params["sysctl"].items()]
if params["tmpfs"]: if params["tmpfs"]:
params["tmpfs"] = [ params["tmpfs"] = ["%s:%s" % (k, v) if v else k for k, v in params["tmpfs"].items()]
"%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 # Work on params which are not in the param_map but can be calculated
params["global_args"] = [] params["global_args"] = []
@ -227,10 +214,7 @@ class ContainerQuadlet(Quadlet):
if params["blkio_weight_device"]: if params["blkio_weight_device"]:
params["podman_args"].append( params["podman_args"].append(
" ".join( " ".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"]: if params["cgroupns"]:
@ -265,9 +249,7 @@ class ContainerQuadlet(Quadlet):
if params["decryption_key"]: if params["decryption_key"]:
params["podman_args"].append(f"--decryption-key {params['decryption_key']}") params["podman_args"].append(f"--decryption-key {params['decryption_key']}")
if params["device_cgroup_rule"]: if params["device_cgroup_rule"]:
params["podman_args"].append( params["podman_args"].append(f"--device-cgroup-rule {params['device_cgroup_rule']}")
f"--device-cgroup-rule {params['device_cgroup_rule']}"
)
if params["device_read_bps"]: if params["device_read_bps"]:
for i in params["device_read_bps"]: for i in params["device_read_bps"]:
params["podman_args"].append(f"--device-read-bps {i}") params["podman_args"].append(f"--device-read-bps {i}")
@ -281,9 +263,7 @@ class ContainerQuadlet(Quadlet):
for i in params["device_write_iops"]: for i in params["device_write_iops"]:
params["podman_args"].append(f"--device-write-iops {i}") params["podman_args"].append(f"--device-write-iops {i}")
if params["etc_hosts"]: if params["etc_hosts"]:
params["etc_hosts"] = [ params["etc_hosts"] = ["%s:%s" % (k, v) for k, v in params["etc_hosts"].items()]
"%s:%s" % (k, v) for k, v in params["etc_hosts"].items()
]
if params["env_merge"]: if params["env_merge"]:
for k, v in params["env_merge"].items(): for k, v in params["env_merge"].items():
params["podman_args"].append(f"--env {k}={v}") 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']}") params["podman_args"].append(f"--label-file {params['label_file']}")
if params["log_opt"]: if params["log_opt"]:
params["log_opt"] = [ params["log_opt"] = [
"%s=%s" % (k.replace("max_size", "max-size"), v) "%s=%s" % (k.replace("max_size", "max-size"), v) for k, v in params["log_opt"].items() if v is not None
for k, v in params["log_opt"].items()
if v is not None
] ]
if params["mac_address"]: if params["mac_address"]:
params["podman_args"].append(f"--mac-address {params['mac_address']}") params["podman_args"].append(f"--mac-address {params['mac_address']}")
if params["memory"]: if params["memory"]:
params["podman_args"].append(f"--memory {params['memory']}") params["podman_args"].append(f"--memory {params['memory']}")
if params["memory_reservation"]: if params["memory_reservation"]:
params["podman_args"].append( params["podman_args"].append(f"--memory-reservation {params['memory_reservation']}")
f"--memory-reservation {params['memory_reservation']}"
)
if params["memory_swap"]: if params["memory_swap"]:
params["podman_args"].append(f"--memory-swap {params['memory_swap']}") params["podman_args"].append(f"--memory-swap {params['memory_swap']}")
if params["memory_swappiness"]: if params["memory_swappiness"]:
params["podman_args"].append( params["podman_args"].append(f"--memory-swappiness {params['memory_swappiness']}")
f"--memory-swappiness {params['memory_swappiness']}"
)
if params["no_healthcheck"]: if params["no_healthcheck"]:
params["podman_args"].append("--no-healthcheck") params["podman_args"].append("--no-healthcheck")
if params["no_hosts"] is not None: if params["no_hosts"] is not None:
params["podman_args"].append(f"--no-hosts={params['no_hosts']}") params["podman_args"].append(f"--no-hosts={params['no_hosts']}")
if params["oom_kill_disable"]: if params["oom_kill_disable"]:
params["podman_args"].append( params["podman_args"].append(f"--oom-kill-disable={params['oom_kill_disable']}")
f"--oom-kill-disable={params['oom_kill_disable']}"
)
if params["oom_score_adj"]: if params["oom_score_adj"]:
params["podman_args"].append(f"--oom-score-adj {params['oom_score_adj']}") params["podman_args"].append(f"--oom-score-adj {params['oom_score_adj']}")
if params["os"]: if params["os"]:
@ -385,9 +357,7 @@ class ContainerQuadlet(Quadlet):
for security_opt in params["security_opt"]: for security_opt in params["security_opt"]:
params["podman_args"].append(f"--security-opt {security_opt}") params["podman_args"].append(f"--security-opt {security_opt}")
if params["shm_size_systemd"]: if params["shm_size_systemd"]:
params["podman_args"].append( params["podman_args"].append(f"--shm-size-systemd {params['shm_size_systemd']}")
f"--shm-size-systemd {params['shm_size_systemd']}"
)
if params["sig_proxy"]: if params["sig_proxy"]:
params["podman_args"].append(f"--sig-proxy {params['sig_proxy']}") params["podman_args"].append(f"--sig-proxy {params['sig_proxy']}")
if params["systemd"]: if params["systemd"]:
@ -395,9 +365,7 @@ class ContainerQuadlet(Quadlet):
if params["timeout"]: if params["timeout"]:
params["podman_args"].append(f"--timeout {params['timeout']}") params["podman_args"].append(f"--timeout {params['timeout']}")
if params["tls_verify"]: if params["tls_verify"]:
params["podman_args"].append( params["podman_args"].append(f"--tls-verify={str(params['tls_verify']).lower()}")
f"--tls-verify={str(params['tls_verify']).lower()}"
)
if params["tty"]: if params["tty"]:
params["podman_args"].append("--tty") params["podman_args"].append("--tty")
if params["umask"]: if params["umask"]:
@ -493,10 +461,7 @@ class PodQuadlet(Quadlet):
if params["blkio_weight_device"]: if params["blkio_weight_device"]:
params["podman_args"].append( params["podman_args"].append(
" ".join( " ".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"]: if params["cpuset_cpus"]:
@ -539,9 +504,7 @@ class PodQuadlet(Quadlet):
if params["infra_command"]: if params["infra_command"]:
params["podman_args"].append(f"--infra-command {params['infra_command']}") params["podman_args"].append(f"--infra-command {params['infra_command']}")
if params["infra_conmon_pidfile"]: if params["infra_conmon_pidfile"]:
params["podman_args"].append( params["podman_args"].append(f"--infra-conmon-pidfile {params['infra_conmon_pidfile']}")
f"--infra-conmon-pidfile {params['infra_conmon_pidfile']}"
)
if params["infra_image"]: if params["infra_image"]:
params["podman_args"].append(f"--infra-image {params['infra_image']}") params["podman_args"].append(f"--infra-image {params['infra_image']}")
if params["infra_name"]: if params["infra_name"]:
@ -575,15 +538,11 @@ class PodQuadlet(Quadlet):
if params["share"]: if params["share"]:
params["podman_args"].append(f"--share {params['share']}") params["podman_args"].append(f"--share {params['share']}")
if params["share_parent"] is not None: if params["share_parent"] is not None:
params["podman_args"].append( params["podman_args"].append(f"--share-parent={str(params['share_parent']).lower()}")
f"--share-parent={str(params['share_parent']).lower()}"
)
if params["shm_size"]: if params["shm_size"]:
params["podman_args"].append(f"--shm-size {params['shm_size']}") params["podman_args"].append(f"--shm-size {params['shm_size']}")
if params["shm_size_systemd"]: if params["shm_size_systemd"]:
params["podman_args"].append( params["podman_args"].append(f"--shm-size-systemd {params['shm_size_systemd']}")
f"--shm-size-systemd {params['shm_size_systemd']}"
)
if params["subgidname"]: if params["subgidname"]:
params["podman_args"].append(f"--subgidname {params['subgidname']}") params["podman_args"].append(f"--subgidname {params['subgidname']}")
if params["subuidname"]: if params["subuidname"]:
@ -722,9 +681,7 @@ def check_quadlet_directory(module, quadlet_dir):
except Exception as e: except Exception as e:
module.fail_json(msg="Directory for quadlet_file can't be created: %s" % e) module.fail_json(msg="Directory for quadlet_file can't be created: %s" % e)
if not os.access(quadlet_dir, os.W_OK): if not os.access(quadlet_dir, os.W_OK):
module.fail_json( module.fail_json(msg="Directory for quadlet_file is not writable: %s" % quadlet_dir)
msg="Directory for quadlet_file is not writable: %s" % quadlet_dir
)
def create_quadlet_state(module, issuer): 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) quadlet_dir = os.path.expanduser(QUADLET_NON_ROOT_PATH)
# Create a filename based on the issuer # Create a filename based on the issuer
if not module.params.get("name") and not module.params.get("quadlet_filename"): if not module.params.get("name") and not module.params.get("quadlet_filename"):
module.fail_json( module.fail_json(msg=f"Filename for {issuer} is required for creating a quadlet file.")
msg=f"Filename for {issuer} is required for creating a quadlet file."
)
if issuer == "image": if issuer == "image":
name = module.params["name"].split("/")[-1].split(":")[0] name = module.params["name"].split("/")[-1].split(":")[0]
else: else:
@ -779,24 +734,14 @@ def create_quadlet_state(module, issuer):
results_update = { results_update = {
"changed": True, "changed": True,
"diff": { "diff": {
"before": ( "before": ("\n".join(file_diff[0]) if isinstance(file_diff[0], list) else file_diff[0] + "\n"),
"\n".join(file_diff[0]) "after": ("\n".join(file_diff[1]) if isinstance(file_diff[1], list) else file_diff[1] + "\n"),
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: else:
# adjust file permissions # adjust file permissions
diff = {} diff = {}
if mode is not None and module.set_mode_if_different( if mode is not None and module.set_mode_if_different(quadlet_file_path, mode, False, diff):
quadlet_file_path, mode, False, diff
):
results_update = {"changed": True, "diff": diff} results_update = {"changed": True, "diff": diff}
else: else:
results_update = {} results_update = {}

View file

@ -1540,9 +1540,7 @@ def main():
and not module.params["force_restart"] and not module.params["force_restart"]
and not module.params["image"] and not module.params["image"]
): ):
module.fail_json( module.fail_json(msg="State '%s' required image to be configured!" % module.params["state"])
msg="State '%s' required image to be configured!" % module.params["state"]
)
results = PodmanManager(module, module.params).execute() results = PodmanManager(module, module.params).execute()
module.exit_json(**results) module.exit_json(**results)

View file

@ -74,9 +74,7 @@ EXAMPLES = r"""
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
def copy_file( def copy_file(module, executable, src, dest, container, from_container, archive, overwrite):
module, executable, src, dest, container, from_container, archive, overwrite
):
if from_container: if from_container:
command = [executable, "cp", "{0}:{1}".format(container, src), dest] command = [executable, "cp", "{0}:{1}".format(container, src), dest]
else: else:
@ -91,9 +89,7 @@ def copy_file(
rc, out, err = module.run_command(command) rc, out, err = module.run_command(command)
if rc != 0: if rc != 0:
module.fail_json( module.fail_json(msg="Unable to copy file to/from container - {out}".format(out=err))
msg="Unable to copy file to/from container - {out}".format(out=err)
)
else: else:
changed = True changed = True
return changed, out, err return changed, out, err
@ -123,9 +119,7 @@ def main():
executable = module.get_bin_path(executable, required=True) executable = module.get_bin_path(executable, required=True)
changed, out, err = copy_file( changed, out, err = copy_file(module, executable, src, dest, container, from_container, archive, overwrite)
module, executable, src, dest, container, from_container, archive, overwrite
)
results = dict(changed=changed) results = dict(changed=changed)

View file

@ -160,9 +160,7 @@ def run_container_exec(module: AnsibleModule) -> dict:
if env is not None: if env is not None:
for key, value in env.items(): for key, value in env.items():
if not isinstance(value, string_types): if not isinstance(value, string_types):
module.fail_json( module.fail_json(msg="Specify string value %s on the env field" % (value))
msg="Specify string value %s on the env field" % (value)
)
to_text(value, errors="surrogate_or_strict") to_text(value, errors="surrogate_or_strict")
exec_options += ["--env", "%s=%s" % (key, value)] exec_options += ["--env", "%s=%s" % (key, value)]

View file

@ -349,10 +349,7 @@ def get_containers_facts(module, executable, name):
retry += 1 retry += 1
rc, out, err = module.run_command(all_names) rc, out, err = module.run_command(all_names)
if rc != 0: if rc != 0:
module.fail_json( module.fail_json(msg="Unable to get list of containers during" " %s retries" % retry_limit)
msg="Unable to get list of containers during"
" %s retries" % retry_limit
)
name = out.split() name = out.split()
if not name: if not name:
return [], out, err return [], out, err

View file

@ -117,10 +117,7 @@ def main():
options_dict["debug"] = module.params["debug"] or options_dict["debug"] options_dict["debug"] = module.params["debug"] or options_dict["debug"]
test_input = check_input_strict(options_dict) test_input = check_input_strict(options_dict)
if test_input: if test_input:
module.fail_json( module.fail_json(msg="Failed to run container %s because: %s" % (options_dict["name"], test_input))
msg="Failed to run container %s because: %s"
% (options_dict["name"], test_input)
)
res = PodmanManager(module, options_dict).execute() res = PodmanManager(module, options_dict).execute()
results.append(res) results.append(res)
total_results = combine(results) total_results = combine(results)

View file

@ -89,10 +89,7 @@ def export(module, executable):
return changed, "", "" return changed, "", ""
rc, out, err = module.run_command(command) rc, out, err = module.run_command(command)
if rc != 0: if rc != 0:
module.fail_json( module.fail_json(msg="Error exporting %s %s: %s" % (export_type, module.params["container"], err))
msg="Error exporting %s %s: %s"
% (export_type, module.params["container"], err)
)
return changed, out, err return changed, out, err

View file

@ -463,9 +463,7 @@ def generate_systemd(module):
need_to_write_file = True need_to_write_file = True
else: else:
# See if we need to write the unit file, default yes # See if we need to write the unit file, default yes
need_to_write_file = bool( need_to_write_file = bool(compare_systemd_file_content(unit_file_full_path, unit_content))
compare_systemd_file_content(unit_file_full_path, unit_content)
)
# Write the file, if needed # Write the file, if needed
if need_to_write_file: if need_to_write_file:

View file

@ -454,9 +454,7 @@ class PodmanImageManager(object):
self.module = module self.module = module
self.results = results self.results = results
self.name = self.module.params.get("name") self.name = self.module.params.get("name")
self.executable = self.module.get_bin_path( self.executable = self.module.get_bin_path(module.params.get("executable"), required=True)
module.params.get("executable"), required=True
)
self.tag = self.module.params.get("tag") self.tag = self.module.params.get("tag")
self.pull = self.module.params.get("pull") self.pull = self.module.params.get("pull")
self.pull_extra_args = self.module.params.get("pull_extra_args") self.pull_extra_args = self.module.params.get("pull_extra_args")
@ -479,9 +477,7 @@ class PodmanImageManager(object):
self.tag = repo_tag self.tag = repo_tag
delimiter = ":" if "sha256" not in self.tag else "@" delimiter = ":" if "sha256" not in self.tag else "@"
self.image_name = "{name}{d}{tag}".format( self.image_name = "{name}{d}{tag}".format(name=self.name, d=delimiter, tag=self.tag)
name=self.name, d=delimiter, tag=self.tag
)
if self.state in ["present", "build"]: if self.state in ["present", "build"]:
self.present() self.present()
@ -504,17 +500,10 @@ class PodmanImageManager(object):
ignore_errors=ignore_errors, ignore_errors=ignore_errors,
) )
def _get_id_from_output( def _get_id_from_output(self, lines, startswith=None, contains=None, split_on=" ", maxsplit=1):
self, lines, startswith=None, contains=None, split_on=" ", maxsplit=1
):
layer_ids = [] layer_ids = []
for line in lines.splitlines(): for line in lines.splitlines():
if ( if startswith and line.startswith(startswith) or contains and contains in line:
startswith
and line.startswith(startswith)
or contains
and contains in line
):
splitline = line.rsplit(split_on, maxsplit) splitline = line.rsplit(split_on, maxsplit)
layer_ids.append(splitline[1]) layer_ids.append(splitline[1])
@ -531,9 +520,7 @@ class PodmanImageManager(object):
""" """
containerfile_path = None containerfile_path = None
for filename in [ for filename in [os.path.join(self.path, fname) for fname in ["Containerfile", "Dockerfile"]]:
os.path.join(self.path, fname) for fname in ["Containerfile", "Dockerfile"]
]:
if os.path.exists(filename): if os.path.exists(filename):
containerfile_path = filename containerfile_path = filename
break break
@ -553,9 +540,7 @@ class PodmanImageManager(object):
""" """
build_file_arg = self.build.get("file") if self.build else None build_file_arg = self.build.get("file") if self.build else None
containerfile_contents = ( containerfile_contents = self.build.get("container_file") if self.build else None
self.build.get("container_file") if self.build else None
)
container_filename = None container_filename = None
if build_file_arg: if build_file_arg:
@ -583,9 +568,7 @@ class PodmanImageManager(object):
containerfile_contents.encode(), containerfile_contents.encode(),
).hexdigest() ).hexdigest()
else: else:
return hashlib.sha256( return hashlib.sha256(containerfile_contents.encode(), usedforsecurity=False).hexdigest()
containerfile_contents.encode(), usedforsecurity=False
).hexdigest()
def _get_args_containerfile_hash(self): def _get_args_containerfile_hash(self):
""" """
@ -597,9 +580,7 @@ class PodmanImageManager(object):
args_containerfile_hash = None args_containerfile_hash = None
context_has_containerfile = ( context_has_containerfile = self.path and self._find_containerfile_from_context()
self.path and self._find_containerfile_from_context()
)
should_hash_args_containerfile = ( should_hash_args_containerfile = (
context_has_containerfile context_has_containerfile
@ -608,9 +589,7 @@ class PodmanImageManager(object):
) )
if should_hash_args_containerfile: if should_hash_args_containerfile:
args_containerfile_hash = self._hash_containerfile_contents( args_containerfile_hash = self._hash_containerfile_contents(self._get_containerfile_contents())
self._get_containerfile_contents()
)
return args_containerfile_hash return args_containerfile_hash
def present(self): def present(self):
@ -637,34 +616,24 @@ class PodmanImageManager(object):
if self.state == "build" or self.path: if self.state == "build" or self.path:
# Build the image # Build the image
build_file = self.build.get("file") if self.build else None build_file = self.build.get("file") if self.build else None
container_file_txt = ( container_file_txt = self.build.get("container_file") if self.build else None
self.build.get("container_file") if self.build else None
)
if build_file and container_file_txt: if build_file and container_file_txt:
self.module.fail_json( self.module.fail_json(msg="Cannot specify both build file and container file content!")
msg="Cannot specify both build file and container file content!"
)
if not self.path and build_file: if not self.path and build_file:
self.path = os.path.dirname(build_file) self.path = os.path.dirname(build_file)
elif not self.path and not build_file and not container_file_txt: elif not self.path and not build_file and not container_file_txt:
self.module.fail_json( self.module.fail_json(msg="Path to build context or file is required when building an image")
msg="Path to build context or file is required when building an image"
)
self.results["actions"].append( self.results["actions"].append(
"Built image {image_name} from {path}".format( "Built image {image_name} from {path}".format(
image_name=self.image_name, path=self.path or "default context" image_name=self.image_name, path=self.path or "default context"
) )
) )
if not self.module.check_mode: if not self.module.check_mode:
self.results["image"], self.results["stdout"] = self.build_image( self.results["image"], self.results["stdout"] = self.build_image(args_containerfile_hash)
args_containerfile_hash
)
image = self.results["image"] image = self.results["image"]
else: else:
# Pull the image # Pull the image
self.results["actions"].append( self.results["actions"].append("Pulled image {image_name}".format(image_name=self.image_name))
"Pulled image {image_name}".format(image_name=self.image_name)
)
if not self.module.check_mode: if not self.module.check_mode:
image = self.results["image"] = self.pull_image() image = self.results["image"] = self.pull_image()
@ -687,17 +656,13 @@ class PodmanImageManager(object):
image_id = self.find_image_id() image_id = self.find_image_id()
if image: if image:
self.results["actions"].append( self.results["actions"].append("Removed image {name}".format(name=self.name))
"Removed image {name}".format(name=self.name)
)
self.results["changed"] = True self.results["changed"] = True
self.results["image"]["state"] = "Deleted" self.results["image"]["state"] = "Deleted"
if not self.module.check_mode: if not self.module.check_mode:
self.remove_image() self.remove_image()
elif image_id: elif image_id:
self.results["actions"].append( self.results["actions"].append("Removed image with id {id}".format(id=self.image_name))
"Removed image with id {id}".format(id=self.image_name)
)
self.results["changed"] = True self.results["changed"] = True
self.results["image"]["state"] = "Deleted" self.results["image"]["state"] = "Deleted"
if not self.module.check_mode: if not self.module.check_mode:
@ -722,11 +687,7 @@ class PodmanImageManager(object):
try: try:
images = json.loads(images) images = json.loads(images)
except json.decoder.JSONDecodeError: except json.decoder.JSONDecodeError:
self.module.fail_json( self.module.fail_json(msg="Failed to parse JSON output from podman image ls: {out}".format(out=images))
msg="Failed to parse JSON output from podman image ls: {out}".format(
out=images
)
)
if len(images) == 0: if len(images) == 0:
return None return None
inspect_json = self.inspect_image(image_name) inspect_json = self.inspect_image(image_name)
@ -757,11 +718,7 @@ class PodmanImageManager(object):
try: try:
image_data = json.loads(image_data) image_data = json.loads(image_data)
except json.decoder.JSONDecodeError: except json.decoder.JSONDecodeError:
self.module.fail_json( self.module.fail_json(msg="Failed to parse JSON output from podman inspect: {out}".format(out=image_data))
msg="Failed to parse JSON output from podman inspect: {out}".format(
out=image_data
)
)
if len(image_data) > 0: if len(image_data) > 0:
return image_data return image_data
else: else:
@ -780,9 +737,7 @@ class PodmanImageManager(object):
args.extend(["--authfile", self.auth_file]) args.extend(["--authfile", self.auth_file])
if self.username and self.password: if self.username and self.password:
cred_string = "{user}:{password}".format( cred_string = "{user}:{password}".format(user=self.username, password=self.password)
user=self.username, password=self.password
)
args.extend(["--creds", cred_string]) args.extend(["--creds", cred_string])
if self.validate_certs is not None: if self.validate_certs is not None:
@ -806,11 +761,7 @@ class PodmanImageManager(object):
) )
) )
else: else:
self.module.fail_json( self.module.fail_json(msg="Failed to pull image {image_name}".format(image_name=image_name))
msg="Failed to pull image {image_name}".format(
image_name=image_name
)
)
return self.inspect_image(out.strip()) return self.inspect_image(out.strip())
def build_image(self, containerfile_hash): def build_image(self, containerfile_hash):
@ -854,9 +805,7 @@ class PodmanImageManager(object):
if container_file_txt: if container_file_txt:
# create a temporarly file with the content of the Containerfile # create a temporarly file with the content of the Containerfile
if self.path: if self.path:
container_file_path = os.path.join( container_file_path = os.path.join(self.path, "Containerfile.generated_by_ansible_%s" % time.time())
self.path, "Containerfile.generated_by_ansible_%s" % time.time()
)
else: else:
container_file_path = os.path.join( container_file_path = os.path.join(
tempfile.gettempdir(), tempfile.gettempdir(),
@ -879,9 +828,7 @@ class PodmanImageManager(object):
args.extend(["--authfile", self.auth_file]) args.extend(["--authfile", self.auth_file])
if self.username and self.password: if self.username and self.password:
cred_string = "{user}:{password}".format( cred_string = "{user}:{password}".format(user=self.username, password=self.password)
user=self.username, password=self.password
)
args.extend(["--creds", cred_string]) args.extend(["--creds", cred_string])
extra_args = self.build.get("extra_args") extra_args = self.build.get("extra_args")
@ -897,9 +844,7 @@ class PodmanImageManager(object):
rc, out, err = self._run(args, ignore_errors=True) rc, out, err = self._run(args, ignore_errors=True)
if rc != 0: if rc != 0:
self.module.fail_json( self.module.fail_json(
msg="Failed to build image {image}: {out} {err}".format( msg="Failed to build image {image}: {out} {err}".format(image=self.image_name, out=out, err=err)
image=self.image_name, out=out, err=err
)
) )
# remove the temporary file if it was created # remove the temporary file if it was created
if container_file_txt: if container_file_txt:
@ -920,9 +865,7 @@ class PodmanImageManager(object):
args.extend(["--cert-dir", self.ca_cert_dir]) args.extend(["--cert-dir", self.ca_cert_dir])
if self.username and self.password: if self.username and self.password:
cred_string = "{user}:{password}".format( cred_string = "{user}:{password}".format(user=self.username, password=self.password)
user=self.username, password=self.password
)
args.extend(["--creds", cred_string]) args.extend(["--creds", cred_string])
if self.auth_file: if self.auth_file:
@ -964,27 +907,15 @@ class PodmanImageManager(object):
dest_format_string = "{transport}:{dest}" dest_format_string = "{transport}:{dest}"
if transport == "docker-daemon" and ":" not in dest: if transport == "docker-daemon" and ":" not in dest:
dest_format_string = "{transport}:{dest}:latest" dest_format_string = "{transport}:{dest}:latest"
dest_string = dest_format_string.format( dest_string = dest_format_string.format(transport=transport, name=self.name, dest=dest)
transport=transport, name=self.name, dest=dest
)
else: else:
dest_string = dest dest_string = dest
# In case of dest as a repository with org name only, append image name to it # In case of dest as a repository with org name only, append image name to it
if ( if ":" not in dest and "@" not in dest and len(dest.rstrip("/").split("/")) == 2:
":" not in dest
and "@" not in dest
and len(dest.rstrip("/").split("/")) == 2
):
dest_string = dest.rstrip("/") + "/" + self.image_name dest_string = dest.rstrip("/") + "/" + self.image_name
if ( if "/" not in dest_string and "@" not in dest_string and "docker-daemon" not in dest_string:
"/" 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.")
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) args.append(dest_string)
self.module.log( self.module.log(
@ -999,9 +930,7 @@ class PodmanImageManager(object):
rc, out, err = self._run(args, ignore_errors=True) rc, out, err = self._run(args, ignore_errors=True)
if rc != 0: if rc != 0:
self.module.fail_json( self.module.fail_json(
msg="Failed to push image {image_name}".format( msg="Failed to push image {image_name}".format(image_name=self.image_name),
image_name=self.image_name
),
stdout=out, stdout=out,
stderr=err, stderr=err,
actions=self.results["actions"], actions=self.results["actions"],
@ -1020,9 +949,7 @@ class PodmanImageManager(object):
rc, out, err = self._run(args, ignore_errors=True) rc, out, err = self._run(args, ignore_errors=True)
if rc != 0: if rc != 0:
self.module.fail_json( self.module.fail_json(
msg="Failed to remove image {image_name}. {err}".format( msg="Failed to remove image {image_name}. {err}".format(image_name=image_name, err=err)
image_name=image_name, err=err
)
) )
return out return out
@ -1036,9 +963,7 @@ class PodmanImageManager(object):
rc, out, err = self._run(args, ignore_errors=True) rc, out, err = self._run(args, ignore_errors=True)
if rc != 0: if rc != 0:
self.module.fail_json( self.module.fail_json(
msg="Failed to remove image with id {image_id}. {err}".format( msg="Failed to remove image with id {image_id}. {err}".format(image_id=image_id, err=err)
image_id=image_id, err=err
)
) )
return out return out

View file

@ -164,9 +164,7 @@ def get_image_info(module, executable, name):
rc, out, err = module.run_command(command) rc, out, err = module.run_command(command)
if rc != 0: if rc != 0:
module.fail_json( module.fail_json(msg="Unable to gather info for '{0}': {1}".format(", ".join(names), err))
msg="Unable to gather info for '{0}': {1}".format(", ".join(names), err)
)
return out return out
else: else:

View file

@ -150,19 +150,13 @@ def volume_load(module, executable):
rc, out, err = module.run_command(command) rc, out, err = module.run_command(command)
if rc != 0: if rc != 0:
module.fail_json(msg="Error importing volume %s: %s" % (src, err)) module.fail_json(msg="Error importing volume %s: %s" % (src, err))
rc, out2, err2 = module.run_command( rc, out2, err2 = module.run_command([executable, "volume", "inspect", module.params["volume"]])
[executable, "volume", "inspect", module.params["volume"]]
)
if rc != 0: if rc != 0:
module.fail_json( module.fail_json(msg="Volume %s inspection failed: %s" % (module.params["volume"], err2))
msg="Volume %s inspection failed: %s" % (module.params["volume"], err2)
)
try: try:
info = json.loads(out2)[0] info = json.loads(out2)[0]
except Exception as e: except Exception as e:
module.fail_json( module.fail_json(msg="Could not parse JSON from volume %s: %s" % (module.params["volume"], e))
msg="Could not parse JSON from volume %s: %s" % (module.params["volume"], e)
)
return changed, out, err, info, command return changed, out, err, info, command

View file

@ -199,11 +199,7 @@ def main():
podman_version = get_podman_version(module, fail=False) podman_version = get_podman_version(module, fail=False)
if ( if (podman_version is not None) and (LooseVersion(podman_version) < LooseVersion("4.7.0")) and secret:
(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") module.fail_json(msg="secret option may not be used with podman < 4.7.0")
if username and ((not password) and (not secret)): if username and ((not password) and (not secret)):

View file

@ -88,9 +88,7 @@ EXAMPLES = r"""
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
def logout( def logout(module, executable, registry, authfile, all_registries, ignore_docker_credentials):
module, executable, registry, authfile, all_registries, ignore_docker_credentials
):
command = [executable, "logout"] command = [executable, "logout"]
changed = False changed = False
if authfile: if authfile:

View file

@ -352,9 +352,7 @@ class PodmanNetworkModuleParams:
def _create_action(self): def _create_action(self):
cmd = [self.action, self.params["name"]] cmd = [self.action, self.params["name"]]
all_param_methods = [ all_param_methods = [
func func for func in dir(self) if callable(getattr(self, func)) and func.startswith("addparam")
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) params_set = (i for i in self.params if self.params[i] is not None)
for param in params_set: for param in params_set:
@ -367,14 +365,12 @@ class PodmanNetworkModuleParams:
if minv and LooseVersion(minv) > LooseVersion(self.podman_version): if minv and LooseVersion(minv) > LooseVersion(self.podman_version):
self.module.fail_json( self.module.fail_json(
msg="Parameter %s is supported from podman " msg="Parameter %s is supported from podman "
"version %s only! Current version is %s" "version %s only! Current version is %s" % (param, minv, self.podman_version)
% (param, minv, self.podman_version)
) )
if maxv and LooseVersion(maxv) < LooseVersion(self.podman_version): if maxv and LooseVersion(maxv) < LooseVersion(self.podman_version):
self.module.fail_json( self.module.fail_json(
msg="Parameter %s is supported till podman " msg="Parameter %s is supported till podman "
"version %s only! Current version is %s" "version %s only! Current version is %s" % (param, minv, self.podman_version)
% (param, minv, self.podman_version)
) )
def addparam_gateway(self, c): def addparam_gateway(self, c):
@ -464,9 +460,7 @@ class PodmanNetworkDiff:
def defaultize(self): def defaultize(self):
params_with_defaults = {} params_with_defaults = {}
self.default_dict = PodmanNetworkDefaults( self.default_dict = PodmanNetworkDefaults(self.module, self.version).default_dict()
self.module, self.version
).default_dict()
for p in self.module.params: for p in self.module.params:
if self.module.params[p] is None and p in self.default_dict: if self.module.params[p] is None and p in self.default_dict:
params_with_defaults[p] = self.default_dict[p] params_with_defaults[p] = self.default_dict[p]
@ -564,30 +558,16 @@ class PodmanNetworkDiff:
return self._diff_update_and_compare("net_config", "", "") return self._diff_update_and_compare("net_config", "", "")
before_subs = self.info.get("subnets", []) before_subs = self.info.get("subnets", [])
if before_subs: if before_subs:
before = ":".join( before = ":".join(sorted([",".join([i["subnet"], i["gateway"]]).rstrip(",") for i in before_subs]))
sorted(
[
",".join([i["subnet"], i["gateway"]]).rstrip(",")
for i in before_subs
]
)
)
else: else:
before = "" before = ""
after = ":".join( after = ":".join(sorted([",".join([i["subnet"], i["gateway"]]).rstrip(",") for i in after]))
sorted([",".join([i["subnet"], i["gateway"]]).rstrip(",") for i in after])
)
return self._diff_update_and_compare("net_config", before, after) return self._diff_update_and_compare("net_config", before, after)
def diffparam_route(self): def diffparam_route(self):
routes = self.info.get("routes", []) routes = self.info.get("routes", [])
if routes: if routes:
before = [ before = [",".join([r["destination"], r["gateway"], str(r.get("metric", ""))]).rstrip(",") for r in routes]
",".join(
[r["destination"], r["gateway"], str(r.get("metric", ""))]
).rstrip(",")
for r in routes
]
else: else:
before = [] before = []
after = self.params["route"] or [] after = self.params["route"] or []
@ -617,9 +597,7 @@ class PodmanNetworkDiff:
before = self.info.get("subnets") before = self.info.get("subnets")
if before: if before:
if len(before) > 1 and after: if len(before) > 1 and after:
return self._diff_update_and_compare( return self._diff_update_and_compare("subnet", ",".join([i["subnet"] for i in before]), after)
"subnet", ",".join([i["subnet"] for i in before]), after
)
before = [i["subnet"] for i in before][0] before = [i["subnet"] for i in before][0]
return self._diff_update_and_compare("subnet", before, after) return self._diff_update_and_compare("subnet", before, after)
@ -654,11 +632,7 @@ class PodmanNetworkDiff:
return self._diff_update_and_compare("opt", before, after) return self._diff_update_and_compare("opt", before, after)
def is_different(self): def is_different(self):
diff_func_list = [ diff_func_list = [func for func in dir(self) if callable(getattr(self, func)) and func.startswith("diffparam")]
func
for func in dir(self)
if callable(getattr(self, func)) and func.startswith("diffparam")
]
fail_fast = not bool(self.module._diff) fail_fast = not bool(self.module._diff)
different = False different = False
for func_name in diff_func_list: for func_name in diff_func_list:
@ -713,37 +687,21 @@ class PodmanNetwork:
is_different = diffcheck.is_different() is_different = diffcheck.is_different()
diffs = diffcheck.diff diffs = diffcheck.diff
if self.module._diff and is_different and diffs["before"] and diffs["after"]: if self.module._diff and is_different and diffs["before"] and diffs["after"]:
self.diff["before"] = ( self.diff["before"] = "\n".join(["%s - %s" % (k, v) for k, v in sorted(diffs["before"].items())]) + "\n"
"\n".join( self.diff["after"] = "\n".join(["%s - %s" % (k, v) for k, v in sorted(diffs["after"].items())]) + "\n"
["%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 return is_different
def get_info(self): def get_info(self):
"""Inspect network and gather info about it.""" """Inspect network and gather info about it."""
# pylint: disable=unused-variable # pylint: disable=unused-variable
rc, out, err = self.module.run_command( rc, out, err = self.module.run_command([self.module.params["executable"], b"network", b"inspect", self.name])
[self.module.params["executable"], b"network", b"inspect", self.name]
)
return json.loads(out)[0] if rc == 0 else {} return json.loads(out)[0] if rc == 0 else {}
def _get_podman_version(self): def _get_podman_version(self):
# pylint: disable=unused-variable # pylint: disable=unused-variable
rc, out, err = self.module.run_command( rc, out, err = self.module.run_command([self.module.params["executable"], b"--version"])
[self.module.params["executable"], b"--version"]
)
if rc != 0 or not out or "version" not in out: if rc != 0 or not out or "version" not in out:
self.module.fail_json( self.module.fail_json(msg="%s run failed!" % self.module.params["executable"])
msg="%s run failed!" % self.module.params["executable"]
)
return out.split("version")[1].strip() return out.split("version")[1].strip()
def _perform_action(self, action): def _perform_action(self, action):
@ -758,10 +716,7 @@ class PodmanNetwork:
self.version, self.version,
self.module, self.module,
).construct_command_from_params() ).construct_command_from_params()
full_cmd = " ".join( full_cmd = " ".join([self.module.params["executable"], "network"] + [to_native(i) for i in b_command])
[self.module.params["executable"], "network"]
+ [to_native(i) for i in b_command]
)
self.module.log("PODMAN-NETWORK-DEBUG: %s" % full_cmd) self.module.log("PODMAN-NETWORK-DEBUG: %s" % full_cmd)
self.actions.append(full_cmd) self.actions.append(full_cmd)
if not self.module.check_mode: if not self.module.check_mode:
@ -814,9 +769,7 @@ class PodmanNetworkManager:
"network": {}, "network": {},
} }
self.name = self.module.params["name"] self.name = self.module.params["name"]
self.executable = self.module.get_bin_path( self.executable = self.module.get_bin_path(self.module.params["executable"], required=True)
self.module.params["executable"], required=True
)
self.state = self.module.params["state"] self.state = self.module.params["state"]
self.recreate = self.module.params["recreate"] self.recreate = self.module.params["recreate"]
self.network = PodmanNetwork(self.module, self.name) self.network = PodmanNetwork(self.module, self.name)
@ -854,9 +807,7 @@ class PodmanNetworkManager:
} }
process_action = states_map[self.state] process_action = states_map[self.state]
process_action() process_action()
self.module.fail_json( self.module.fail_json(msg="Unexpected logic error happened, " "please contact maintainers ASAP!")
msg="Unexpected logic error happened, " "please contact maintainers ASAP!"
)
def make_present(self): def make_present(self):
"""Run actions if desired state is 'started'.""" """Run actions if desired state is 'started'."""
@ -891,9 +842,7 @@ class PodmanNetworkManager:
def main(): def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec=dict( argument_spec=dict(
state=dict( state=dict(type="str", default="present", choices=["present", "absent", "quadlet"]),
type="str", default="present", choices=["present", "absent", "quadlet"]
),
name=dict(type="str", required=True), name=dict(type="str", required=True),
disable_dns=dict(type="bool", required=False), disable_dns=dict(type="bool", required=False),
dns=dict(type="list", elements="str", required=False), dns=dict(type="list", elements="str", required=False),
@ -903,9 +852,7 @@ def main():
interface_name=dict(type="str", required=False), interface_name=dict(type="str", required=False),
internal=dict(type="bool", required=False), internal=dict(type="bool", required=False),
ip_range=dict(type="str", required=False), ip_range=dict(type="str", required=False),
ipam_driver=dict( ipam_driver=dict(type="str", required=False, choices=["host-local", "dhcp", "none"]),
type="str", required=False, choices=["host-local", "dhcp", "none"]
),
ipv6=dict(type="bool", required=False), ipv6=dict(type="bool", required=False),
subnet=dict(type="str", required=False), subnet=dict(type="str", required=False),
macvlan=dict(type="str", required=False), macvlan=dict(type="str", required=False),

View file

@ -105,9 +105,7 @@ def get_network_info(module, executable, name):
def main(): def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec=dict( argument_spec=dict(executable=dict(type="str", default="podman"), name=dict(type="str")),
executable=dict(type="str", default="podman"), name=dict(type="str")
),
supports_check_mode=True, supports_check_mode=True,
) )

View file

@ -276,9 +276,7 @@ class PodmanKubeManagement:
self.command.extend(["--configmap=%s" % configmaps]) self.command.extend(["--configmap=%s" % configmaps])
if self.module.params["log_opt"]: if self.module.params["log_opt"]:
for k, v in self.module.params["log_opt"].items(): for k, v in self.module.params["log_opt"].items():
self.command.extend( self.command.extend(["--log-opt", "{k}={v}".format(k=k.replace("_", "-"), v=v)])
["--log-opt", "{k}={v}".format(k=k.replace("_", "-"), v=v)]
)
start = self.module.params["state"] == "started" start = self.module.params["state"] == "started"
self.command.extend(["--start=%s" % str(start).lower()]) self.command.extend(["--start=%s" % str(start).lower()])
for arg, param in { for arg, param in {
@ -302,9 +300,7 @@ class PodmanKubeManagement:
def _command_run(self, cmd): def _command_run(self, cmd):
if self.module.params["kube_file_content"]: if self.module.params["kube_file_content"]:
rc, out, err = self.module.run_command( rc, out, err = self.module.run_command(cmd, data=self.module.params["kube_file_content"])
cmd, data=self.module.params["kube_file_content"]
)
else: else:
rc, out, err = self.module.run_command(cmd) rc, out, err = self.module.run_command(cmd)
self.actions.append(" ".join(cmd)) self.actions.append(" ".join(cmd))
@ -324,20 +320,15 @@ class PodmanKubeManagement:
kube_file = self.module.params["kube_file"] kube_file = self.module.params["kube_file"]
kube_file_content = self.module.params["kube_file_content"] kube_file_content = self.module.params["kube_file_content"]
if kube_file: if kube_file:
rc, out, err = self._command_run( rc, out, err = self._command_run([self.executable, "kube", "play", "--down", kube_file])
[self.executable, "kube", "play", "--down", kube_file]
)
elif kube_file_content: elif kube_file_content:
rc, out, err = self._command_run( rc, out, err = self._command_run([self.executable, "kube", "play", "--down", "-"])
[self.executable, "kube", "play", "--down", "-"]
)
if rc != 0 and "no such pod" in err: if rc != 0 and "no such pod" in err:
changed = False changed = False
return changed, out, err return changed, out, err
if rc != 0: if rc != 0:
self.module.fail_json( self.module.fail_json(
msg="Failed to delete Pod with %s: %s %s" msg="Failed to delete Pod with %s: %s %s" % (kube_file if kube_file else "YAML content", out, err)
% (kube_file if kube_file else "YAML content", out, err)
) )
# hack to check if no resources are deleted # hack to check if no resources are deleted
@ -386,9 +377,7 @@ class PodmanKubeManagement:
out_all, err_all = "", "" out_all, err_all = "", ""
# Delete all pods # Delete all pods
for pod_id in pods: for pod_id in pods:
rc, out, err = self._command_run( rc, out, err = self._command_run([self.executable, "pod", "rm", "-f", pod_id])
[self.executable, "pod", "rm", "-f", pod_id]
)
if rc != 0: if rc != 0:
self.module.fail_json("Can NOT delete Pod %s" % pod_id) self.module.fail_json("Can NOT delete Pod %s" % pod_id)
else: else:
@ -398,9 +387,7 @@ class PodmanKubeManagement:
return changed, out_all, err_all return changed, out_all, err_all
def pod_recreate(self): def pod_recreate(self):
if self.version is not None and LooseVersion(self.version) >= LooseVersion( if self.version is not None and LooseVersion(self.version) >= LooseVersion("3.4.0"):
"3.4.0"
):
self.tear_down_pods() self.tear_down_pods()
else: else:
pods = self.discover_pods() pods = self.discover_pods()
@ -420,9 +407,7 @@ class PodmanKubeManagement:
changed = True changed = True
else: else:
changed = False changed = False
err = "\n".join( err = "\n".join([i for i in err.splitlines() if "pod already exists" not in i])
[i for i in err.splitlines() if "pod already exists" not in i]
)
elif rc != 0: elif rc != 0:
self.module.fail_json(msg="Output: %s\nError=%s" % (out, err)) self.module.fail_json(msg="Output: %s\nError=%s" % (out, err))
else: else:
@ -472,9 +457,7 @@ def main():
quiet=dict(type="bool"), quiet=dict(type="bool"),
recreate=dict(type="bool"), recreate=dict(type="bool"),
userns=dict(type="str"), userns=dict(type="str"),
log_level=dict( log_level=dict(type="str", choices=["debug", "info", "warn", "error", "fatal", "panic"]),
type="str", choices=["debug", "info", "warn", "error", "fatal", "panic"]
),
quadlet_dir=dict(type="path", required=False), quadlet_dir=dict(type="path", required=False),
quadlet_filename=dict(type="str", required=False), quadlet_filename=dict(type="str", required=False),
quadlet_file_mode=dict(type="raw", required=False), quadlet_file_mode=dict(type="raw", required=False),
@ -494,13 +477,8 @@ def main():
changed = False changed = False
out = err = "" out = err = ""
if module.params["state"] == "absent": if module.params["state"] == "absent":
if manage.version is not None and LooseVersion(manage.version) > LooseVersion( if manage.version is not None and LooseVersion(manage.version) > LooseVersion("3.4.0"):
"3.4.0" manage.module.log(msg="version: %s, kube file %s" % (manage.version, manage.module.params["kube_file"]))
):
manage.module.log(
msg="version: %s, kube file %s"
% (manage.version, manage.module.params["kube_file"])
)
changed, out, err = manage.tear_down_pods() changed, out, err = manage.tear_down_pods()
else: else:
pods = manage.discover_pods() pods = manage.discover_pods()

View file

@ -185,9 +185,7 @@ def get_pod_info(module, executable, name):
def main(): def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec=dict( argument_spec=dict(executable=dict(type="str", default="podman"), name=dict(type="str")),
executable=dict(type="str", default="podman"), name=dict(type="str")
),
supports_check_mode=True, supports_check_mode=True,
) )

View file

@ -182,21 +182,14 @@ def filtersPrepare(target, filters):
) )
) )
else: else:
if target == "image" and ( if target == "image" and (common_filter in ("dangling_only", "external")):
common_filter in ("dangling_only", "external") if common_filter == "dangling_only" and not filters["dangling_only"]:
):
if (
common_filter == "dangling_only"
and not filters["dangling_only"]
):
filter_out.append("-a") filter_out.append("-a")
if common_filter == "external" and filters["external"]: if common_filter == "external" and filters["external"]:
filter_out.append("--external") filter_out.append("--external")
else: else:
filter_out.append( filter_out.append(
"--filter={label}={value}".format( "--filter={label}={value}".format(label=common_filter, value=filters[common_filter])
label=common_filter, value=filters[common_filter]
)
) )
return filter_out return filter_out
@ -210,11 +203,7 @@ def podmanExec(module, target, filters, executable):
changed = bool(out) changed = bool(out)
if rc != 0: if rc != 0:
module.fail_json( module.fail_json(msg="Error executing prune on {target}: {err}".format(target=target, err=err))
msg="Error executing prune on {target}: {err}".format(
target=target, err=err
)
)
return { return {
"changed": changed, "changed": changed,
@ -251,9 +240,7 @@ def main():
("volume", "volume_filters"), ("volume", "volume_filters"),
): ):
if module.params[target]: if module.params[target]:
results[target] = podmanExec( results[target] = podmanExec(module, target, module.params[filters], executable)
module, target, module.params[filters], executable
)
if module.params["system"]: if module.params["system"]:
target = "system" target = "system"

View file

@ -56,10 +56,7 @@ def runlabel(module, executable):
if rc == 0: if rc == 0:
changed = True changed = True
else: else:
module.fail_json( module.fail_json(msg="Error running the runlabel from image %s: %s" % (module.params["image"], err))
msg="Error running the runlabel from image %s: %s"
% (module.params["image"], err)
)
return changed, out, err return changed, out, err

View file

@ -140,9 +140,7 @@ def main():
"oci-dir", "oci-dir",
"docker-dir", "docker-dir",
]: ]:
module.fail_json( module.fail_json(msg="Compression is only supported for oci-dir and docker-dir format")
msg="Compression is only supported for oci-dir and docker-dir format"
)
executable = module.get_bin_path(module.params["executable"], required=True) executable = module.get_bin_path(module.params["executable"], required=True)
changed, out, err = save(module, executable) changed, out, err = save(module, executable)

View file

@ -119,11 +119,7 @@ def main():
try: try:
results = json.loads(result_str) results = json.loads(result_str)
except json.decoder.JSONDecodeError: except json.decoder.JSONDecodeError:
module.fail_json( module.fail_json(msg="Failed to parse JSON output from podman search: {out}".format(out=result_str))
msg="Failed to parse JSON output from podman search: {out}".format(
out=result_str
)
)
results = dict( results = dict(
changed=False, changed=False,

View file

@ -126,17 +126,13 @@ diff = {"before": "", "after": ""}
def podman_secret_exists(module, executable, name, version): def podman_secret_exists(module, executable, name, version):
if version is None or LooseVersion(version) < LooseVersion("4.5.0"): if version is None or LooseVersion(version) < LooseVersion("4.5.0"):
rc, out, err = module.run_command( rc, out, err = module.run_command([executable, "secret", "ls", "--format", "{{.Name}}"])
[executable, "secret", "ls", "--format", "{{.Name}}"]
)
return name in [i.strip() for i in out.splitlines()] return name in [i.strip() for i in out.splitlines()]
rc, out, err = module.run_command([executable, "secret", "exists", name]) rc, out, err = module.run_command([executable, "secret", "exists", name])
return rc == 0 return rc == 0
def need_update( def need_update(module, executable, name, data, path, env, skip, driver, driver_opts, debug, labels):
module, executable, name, data, path, env, skip, driver, driver_opts, debug, labels
):
cmd = [executable, "secret", "inspect", "--showsecret", name] cmd = [executable, "secret", "inspect", "--showsecret", name]
rc, out, err = module.run_command(cmd) rc, out, err = module.run_command(cmd)
if rc != 0: if rc != 0:
@ -186,9 +182,7 @@ def need_update(
for k, v in driver_opts.items(): for k, v in driver_opts.items():
if secret["Spec"]["Driver"]["Options"].get(k) != v: if secret["Spec"]["Driver"]["Options"].get(k) != v:
diff["after"] = "=".join([k, v]) diff["after"] = "=".join([k, v])
diff["before"] = "=".join( diff["before"] = "=".join([k, secret["Spec"]["Driver"]["Options"].get(k)])
[k, secret["Spec"]["Driver"]["Options"].get(k)]
)
return True return True
if labels: if labels:
for k, v in labels.items(): for k, v in labels.items():
@ -216,9 +210,7 @@ def podman_secret_create(
labels, labels,
): ):
podman_version = get_podman_version(module, fail=False) podman_version = get_podman_version(module, fail=False)
if podman_version is not None and LooseVersion(podman_version) >= LooseVersion( if podman_version is not None and LooseVersion(podman_version) >= LooseVersion("4.7.0"):
"4.7.0"
):
if need_update( if need_update(
module, module,
executable, executable,

View file

@ -87,9 +87,7 @@ def get_secret_info(module, executable, show, name):
command.extend(name) command.extend(name)
rc, out, err = module.run_command(command) rc, out, err = module.run_command(command)
if rc != 0 or "no secret with name or id" in err: if rc != 0 or "no secret with name or id" in err:
module.fail_json( module.fail_json(msg="Unable to gather info for %s: %s" % (name or "all secrets", err))
msg="Unable to gather info for %s: %s" % (name or "all secrets", err)
)
if not out or json.loads(out) is None: if not out or json.loads(out) is None:
return [], out, err return [], out, err
return json.loads(out), out, err return json.loads(out), out, err

View file

@ -61,9 +61,7 @@ def tag(module, executable):
if rc == 0: if rc == 0:
changed = True changed = True
else: else:
module.fail_json( module.fail_json(msg="Error tagging local image %s: %s" % (module.params["image"], err))
msg="Error tagging local image %s: %s" % (module.params["image"], err)
)
return changed, out, err return changed, out, err

View file

@ -206,9 +206,7 @@ class PodmanVolumeModuleParams:
def _create_action(self): def _create_action(self):
cmd = [self.action, self.params["name"]] cmd = [self.action, self.params["name"]]
all_param_methods = [ all_param_methods = [
func func for func in dir(self) if callable(getattr(self, func)) and func.startswith("addparam")
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) params_set = (i for i in self.params if self.params[i] is not None)
for param in params_set: for param in params_set:
@ -221,14 +219,12 @@ class PodmanVolumeModuleParams:
if minv and LooseVersion(minv) > LooseVersion(self.podman_version): if minv and LooseVersion(minv) > LooseVersion(self.podman_version):
self.module.fail_json( self.module.fail_json(
msg="Parameter %s is supported from podman " msg="Parameter %s is supported from podman "
"version %s only! Current version is %s" "version %s only! Current version is %s" % (param, minv, self.podman_version)
% (param, minv, self.podman_version)
) )
if maxv and LooseVersion(maxv) < LooseVersion(self.podman_version): if maxv and LooseVersion(maxv) < LooseVersion(self.podman_version):
self.module.fail_json( self.module.fail_json(
msg="Parameter %s is supported till podman " msg="Parameter %s is supported till podman "
"version %s only! Current version is %s" "version %s only! Current version is %s" % (param, minv, self.podman_version)
% (param, minv, self.podman_version)
) )
def addparam_label(self, c): def addparam_label(self, c):
@ -271,9 +267,7 @@ class PodmanVolumeDiff:
def defaultize(self): def defaultize(self):
params_with_defaults = {} params_with_defaults = {}
self.default_dict = PodmanVolumeDefaults( self.default_dict = PodmanVolumeDefaults(self.module, self.version).default_dict()
self.module, self.version
).default_dict()
for p in self.module.params: for p in self.module.params:
if self.module.params[p] is None and p in self.default_dict: if self.module.params[p] is None and p in self.default_dict:
params_with_defaults[p] = self.default_dict[p] params_with_defaults[p] = self.default_dict[p]
@ -325,11 +319,7 @@ class PodmanVolumeDiff:
return self._diff_update_and_compare("options", before, after) return self._diff_update_and_compare("options", before, after)
def is_different(self): def is_different(self):
diff_func_list = [ diff_func_list = [func for func in dir(self) if callable(getattr(self, func)) and func.startswith("diffparam")]
func
for func in dir(self)
if callable(getattr(self, func)) and func.startswith("diffparam")
]
fail_fast = not bool(self.module._diff) fail_fast = not bool(self.module._diff)
different = False different = False
for func_name in diff_func_list: for func_name in diff_func_list:
@ -386,26 +376,14 @@ class PodmanVolume:
is_different = diffcheck.is_different() is_different = diffcheck.is_different()
diffs = diffcheck.diff diffs = diffcheck.diff
if self.module._diff and is_different and diffs["before"] and diffs["after"]: if self.module._diff and is_different and diffs["before"] and diffs["after"]:
self.diff["before"] = ( self.diff["before"] = "\n".join(["%s - %s" % (k, v) for k, v in sorted(diffs["before"].items())]) + "\n"
"\n".join( self.diff["after"] = "\n".join(["%s - %s" % (k, v) for k, v in sorted(diffs["after"].items())]) + "\n"
["%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 return is_different
def get_info(self): def get_info(self):
"""Inspect volume and gather info about it.""" """Inspect volume and gather info about it."""
# pylint: disable=unused-variable # pylint: disable=unused-variable
rc, out, err = self.module.run_command( rc, out, err = self.module.run_command([self.module.params["executable"], b"volume", b"inspect", self.name])
[self.module.params["executable"], b"volume", b"inspect", self.name]
)
if rc == 0: if rc == 0:
data = json.loads(out) data = json.loads(out)
if data: if data:
@ -416,13 +394,9 @@ class PodmanVolume:
def _get_podman_version(self): def _get_podman_version(self):
# pylint: disable=unused-variable # pylint: disable=unused-variable
rc, out, err = self.module.run_command( rc, out, err = self.module.run_command([self.module.params["executable"], b"--version"])
[self.module.params["executable"], b"--version"]
)
if rc != 0 or not out or "version" not in out: if rc != 0 or not out or "version" not in out:
self.module.fail_json( self.module.fail_json(msg="%s run failed!" % self.module.params["executable"])
msg="%s run failed!" % self.module.params["executable"]
)
return out.split("version")[1].strip() return out.split("version")[1].strip()
def _perform_action(self, action): def _perform_action(self, action):
@ -437,10 +411,7 @@ class PodmanVolume:
self.version, self.version,
self.module, self.module,
).construct_command_from_params() ).construct_command_from_params()
full_cmd = " ".join( full_cmd = " ".join([self.module.params["executable"], "volume"] + [to_native(i) for i in b_command])
[self.module.params["executable"], "volume"]
+ [to_native(i) for i in b_command]
)
# check if running not from root # check if running not from root
if os.getuid() != 0 and action == "mount": if os.getuid() != 0 and action == "mount":
full_cmd = f"{self.module.params['executable']} unshare {full_cmd}" full_cmd = f"{self.module.params['executable']} unshare {full_cmd}"
@ -504,9 +475,7 @@ class PodmanVolumeManager:
"volume": {}, "volume": {},
} }
self.name = self.module.params["name"] self.name = self.module.params["name"]
self.executable = self.module.get_bin_path( self.executable = self.module.get_bin_path(self.module.params["executable"], required=True)
self.module.params["executable"], required=True
)
self.state = self.module.params["state"] self.state = self.module.params["state"]
self.recreate = self.module.params["recreate"] self.recreate = self.module.params["recreate"]
self.volume = PodmanVolume(self.module, self.name) self.volume = PodmanVolume(self.module, self.name)
@ -546,9 +515,7 @@ class PodmanVolumeManager:
} }
process_action = states_map[self.state] process_action = states_map[self.state]
process_action() process_action()
self.module.fail_json( self.module.fail_json(msg="Unexpected logic error happened, " "please contact maintainers ASAP!")
msg="Unexpected logic error happened, " "please contact maintainers ASAP!"
)
def make_present(self): def make_present(self):
"""Run actions if desired state is 'started'.""" """Run actions if desired state is 'started'."""

View file

@ -73,9 +73,7 @@ def get_volume_info(module, executable, name):
command.append("--all") command.append("--all")
rc, out, err = module.run_command(command) rc, out, err = module.run_command(command)
if rc != 0 or "no such volume" in err: if rc != 0 or "no such volume" in err:
module.fail_json( module.fail_json(msg="Unable to gather info for %s: %s" % (name or "all volumes", err))
msg="Unable to gather info for %s: %s" % (name or "all volumes", err)
)
if not out or json.loads(out) is None: if not out or json.loads(out) is None:
return [], out, err return [], out, err
return json.loads(out), out, err return json.loads(out), out, err
@ -83,9 +81,7 @@ def get_volume_info(module, executable, name):
def main(): def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec=dict( argument_spec=dict(executable=dict(type="str", default="podman"), name=dict(type="str")),
executable=dict(type="str", default="podman"), name=dict(type="str")
),
supports_check_mode=True, supports_check_mode=True,
) )