Debian Codegraph @

ansible_collections/containers/podman/plugins/modules/podman_quadlet_info.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_info
13 author:
14 - "Sagi Shnaidman (@sshnaidm)"
15 short_description: Gather information about Podman Quadlets
16 description:
17 - List installed Podman Quadlets or print one quadlet content using C(podman quadlet list/print).
18 - Gather information about Podman Quadlets available on the system.
19 options:
20 name:
21 description:
22 - Name of the quadlet to print content for.
23 - When specified, runs C(podman quadlet print) instead of list.
24 type: str
25 required: false
26 kinds:
27 description:
28 - List of quadlet kinds to filter by (based on file suffix).
29 - For example, C(container) matches quadlets ending with C(.container).
30 type: list
31 elements: str
32 choices:
33 - container
34 - pod
35 - network
36 - volume
37 - kube
38 - image
39 required: false
40 quadlet_dir:
41 description:
42 - Filter results to quadlets whose path is under this directory.
43 - By default no filtering is applied.
44 type: path
45 required: false
46 executable:
47 description:
48 - Path to the podman executable.
49 type: str
50 default: podman
51 cmd_args:
52 description:
53 - Extra global arguments to pass to the C(podman) command (e.g., C(--log-level=debug)).
54 - These are placed after the executable and before the subcommand.
55 type: list
56 elements: str
57 required: false
58 debug:
59 description:
60 - Return additional debug information.
61 type: bool
62 default: false
63 """
64
65 EXAMPLES = r"""
66 - name: List all quadlets
67 containers.podman.podman_quadlet_info:
68
69 - name: Get information about a specific quadlet
70 containers.podman.podman_quadlet_info:
71 name: myapp.container
72
73 - name: List only container quadlets
74 containers.podman.podman_quadlet_info:
75 kinds:
76 - container
77
78 - name: List quadlets in a custom directory
79 containers.podman.podman_quadlet_info:
80 quadlet_dir: /etc/containers/systemd
81 """
82
83
84 RETURN = r"""
85 changed:
86 description: Always false
87 returned: always
88 type: bool
89 quadlets:
90 description: List of installed quadlets when listing
91 returned: when name is not provided
92 type: list
93 content:
94 description: Content of the quadlet when name is provided
95 returned: when name is provided
96 type: str
97 stdout:
98 description: podman stdout
99 returned: when debug=true
100 type: str
101 stderr:
102 description: podman stderr
103 returned: when debug=true
104 type: str
105 """
106
107
108 import json
109 import os
110
111 from ansible.module_utils.basic import AnsibleModule # noqa: F402
112
113 try:
114 from ansible.module_utils.common.text.converters import to_native # noqa: F402
115 except ImportError:
116 from ansible.module_utils.common.text import to_native # noqa: F402
117
118
119 # Mapping from kind name to file suffix
120 KIND_SUFFIXES = {
121 "container": ".container",
122 "pod": ".pod",
123 "network": ".network",
124 "volume": ".volume",
125 "kube": ".kube",
126 "image": ".image",
127 }
128
129
130 def _get_quadlet_kind(name):
131 """Extract kind from quadlet name based on suffix."""
132 if not name:
133 return None
134 for kind, suffix in KIND_SUFFIXES.items():
135 if name.endswith(suffix):
136 return kind
137 return None
138
139
140 def _build_base_cmd(module, executable):
141 """Build base command with executable and global args."""
142 cmd = [executable]
143 if module.params.get("cmd_args"):
144 cmd.extend(module.params["cmd_args"])
145 return cmd
146
147
148 def _list_quadlets(module, executable):
149 """List installed quadlets with optional filtering."""
150 cmd = _build_base_cmd(module, executable)
151 cmd.extend(["quadlet", "list", "--format", "json"])
152
153 module.log("PODMAN-QUADLET-INFO-DEBUG: %s" % " ".join([to_native(i) for i in cmd]))
154 rc, out, err = module.run_command(cmd)
155
156 if rc != 0:
157 module.fail_json(msg="Failed to list quadlets: %s" % err, stdout=out, stderr=err)
158
159 # Strict JSON parsing - fail on errors instead of returning empty
160 try:
161 data = json.loads(out) if out.strip() else []
162 except json.JSONDecodeError as e:
163 module.fail_json(
164 msg="Failed to parse quadlet list output: %s" % str(e),
165 stdout=out,
166 stderr=err,
167 )
168
169 # Filter by kinds (based on file suffix in Name)
170 kinds = module.params.get("kinds")
171 if kinds:
172 kinds_set = set(kinds)
173 filtered = []
174 for q in data:
175 name = q.get("Name", "")
176 kind = _get_quadlet_kind(name)
177 if kind and kind in kinds_set:
178 filtered.append(q)
179 data = filtered
180
181 # Filter by quadlet_dir (based on Path)
182 quadlet_dir = module.params.get("quadlet_dir")
183 if quadlet_dir:
184 # Normalize the directory path
185 quadlet_dir = os.path.normpath(quadlet_dir)
186 filtered = []
187 for q in data:
188 path = q.get("Path", "")
189 if path:
190 # Check if the quadlet's path is under the specified directory
191 normalized_path = os.path.normpath(path)
192 if normalized_path.startswith(quadlet_dir + os.sep) or os.path.dirname(normalized_path) == quadlet_dir:
193 filtered.append(q)
194 data = filtered
195
196 result = {
197 "changed": False,
198 "quadlets": data,
199 }
200 if module.params["debug"]:
201 result.update({"stdout": out, "stderr": err})
202 return result
203
204
205 def _print_quadlet(module, executable):
206 """Print content of a specific quadlet."""
207 name = module.params["name"]
208 cmd = _build_base_cmd(module, executable)
209 cmd.extend(["quadlet", "print", name])
210
211 module.log("PODMAN-QUADLET-INFO-DEBUG: %s" % " ".join([to_native(i) for i in cmd]))
212 rc, out, err = module.run_command(cmd)
213
214 if rc != 0:
215 module.fail_json(msg="Failed to print quadlet %s: %s" % (name, err), stdout=out, stderr=err)
216
217 result = {
218 "changed": False,
219 "content": out,
220 }
221 if module.params["debug"]:
222 result.update({"stdout": out, "stderr": err})
223 return result
224
225
226 def main():
227 module = AnsibleModule(
228 argument_spec=dict(
229 name=dict(type="str", required=False),
230 quadlet_dir=dict(type="path", required=False),
231 kinds=dict(
232 type="list",
233 elements="str",
234 required=False,
235 choices=["container", "pod", "network", "volume", "kube", "image"],
236 ),
237 executable=dict(type="str", default="podman"),
238 cmd_args=dict(type="list", elements="str", required=False),
239 debug=dict(type="bool", default=False),
240 ),
241 supports_check_mode=True,
242 )
243
244 executable = module.get_bin_path(module.params["executable"], required=True)
245
246 if module.params.get("name"):
247 result = _print_quadlet(module, executable)
248 else:
249 result = _list_quadlets(module, executable)
250
251 module.exit_json(**result)
252
253
254 if __name__ == "__main__":
255 main()