Debian Codegraph @

ansible_collections/containers/podman/plugins/modules/podman_quadlet.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2025 Red Hat
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 # flake8: noqa: E501
6 from __future__ import absolute_import, division, print_function
7
8 __metaclass__ = type
9
10
11 DOCUMENTATION = r"""
12 module: podman_quadlet
13 author:
14 - "Sagi Shnaidman (@sshnaidm)"
15 short_description: Install or remove Podman Quadlets
16 description:
17 - Install or remove Podman Quadlets using C(podman quadlet install) and C(podman quadlet rm).
18 - Creation of quadlet files is handled by resource modules with I(state=quadlet).
19 - Updates are handled by removing the existing quadlet and installing the new one.
20 - "Idempotency for local sources uses Podman's .app/.asset manifest files and direct content comparison."
21 - "For remote URLs, the module always reinstalls to ensure the host matches the configured source (reports changed=true)."
22 - Supports C(.quadlets) files containing multiple quadlet sections separated by C(---) delimiter (requires Podman 6.0+).
23 - Each section in a C(.quadlets) file must include a C(# FileName=<name>) comment to specify the output filename.
24 requirements:
25 - podman
26 options:
27 state:
28 description:
29 - Desired state of quadlet(s).
30 type: str
31 default: present
32 choices:
33 - present
34 - absent
35 name:
36 description:
37 - Name (filename without path) of an installed quadlet to remove when I(state=absent).
38 - If the name does not include the type suffix (e.g. C(.container)), the module will attempt to find a matching quadlet file.
39 type: list
40 elements: str
41 src:
42 description:
43 - Path to a quadlet file, a directory containing a quadlet application, or a URL to install when I(state=present).
44 - For local files and directories, full idempotency is provided (content comparison).
45 - For remote URLs, the module always installs fresh and reports C(changed=true) since content cannot be verified.
46 - Directory installs support only top-level files; nested subdirectories will cause an error.
47 type: str
48 files:
49 description:
50 - Additional non-quadlet files or URLs to install along with the primary I(src) (quadlet application use-case).
51 - Passed positionally to C(podman quadlet install) after I(src).
52 - For local files, full idempotency is provided.
53 - If any file is a URL, the entire install always reports C(changed=true) since remote content cannot be verified.
54 type: list
55 elements: str
56 quadlet_dir:
57 description:
58 - Override the target quadlet directory used for idempotency checks.
59 - By default it follows Podman defaults.
60 - C(/etc/containers/systemd/) for root, C(~/.config/containers/systemd/) for non-root.
61 - Note this is used for content comparison only and is not passed to Podman.
62 type: path
63 reload_systemd:
64 description:
65 - Control systemd reload behavior in Podman. When true, pass C(--reload-systemd).
66 - When false, pass C(--reload-systemd=false).
67 type: bool
68 default: true
69 force:
70 description:
71 - Force removal when I(state=absent) (maps to C(podman quadlet rm --force)).
72 type: bool
73 default: true
74 all:
75 description:
76 - Remove all installed quadlets when I(state=absent) (maps to C(podman quadlet rm --all)).
77 type: bool
78 default: false
79 executable:
80 description:
81 - Path to C(podman) executable if it is not in the C($PATH) on the machine running C(podman)
82 default: 'podman'
83 type: str
84 cmd_args:
85 description:
86 - Extra global arguments to pass to the C(podman) command (e.g., C(--log-level=debug)).
87 - These are placed after the executable and before the subcommand.
88 type: list
89 elements: str
90 debug:
91 description:
92 - Return additional information which can be helpful for investigations.
93 type: bool
94 default: false
95 """
96
97
98 RETURN = r"""
99 changed:
100 description: Whether any change was made
101 returned: always
102 type: bool
103 actions:
104 description: Human-readable actions performed
105 returned: always
106 type: list
107 podman_actions:
108 description: Executed podman command lines
109 returned: always
110 type: list
111 quadlets:
112 description: List of affected quadlets with name, path, and scope
113 returned: always
114 type: list
115 stdout:
116 description: podman stdout
117 returned: when debug=true
118 type: str
119 stderr:
120 description: podman stderr
121 returned: when debug=true
122 type: str
123 _debug_spec:
124 description: Internal specification used for idempotency detection
125 returned: when debug=true and state=present
126 type: dict
127 contains:
128 mode:
129 description: Install mode (dir_app, quadlets_app, single_file, or remote)
130 type: str
131 marker_name:
132 description: The .app or .asset marker filename used by Podman
133 type: str
134 desired_files:
135 description: List of filenames that should be installed
136 type: list
137 removal_target:
138 description: What will be passed to 'podman quadlet rm' for updates
139 type: str
140 _debug_installed_files:
141 description: List of currently installed files detected from Podman manifests
142 returned: when debug=true and state=present and mode is not remote
143 type: list
144 """
145
146
147 EXAMPLES = r"""
148 - name: Install a simple quadlet file
149 containers.podman.podman_quadlet:
150 state: present
151 src: /tmp/myapp.container
152
153 - name: Install a quadlet application with additional config files
154 containers.podman.podman_quadlet:
155 state: present
156 src: /tmp/myapp.container
157 files:
158 - /tmp/myapp.conf
159 - /tmp/secrets.env
160
161 - name: Install quadlet application from a directory
162 containers.podman.podman_quadlet:
163 state: present
164 src: /tmp/myapp_dir/
165
166 - name: Install with custom quadlet directory (e.g. for system-wide install)
167 containers.podman.podman_quadlet:
168 state: present
169 src: /tmp/myapp.container
170 quadlet_dir: /etc/containers/systemd
171 become: true
172
173 - name: Remove a specific quadlet
174 containers.podman.podman_quadlet:
175 state: absent
176 name:
177 - myapp.container
178
179 - name: Remove multiple quadlets
180 containers.podman.podman_quadlet:
181 state: absent
182 name:
183 - myapp.container
184 - database.container
185 - cache.container
186
187 - name: Remove quadlet without suffix (module resolves to .container, .pod, etc.)
188 containers.podman.podman_quadlet:
189 state: absent
190 name:
191 - myapp
192
193 - name: Remove all quadlets (use with caution)
194 containers.podman.podman_quadlet:
195 state: absent
196 all: true
197
198 - name: Install quadlet from a URL (always reports changed=true)
199 containers.podman.podman_quadlet:
200 state: present
201 src: https://example.com/myapp.container
202
203 - name: Install multi-quadlet application from .quadlets file (Podman 6.0+)
204 containers.podman.podman_quadlet:
205 state: present
206 src: /tmp/webapp.quadlets
207 """
208
209
210 import os
211 import json
212
213 from ansible.module_utils.basic import AnsibleModule # noqa: F402
214
215 try:
216 from ansible.module_utils.common.text.converters import to_native # noqa: F402
217 except ImportError:
218 from ansible.module_utils.common.text import to_native # noqa: F402
219 from ..module_utils.podman.quadlet import (
220 resolve_quadlet_dir,
221 QUADLET_SUFFIXES,
222 )
223 from ..module_utils.podman.common import get_podman_version
224
225 # Install modes
226 MODE_DIR_APP = "dir_app"
227 MODE_QUADLETS_APP = "quadlets_app"
228 MODE_SINGLE_FILE = "single_file"
229 MODE_REMOTE = "remote"
230
231
232 def _is_remote_ref(path):
233 """Check if the path is a remote URL or OCI artifact reference."""
234 if path is None:
235 return False
236 path_lower = path.lower()
237 return path_lower.startswith("http://") or path_lower.startswith("https://")
238
239
240 def _read_lines_if_exists(path):
241 """Read lines from a file if it exists, returning a set of non-empty lines."""
242 if not os.path.exists(path):
243 return set()
244 try:
245 with open(path, "r") as f:
246 return {line.strip() for line in f if line.strip()}
247 except (IOError, OSError):
248 return set()
249
250
251 def _read_file_bytes(path):
252 """Read file contents as bytes, return None if cannot read."""
253 try:
254 with open(path, "rb") as f:
255 return f.read()
256 except (IOError, OSError):
257 return None
258
259
260 def _get_asset_marker_for_quadlet(quadlet_name):
261 """Get the .asset marker filename for a single quadlet file."""
262 return ".%s.asset" % quadlet_name
263
264
265 def _add_extra_files(module, extra_files, desired_files):
266 """Add extra files to desired_files dict, validating they exist."""
267 for f in extra_files:
268 if not os.path.isfile(f):
269 module.fail_json(msg="Extra file %s is not a file" % f)
270 content = _read_file_bytes(f)
271 if content is not None:
272 desired_files[os.path.basename(f)] = content
273
274
275 def _parse_quadlets_file(path):
276 """Parse a .quadlets file and return a dict of {filename: content}.
277
278 Each section is separated by '---' and must have a '# FileName=<name>' comment.
279 The extension is detected from the section content (e.g. [Container] -> .container).
280 """
281 try:
282 with open(path, "r") as f:
283 content = f.read()
284 except (IOError, OSError):
285 return None
286
287 sections = []
288 current_section = []
289
290 for line in content.split("\n"):
291 if line.strip() == "---":
292 if current_section:
293 sections.append("\n".join(current_section))
294 current_section = []
295 else:
296 current_section.append(line)
297
298 if current_section:
299 sections.append("\n".join(current_section))
300
301 result = {}
302 for section in sections:
303 section = section.strip()
304 if not section:
305 continue
306
307 # Extract FileName from comments
308 filename = None
309 extension = None
310 for line in section.split("\n"):
311 line_stripped = line.strip()
312 if line_stripped.startswith("#"):
313 comment_content = line_stripped[1:].strip()
314 if comment_content.startswith("FileName="):
315 filename = comment_content[9:].strip()
316 elif line_stripped.startswith("[") and line_stripped.endswith("]"):
317 section_name = line_stripped[1:-1].lower()
318 extension = ".%s" % section_name
319
320 if filename and extension:
321 full_filename = filename + extension
322 result[full_filename] = section.encode("utf-8")
323
324 return result
325
326
327 def _build_desired_spec(module, src, extra_files):
328 """Build a specification of what should be installed.
329
330 Returns a dict with:
331 - mode: one of MODE_DIR_APP, MODE_QUADLETS_APP, MODE_SINGLE_FILE, MODE_REMOTE
332 - marker_name: the .app or .asset marker filename (None for remote)
333 - desired_files: dict of {installed_filename: bytes} for local sources
334 - removal_target: what to pass to 'podman quadlet rm' for updates
335 """
336 extra_files = extra_files or []
337
338 # Check if src is a remote reference
339 if _is_remote_ref(src):
340 return {
341 "mode": MODE_REMOTE,
342 "marker_name": None,
343 "desired_files": {},
344 "removal_target": None,
345 }
346
347 # Check if any extra file is remote
348 for f in extra_files:
349 if _is_remote_ref(f):
350 return {
351 "mode": MODE_REMOTE,
352 "marker_name": None,
353 "desired_files": {},
354 "removal_target": None,
355 }
356
357 # Local source - check existence
358 if not os.path.exists(src):
359 module.fail_json(msg="Source file or directory %s does not exist" % src)
360
361 desired_files = {}
362
363 if os.path.isdir(src):
364 # Directory install - creates .app marker
365 basename = os.path.basename(src.rstrip("/"))
366 marker_name = ".%s.app" % basename
367
368 # Validate: no subdirectories allowed (Podman doesn't support them)
369 for entry in os.listdir(src):
370 full_path = os.path.join(src, entry)
371 if os.path.isdir(full_path):
372 module.fail_json(
373 msg="Directory %s contains subdirectory '%s'. "
374 "Podman quadlet install does not support nested directories; "
375 "only top-level files are supported." % (src, entry)
376 )
377 if os.path.isfile(full_path):
378 content = _read_file_bytes(full_path)
379 if content is not None:
380 desired_files[entry] = content
381
382 _add_extra_files(module, extra_files, desired_files)
383
384 return {
385 "mode": MODE_DIR_APP,
386 "marker_name": marker_name,
387 "desired_files": desired_files,
388 "removal_target": marker_name,
389 }
390
391 elif os.path.isfile(src):
392 basename = os.path.basename(src)
393
394 # Check if it's a .quadlets file
395 if src.endswith(".quadlets"):
396 # .quadlets file requires Podman 6.0+
397 version_str = get_podman_version(module, fail=False)
398 if version_str:
399 try:
400 major_version = int(version_str.split(".")[0])
401 if major_version < 6:
402 module.fail_json(
403 msg=".quadlets files require Podman 6.0 or later (current: %s)" % version_str
404 )
405 except (ValueError, IndexError):
406 pass # If we can't parse version, let Podman handle it
407
408 # .quadlets file - creates .app marker with extracted quadlets
409 marker_name = ".%s.app" % os.path.splitext(basename)[0]
410 parsed = _parse_quadlets_file(src)
411 if parsed is None:
412 module.fail_json(msg="Failed to parse .quadlets file %s" % src)
413 desired_files = parsed
414
415 _add_extra_files(module, extra_files, desired_files)
416
417 return {
418 "mode": MODE_QUADLETS_APP,
419 "marker_name": marker_name,
420 "desired_files": desired_files,
421 "removal_target": marker_name,
422 }
423 else:
424 # Single quadlet file - creates .asset marker for extra files only
425 content = _read_file_bytes(src)
426 if content is not None:
427 desired_files[basename] = content
428
429 _add_extra_files(module, extra_files, desired_files)
430
431 return {
432 "mode": MODE_SINGLE_FILE,
433 "marker_name": _get_asset_marker_for_quadlet(basename) if extra_files else None,
434 "desired_files": desired_files,
435 "removal_target": basename,
436 }
437 else:
438 module.fail_json(msg="Source %s is not a file or directory" % src)
439
440
441 def _get_installed_files_for_spec(spec, quadlet_dir):
442 """Get the set of installed filenames based on the spec mode.
443
444 For .app modes: read the .app marker file
445 For single_file mode: the quadlet file + contents of .asset marker
446 """
447 if spec["mode"] == MODE_REMOTE:
448 return set()
449
450 if spec["mode"] in (MODE_DIR_APP, MODE_QUADLETS_APP):
451 # Read .app marker
452 marker_path = os.path.join(quadlet_dir, spec["marker_name"])
453 return _read_lines_if_exists(marker_path)
454
455 elif spec["mode"] == MODE_SINGLE_FILE:
456 # The primary quadlet file + any assets
457 installed = set()
458 primary_quadlet_name = None
459
460 # Get the primary file name from desired_files
461 for name in spec["desired_files"]:
462 # Check if it's the primary quadlet (has a quadlet suffix)
463 for suffix in QUADLET_SUFFIXES:
464 if name.endswith(suffix):
465 primary_quadlet_name = name
466 # Only add to installed set if file actually exists
467 if os.path.exists(os.path.join(quadlet_dir, name)):
468 installed.add(name)
469 break
470
471 # ALWAYS check for .asset marker based on primary quadlet name
472 # This is needed to detect when assets are removed from the install
473 if primary_quadlet_name:
474 asset_marker_path = os.path.join(quadlet_dir, _get_asset_marker_for_quadlet(primary_quadlet_name))
475 installed.update(_read_lines_if_exists(asset_marker_path))
476
477 return installed
478
479 return set()
480
481
482 def _needs_change(spec, quadlet_dir):
483 """Determine if installation/update is needed.
484
485 For remote mode: always returns True (best-effort, let Podman decide)
486 For local modes: compare desired vs installed file sets and contents
487 """
488 if spec["mode"] == MODE_REMOTE:
489 # For remote, we'll try to install and let Podman tell us if it exists
490 return True
491
492 desired_set = set(spec["desired_files"].keys())
493 installed_set = _get_installed_files_for_spec(spec, quadlet_dir)
494
495 # If sets differ, definitely need change
496 if desired_set != installed_set:
497 return True
498
499 # Compare content of each file
500 for filename, desired_content in spec["desired_files"].items():
501 installed_path = os.path.join(quadlet_dir, filename)
502 installed_content = _read_file_bytes(installed_path)
503 if installed_content is None or installed_content != desired_content:
504 return True
505
506 return False
507
508
509 class PodmanQuadletManager:
510 def __init__(self, module):
511 self.module = module
512 self.results = {
513 "changed": False,
514 "actions": [],
515 "podman_actions": [],
516 "quadlets": [],
517 }
518 self.executable = module.get_bin_path(module.params["executable"], required=True)
519 self.quadlet_dir = resolve_quadlet_dir(module)
520
521 def _build_base_cmd(self):
522 """Build base command with executable and global args."""
523 cmd = [self.executable]
524 if self.module.params.get("cmd_args"):
525 cmd.extend(self.module.params["cmd_args"])
526 return cmd
527
528 def _build_install_cmd(self):
529 """Build quadlet install command."""
530 cmd = self._build_base_cmd()
531 cmd.extend(["quadlet", "install"])
532 if self.module.params["reload_systemd"]:
533 cmd.append("--reload-systemd")
534 else:
535 cmd.append("--reload-systemd=false")
536 cmd.append(self.module.params["src"])
537 if self.module.params.get("files"):
538 cmd.extend(self.module.params["files"])
539 return cmd
540
541 def _build_rm_cmd(self, names=None):
542 """Build quadlet rm command."""
543 cmd = self._build_base_cmd()
544 cmd.extend(["quadlet", "rm"])
545 if self.module.params["reload_systemd"]:
546 cmd.append("--reload-systemd")
547 else:
548 cmd.append("--reload-systemd=false")
549 if self.module.params.get("force"):
550 cmd.append("--force")
551 if self.module.params.get("all"):
552 cmd.append("--all")
553 if names:
554 cmd.extend(names)
555 return cmd
556
557 def _build_list_cmd(self):
558 """Build quadlet list command."""
559 cmd = self._build_base_cmd()
560 cmd.extend(["quadlet", "list", "--format", "json"])
561 return cmd
562
563 def _run(self, cmd, record=True):
564 """Run a command and optionally record it."""
565 self.module.log("PODMAN-QUADLET-DEBUG: %s" % " ".join([to_native(i) for i in cmd]))
566 if record:
567 self.results["podman_actions"].append(" ".join([to_native(i) for i in cmd]))
568 if self.module.check_mode:
569 return 0, "", ""
570 return self.module.run_command(cmd)
571
572 def _get_installed_quadlets(self):
573 """Get set of installed quadlet names.
574
575 This is a read-only operation that runs even in check_mode.
576 """
577 cmd = self._build_list_cmd()
578 self.module.log("PODMAN-QUADLET-DEBUG: %s" % " ".join([to_native(i) for i in cmd]))
579 # Always run list command, even in check_mode (it's read-only)
580 rc, out, err = self.module.run_command(cmd)
581 if rc != 0:
582 self.module.fail_json(
583 msg="Failed to list quadlets: %s" % err,
584 stdout=out,
585 stderr=err,
586 **self.results,
587 )
588 try:
589 quadlets = json.loads(out) if out.strip() else []
590 except json.JSONDecodeError as e:
591 self.module.fail_json(
592 msg="Failed to parse quadlet list output: %s" % str(e),
593 stdout=out,
594 stderr=err,
595 **self.results,
596 )
597 return {name for name in (q.get("Name") for q in quadlets) if name}
598
599 def _install(self):
600 src = self.module.params["src"]
601 extra_files = self.module.params.get("files") or []
602
603 # Build the desired spec using Podman's manifest-based approach
604 spec = _build_desired_spec(self.module, src, extra_files)
605
606 # Add debug info if requested
607 if self.module.params["debug"]:
608 self.results["_debug_spec"] = {
609 "mode": spec["mode"],
610 "marker_name": spec["marker_name"],
611 "desired_files": list(spec["desired_files"].keys()),
612 "removal_target": spec["removal_target"],
613 }
614 if spec["mode"] != MODE_REMOTE:
615 installed_set = _get_installed_files_for_spec(spec, self.quadlet_dir)
616 self.results["_debug_installed_files"] = list(installed_set)
617
618 # Check if change is needed
619 needs_change = _needs_change(spec, self.quadlet_dir)
620
621 if not needs_change:
622 # Already up to date
623 return
624
625 # For remote sources, we cannot verify content matches the URL.
626 # To ensure Ansible's contract (what's configured = what's on host),
627 # we always install fresh. Try install first, if "already exists",
628 # remove and reinstall.
629 if spec["mode"] == MODE_REMOTE:
630 cmd = self._build_install_cmd()
631 rc, out, err = self._run(cmd)
632 if rc != 0:
633 err_lower = err.lower()
634 if "already exists" in err_lower or "refusing to overwrite" in err_lower:
635 # Need to remove existing and reinstall to ensure fresh content
636 # Extract the quadlet name from the error or URL
637 quadlet_name = os.path.basename(src)
638 rm_cmd = self._build_rm_cmd([quadlet_name])
639 rm_rc, rm_out, rm_err = self._run(rm_cmd)
640 # Ignore rm errors (might not exist with exact name)
641 if rm_rc != 0:
642 rm_err_lower = rm_err.lower()
643 if "does not exist" not in rm_err_lower and "no such" not in rm_err_lower:
644 # Try to proceed anyway - maybe Podman can handle it
645 pass
646 self.results["actions"].append("removed existing quadlet for reinstall from remote")
647
648 # Retry install
649 cmd = self._build_install_cmd()
650 rc, out, err = self._run(cmd)
651 if rc != 0:
652 self.module.fail_json(
653 msg="Failed to install quadlet(s) from remote: %s" % err,
654 stdout=out,
655 stderr=err,
656 **self.results,
657 )
658 else:
659 self.module.fail_json(
660 msg="Failed to install quadlet(s): %s" % err,
661 stdout=out,
662 stderr=err,
663 **self.results,
664 )
665
666 # Remote installs always report changed=true since we can't verify content
667 self.results["changed"] = True
668 self.results["actions"].append("installed quadlets from %s" % src)
669 self.results["quadlets"].append({"source": src, "path": self.quadlet_dir})
670 if self.module.params["debug"]:
671 self.results.update({"stdout": out, "stderr": err})
672 return
673
674 # For local sources with changes needed, remove existing then install
675 removal_target = spec["removal_target"]
676 if removal_target:
677 # Check if the removal target exists
678 marker_path = os.path.join(self.quadlet_dir, removal_target)
679 target_exists = False
680
681 if spec["mode"] in (MODE_DIR_APP, MODE_QUADLETS_APP):
682 # For app modes, check if .app marker exists
683 target_exists = os.path.exists(marker_path)
684 else:
685 # For single file mode, check if the quadlet file exists
686 quadlet_path = os.path.join(self.quadlet_dir, removal_target)
687 target_exists = os.path.exists(quadlet_path)
688
689 if target_exists:
690 rm_cmd = self._build_rm_cmd([removal_target])
691 rc, out, err = self._run(rm_cmd)
692 if rc != 0:
693 err_lower = err.lower()
694 if "does not exist" not in err_lower and "no such" not in err_lower:
695 self.module.fail_json(
696 msg="Failed to remove existing quadlet for update: %s" % err,
697 stdout=out,
698 stderr=err,
699 **self.results,
700 )
701 self.results["actions"].append("removed existing quadlet %s for update" % removal_target)
702
703 # Install
704 cmd = self._build_install_cmd()
705 rc, out, err = self._run(cmd)
706 if rc != 0:
707 self.module.fail_json(
708 msg="Failed to install quadlet(s): %s" % err,
709 stdout=out,
710 stderr=err,
711 **self.results,
712 )
713
714 self.results["changed"] = True
715 self.results["actions"].append("installed quadlets from %s" % src)
716 self.results["quadlets"].append({"source": src, "path": self.quadlet_dir})
717 if self.module.params["debug"]:
718 self.results.update({"stdout": out, "stderr": err})
719
720 def _absent(self):
721 names = self.module.params.get("name") or []
722 resolved_names = []
723
724 # If not removing all, resolve names first for idempotency
725 if not self.module.params.get("all") and names:
726 installed = self._get_installed_quadlets()
727 for name in names:
728 if name in installed:
729 resolved_names.append(name)
730 else:
731 # Try with suffixes
732 for suffix in QUADLET_SUFFIXES:
733 if name + suffix in installed:
734 resolved_names.append(name + suffix)
735 break
736 # If not found, already absent - idempotent
737
738 if not resolved_names:
739 # All quadlets already absent
740 return
741
742 # Build and run rm command
743 if self.module.params.get("all"):
744 cmd = self._build_rm_cmd()
745 else:
746 cmd = self._build_rm_cmd(resolved_names)
747
748 rc, out, err = self._run(cmd)
749 if rc != 0:
750 # Treat "not found" errors as idempotent (race condition safe)
751 if "does not exist" in err.lower() or "no such" in err.lower():
752 return
753
754 if self.module.params.get("all"):
755 msg = "Failed to remove all quadlets: %s" % err
756 else:
757 msg = "Failed to remove quadlet(s) %s: %s" % (", ".join(resolved_names), err)
758 self.module.fail_json(msg=msg, stdout=out, stderr=err, **self.results)
759
760 self.results["changed"] = True
761
762 if self.module.params.get("all"):
763 self.results["actions"].append("removed all quadlets")
764 self.results["quadlets"].append({"name": "all", "path": self.quadlet_dir})
765 else:
766 self.results["actions"].append("removed %s" % ", ".join(resolved_names))
767 for name in resolved_names:
768 self.results["quadlets"].append({"name": name, "path": self.quadlet_dir})
769
770 if self.module.params["debug"]:
771 self.results.update({"stdout": out, "stderr": err})
772
773 def execute(self):
774 state = self.module.params["state"]
775 if state == "present":
776 self._install()
777 elif state == "absent":
778 self._absent()
779 self.module.exit_json(**self.results)
780
781
782 def main():
783 module = AnsibleModule(
784 argument_spec=dict(
785 state=dict(type="str", default="present", choices=["present", "absent"]),
786 name=dict(type="list", elements="str", required=False),
787 src=dict(type="str", required=False),
788 files=dict(type="list", elements="str", required=False),
789 quadlet_dir=dict(type="path", required=False),
790 reload_systemd=dict(type="bool", default=True),
791 force=dict(type="bool", default=True),
792 all=dict(type="bool", default=False),
793 executable=dict(type="str", default="podman"),
794 cmd_args=dict(type="list", elements="str", required=False),
795 debug=dict(type="bool", default=False),
796 ),
797 required_if=[
798 ("state", "present", ["src"]),
799 ],
800 mutually_exclusive=[
801 ["all", "name"],
802 ],
803 supports_check_mode=True,
804 )
805
806 # Custom validation for state=absent
807 if module.params["state"] == "absent":
808 if not module.params["name"] and not module.params["all"]:
809 module.fail_json(msg="For state='absent', either 'name' or 'all' must be specified.")
810
811 PodmanQuadletManager(module).execute()
812
813
814 if __name__ == "__main__":
815 main()