Created
August 8, 2025 14:15
-
-
Save wtnb75/4233423ed62844bf9722d2e4df5b891d to your computer and use it in GitHub Desktop.
UTM to ansible dynamic inventory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python | |
import re | |
import json | |
import subprocess | |
def runcmd(cmd: list[str]): | |
return subprocess.run(["utmctl", *cmd], capture_output=True, encoding="utf-8") | |
nodes = {} | |
for i in runcmd(["list"]).stdout.splitlines(): | |
if i.startswith("UUID"): | |
continue | |
sp = i.split(maxsplit=2) | |
if len(sp) == 3: | |
nodes[sp[2]] = {} | |
for node in nodes.keys(): | |
ipaddr = runcmd(["ip-address", node]).stdout.splitlines() | |
if len(ipaddr) != 0: | |
nodes[node]["ansible_host"] = ipaddr[0] | |
groups = set() | |
singles = set() | |
for node in nodes.keys(): | |
m = re.match("^([a-z]*)", node) | |
if m: | |
if m.group(1) != node: | |
groups.add(m.group(1)) | |
else: | |
singles.add(node) | |
res = { | |
"utm": { | |
"children": list(groups), | |
"hosts": list(singles), | |
}, | |
"_meta": { | |
"hostvars": nodes, | |
}, | |
} | |
for g in groups: | |
res[g] = { | |
"hosts": [x for x in nodes.keys() if x.startswith(g)], | |
} | |
print(json.dumps(res)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment