Debian Codegraph @

ansible_collections/containers/podman/plugins/inventory/buildah_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: buildah_containers
10 short_description: Inventory plugin that discovers Buildah working containers as hosts
11 version_added: '1.18.0'
12 author:
13 - "Sagi Shnaidman (@sshnaidm)"
14 description:
15 - Discover Buildah working containers on the local host and add them as inventory hosts.
16 - Each discovered host is assigned the Buildah connection plugin so tasks execute inside the working container.
17 options:
18 plugin:
19 description: Token that ensures this is a source file for the 'containers.podman.buildah_containers' inventory plugin.
20 required: true
21 type: str
22 choices: ['containers.podman.buildah_containers']
23 executable:
24 description: Path to the C(buildah) executable.
25 type: str
26 default: buildah
27 env:
28 - name: ANSIBLE_BUILDAH_EXECUTABLE
29 name_patterns:
30 description: Glob patterns to match working container names or IDs; empty means include all.
31 type: list
32 elements: str
33 default: []
34 connection_plugin:
35 description: Fully-qualified connection plugin to use for discovered hosts.
36 type: str
37 default: containers.podman.buildah
38 # Logging uses Ansible verbosity (-v/-vvv). Extra debug option is not required.
39 """
40
41 EXAMPLES = r"""
42 plugin: containers.podman.buildah_containers
43 connection_plugin: containers.podman.buildah
44 name_patterns:
45 - my-build-*
46 """
47
48 import json
49 import fnmatch
50 import shutil
51 import subprocess
52
53 from ansible.errors import AnsibleParserError
54 from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable, Constructable
55 from ansible_collections.containers.podman.plugins.module_utils.inventory.utils import verify_inventory_file
56
57
58 class InventoryModule(BaseInventoryPlugin, Cacheable, Constructable):
59 NAME = "containers.podman.buildah_containers"
60
61 def verify_file(self, path: str) -> bool:
62 if not super(InventoryModule, self).verify_file(path):
63 return False
64 return verify_inventory_file(self, path)
65
66 def parse(self, inventory, loader, path, cache=True):
67 super(InventoryModule, self).parse(inventory, loader, path)
68 config = self._read_config_data(path)
69
70 executable = config.get("executable", "buildah")
71 name_patterns = list(config.get("name_patterns", []) or [])
72 connection_plugin = config.get("connection_plugin", "containers.podman.buildah")
73 # Logging is controlled by Ansible verbosity flags
74
75 buildah_path = shutil.which(executable) or executable
76
77 # 'buildah containers -a --format json' lists working containers
78 args = [buildah_path, "containers", "-a", "--json"]
79 output = ""
80 containers = []
81 try:
82 output = subprocess.check_output(args, stderr=subprocess.STDOUT)
83 containers = json.loads(output.decode("utf-8"))
84 except Exception as exc:
85 raise AnsibleParserError(f"Failed to list buildah containers: {exc} from output {output}")
86
87 for c in containers:
88 name = c.get("name") or c.get("containername") or c.get("id")
89 cid = c.get("id") or c.get("containerid")
90 if not name and cid:
91 name = cid[:12]
92
93 # name filtering
94 if name_patterns:
95 if not any(fnmatch.fnmatch(name, pat) or (cid and fnmatch.fnmatch(cid, pat)) for pat in name_patterns):
96 self.display.vvvv(f"Filtered out {name or cid} by name_patterns option")
97 continue
98
99 host = name or cid
100 if not host:
101 self.display.vvvv(f"Filtered out {name or cid} by no name or cid")
102 continue
103
104 self.inventory.add_host(host)
105 self.inventory.set_variable(host, "ansible_connection", connection_plugin)
106 self.inventory.set_variable(host, "ansible_host", name or cid)
107 if cid:
108 self.inventory.set_variable(host, "buildah_container_id", cid)
109 if name:
110 self.inventory.set_variable(host, "buildah_container_name", name)