-
Notifications
You must be signed in to change notification settings - Fork 1
/
inventory
executable file
·104 lines (86 loc) · 2.47 KB
/
inventory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/usr/bin/env python3
import argparse
import json
import subprocess
# TODO: read from setenv
UNGROUPED = "ungrouped"
NETWORK = "podlab"
LABEL = f"org.podlab"
DNS_SUFFIX = "dns.podman"
USE_POD_IP = False
def get_pods():
pr = subprocess.run(
[
"podman",
"ps",
"--format",
"{{.ID}}",
"--filter",
f"label={LABEL}.group",
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
)
if pr.returncode != 0:
raise RuntimeError(pr.stdout)
return pr.stdout.decode().splitlines()
def inspect_pod(pods):
if not pods:
return []
pr = subprocess.run(
["podman", "inspect", "--format", "json"] + pods
if isinstance(pods, list)
else [pods],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
)
if pr.returncode != 0:
raise RuntimeError(pr.stdout)
pods = json.loads(pr.stdout)
return pods
def get_list(pods):
# "Labels" "org.ansible-lab.group"
groups = {}
for p in pods:
g: str = p["Config"]["Labels"].get(
f"{LABEL}.group", UNGROUPED
) # .replace("-", "_")
if g not in groups:
groups[g] = {"hosts": [], "vars": {}, "children": []}
groups[g]["hosts"].append(
# p["NetworkSettings"]["Networks"].get(NETWORK, {}).get("IPAddress", None)
f'{p["Config"]["Hostname"]}'
)
return groups
def get_host(pod):
i = inspect_pod(pod)[0]
return json.dumps(
{
**(
{
"ansible_host": i["NetworkSettings"]["Networks"]
.get(NETWORK, {})
.get("IPAddress", None)
}
if USE_POD_IP
else {}
),
# f'{i["Config"]["Hostname"]}.{DNS_SUFFIX}',
**(lambda v: {"podlab_version": v} if v else {})(
i["Config"]["Labels"].get("org.podlab.version", None)
),
}
)
def main():
parser = argparse.ArgumentParser("Podman Inventory Module")
parser.add_argument("--list", action="store_true", help="List active pods")
parser.add_argument("--host", help="Details about a specific pod")
args = parser.parse_args()
if args.host:
print(get_host([args.host]))
if args.list:
print(json.dumps(get_list(inspect_pod(get_pods()))))
if __name__ == "__main__":
main()