Debian Codegraph @

ansible_collections/containers/podman/plugins/inventory/podman_containers.py

raw
1 # Copyright (c) 2025
2 # GNU General Public License v3.0+
3
4 from __future__ import annotations
5
6 __metaclass__ = type
7
8 DOCUMENTATION = r"""
9 name: podman_containers
10 short_description: Inventory plugin that discovers Podman containers as hosts
11 version_added: '1.18.0'
12 author:
13 - "Sagi Shnaidman (@sshnaidm)"
14 description:
15 - Discover running (and optionally stopped) Podman containers on the local host and add them as inventory hosts.
16 - Each discovered host is assigned an Ansible connection plugin so tasks execute inside the container without SSH.
17 options:
18 plugin:
19 description: Token that ensures this is a source file for the 'containers.podman.podman_containers' inventory plugin.
20 required: true
21 type: str
22 choices: ['containers.podman.podman_containers']
23 executable:
24 description: Path to the C(podman) executable.
25 type: str
26 default: podman
27 env:
28 - name: ANSIBLE_PODMAN_EXECUTABLE
29 include_stopped:
30 description: Whether to include stopped/exited containers.
31 type: bool
32 default: false
33 name_patterns:
34 description: Glob patterns to match container names or IDs; empty means include all.
35 type: list
36 elements: str
37 default: []
38 label_selectors:
39 description: Key/value labels that must match (all) for a container to be included.
40 type: dict
41 default: {}
42 connection_plugin:
43 description: Fully-qualified connection plugin to use for discovered hosts.
44 type: str
45 default: containers.podman.podman
46 group_by_image:
47 description: Add containers to a group derived from image name (e.g., C(image_node_14)).
48 type: bool
49 default: true
50 group_by_label:
51 description: Label keys to group containers by (C(label_<key>_<value>)).
52 type: list
53 elements: str
54 default: []
55 # Additional options (non-API dependent), aligned with community.docker
56 verbose_output:
57 description: When true, store raw C(podman ps --format json) entry under C(podman_ps) host var.
58 type: bool
59 default: false
60 strict:
61 description: Fail when keyed/composed grouping references missing data.
62 type: bool
63 default: false
64 keyed_groups:
65 description: Create groups based on hostvars/labels.
66 type: list
67 elements: dict
68 default: []
69 groups:
70 description: Add hosts to groups based on Jinja2 conditionals.
71 type: dict
72 default: {}
73 filters:
74 description: Include/exclude selection by attributes - C(name), C(id), C(image), C(status), or C(label.<key>).
75 type: dict
76 default: {}
77 # Logging uses Ansible verbosity (-v/-vvv). Extra debug option is not required.
78 """
79
80 EXAMPLES = r"""
81 plugin: containers.podman.podman_containers
82 include_stopped: false
83 label_selectors:
84 role: api
85 connection_plugin: containers.podman.podman
86 """
87
88 import json
89 import fnmatch
90 import shutil
91 import subprocess
92
93 from ansible.errors import AnsibleParserError
94 from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable, Constructable
95 from ansible_collections.containers.podman.plugins.module_utils.inventory.utils import verify_inventory_file
96
97
98 class InventoryModule(BaseInventoryPlugin, Cacheable, Constructable):
99 NAME = "containers.podman.podman_containers"
100
101 def __init__(self):
102 super(InventoryModule, self).__init__()
103
104 def verify_file(self, path: str) -> bool:
105 if not super(InventoryModule, self).verify_file(path):
106 return False
107 return verify_inventory_file(self, path)
108
109 def parse(self, inventory, loader, path, cache=True):
110 super(InventoryModule, self).parse(inventory, loader, path)
111 config = self._read_config_data(path)
112
113 executable = config.get("executable", "podman")
114 include_stopped = bool(config.get("include_stopped", False))
115 name_patterns = list(config.get("name_patterns", []) or [])
116 label_selectors = dict(config.get("label_selectors", {}) or {})
117 connection_plugin = config.get("connection_plugin", "containers.podman.podman")
118 group_by_image = bool(config.get("group_by_image", True))
119 group_by_label = list(config.get("group_by_label", []) or [])
120 verbose_output = bool(config.get("verbose_output", False))
121 strict = bool(config.get("strict", False))
122 keyed_groups = list(config.get("keyed_groups", []) or [])
123 composed_groups = dict(config.get("groups", {}) or {})
124 filters = dict(config.get("filters", {}) or {})
125 # Logging is controlled by Ansible verbosity flags
126
127 podman_path = shutil.which(executable) or executable
128
129 args = [podman_path, "ps", "--format", "json"]
130 if include_stopped:
131 args.insert(2, "-a")
132
133 output = ""
134 containers = []
135 try:
136 output = subprocess.check_output(args, stderr=subprocess.STDOUT)
137 containers = json.loads(output.decode("utf-8"))
138 except Exception as exc:
139 raise AnsibleParserError(f"Failed to list podman containers: {exc} from output {output}")
140
141 def matches_filters(name, cid, image, status, labels):
142 include_rules = dict(filters.get("include", {}) or {})
143 exclude_rules = dict(filters.get("exclude", {}) or {})
144
145 def matches_one(k, v):
146 if k.startswith("label."):
147 lk = k.split(".", 1)[1]
148 return fnmatch.fnmatch(str((labels or {}).get(lk, "")).lower(), str(v).lower())
149 if k == "name":
150 return fnmatch.fnmatch((name or "").lower(), str(v).lower())
151 if k == "id":
152 return fnmatch.fnmatch((cid or "").lower(), str(v).lower())
153 if k == "image":
154 return fnmatch.fnmatch((image or "").lower(), str(v).lower())
155 if k == "status":
156 return fnmatch.fnmatch((status or "").lower(), str(v).lower())
157 return False
158
159 if include_rules:
160 for k, v in include_rules.items():
161 if not matches_one(k, v):
162 return False
163 for k, v in exclude_rules.items():
164 if matches_one(k, v):
165 return False
166 return True
167
168 for c in containers:
169 name = (
170 (c.get("Names") or [c.get("Names", "")])[0]
171 if isinstance(c.get("Names"), list)
172 else c.get("Names") or c.get("Names", "")
173 )
174 cid = c.get("Id") or c.get("ID")
175 if not name and cid:
176 name = cid[:12]
177
178 # name filtering
179 if name_patterns:
180 if not any(fnmatch.fnmatch(name, pat) or (cid and fnmatch.fnmatch(cid, pat)) for pat in name_patterns):
181 self.display.vvvv(f"Filtered out {name or cid} by name_patterns option")
182 continue
183
184 # label filtering
185 labels = c.get("Labels") or {}
186 if any(labels.get(k) != v for k, v in label_selectors.items()):
187 self.display.vvvv(f"Filtered out {name or cid} by label_selectors option")
188 continue
189
190 image = c.get("Image") or c.get("ImageName")
191 status = c.get("Status") or c.get("State")
192
193 # additional include/exclude filters
194 if filters and not matches_filters(name, cid, image, status, labels):
195 self.display.vvvv(f"Filtered out {name or cid} by filters option")
196 continue
197
198 host = name or cid
199 if not host:
200 self.display.vvvv(f"Filtered out {name or cid} by no name or cid")
201 continue
202
203 self.inventory.add_host(host)
204 # Set connection plugin and remote_addr (container id or name works)
205 self.inventory.set_variable(host, "ansible_connection", connection_plugin)
206 self.inventory.set_variable(host, "ansible_host", name or cid)
207
208 # Common vars
209 self.inventory.set_variable(host, "podman_container_id", cid)
210 self.inventory.set_variable(host, "podman_container_name", name)
211 if image:
212 self.inventory.set_variable(host, "podman_image", image)
213 if status:
214 self.inventory.set_variable(host, "podman_status", status)
215 if labels:
216 self.inventory.set_variable(host, "podman_labels", labels)
217 if verbose_output:
218 self.inventory.set_variable(host, "podman_ps", c)
219
220 # Grouping
221 if group_by_image and image:
222 safe_image = image.replace(":", "_").replace("/", "_").replace("-", "_")
223 self.inventory.add_group(f"image_{safe_image}")
224 self.inventory.add_host(host, group=f"image_{safe_image}")
225
226 for key in group_by_label:
227 if key in labels:
228 val = str(labels.get(key)).replace("/", "_").replace(":", "_").replace("-", "_")
229 group = f"label_{key}_{val}"
230 self.inventory.add_group(group)
231 self.inventory.add_host(host, group=group)
232
233 # Composed and keyed groups
234 hostvars = {
235 "name": name,
236 "id": cid,
237 "image": image,
238 "status": status,
239 "labels": labels,
240 }
241 try:
242 if composed_groups:
243 self._add_host_to_composed_groups(composed_groups, hostvars, host)
244 if keyed_groups:
245 # Try built-in helper first (signature may vary by ansible-core), do not fail hard
246 try:
247 self._add_host_to_keyed_groups(keyed_groups, hostvars, host)
248 except Exception as _e:
249 self.display.vvvv(f"_add_host_to_keyed_groups helper failed: {_e}")
250 # Always run manual keyed grouping to support dotted keys like labels.role
251 for kg in keyed_groups:
252 key_expr = kg.get("key")
253 if not key_expr:
254 continue
255 # Resolve dotted key path against hostvars
256 value = None
257 cur = hostvars
258 for part in str(key_expr).split("."):
259 if isinstance(cur, dict) and part in cur:
260 cur = cur.get(part)
261 else:
262 cur = None
263 break
264 value = cur if isinstance(cur, (str, int)) else (cur if cur is not None else None)
265 if value is None:
266 if strict and kg.get("default_value") is None:
267 raise AnsibleParserError(f"Missing keyed_groups key '{key_expr}' for host {host}")
268 value = kg.get("default_value")
269 if value is None or value == "":
270 continue
271 value = str(value)
272 prefix = kg.get("prefix", "") or ""
273 sep = kg.get("separator", "_") or "_"
274 leading = bool(kg.get("leading_separator", False))
275 trailing = bool(kg.get("trailing_separator", False))
276 group_name = ""
277 if leading and not prefix:
278 group_name += sep
279 if prefix:
280 group_name += prefix
281 if value:
282 group_name += sep
283 group_name += value
284 if trailing:
285 group_name += sep
286 parent = kg.get("parent_group")
287 # Sanitize group names per Ansible rules
288 sanitized = self._sanitize_group_name(group_name)
289 parent_sanitized = self._sanitize_group_name(parent) if parent else None
290 if parent_sanitized:
291 self.inventory.add_group(parent_sanitized)
292 self.inventory.add_group(sanitized)
293 try:
294 self.inventory.add_child(parent_sanitized, sanitized)
295 except Exception:
296 pass
297 self.inventory.add_host(host, group=sanitized)
298 else:
299 self.inventory.add_group(sanitized)
300 self.inventory.add_host(host, group=sanitized)
301 except Exception as exc:
302 if strict:
303 raise
304 self.display.vvvv(f"Grouping error for host {host}: {exc}")