Created
January 12, 2020 15:01
-
-
Save alex-leonhardt/7ffa8cce418278c092b174c32ef71da3 to your computer and use it in GitHub Desktop.
libvirt kvm ansible dynamic inventory script
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/python | |
import re | |
import sys | |
import subprocess as sub | |
import json | |
res = sub.Popen(["virsh", "net-dhcp-leases", "default"], stdout=sub.PIPE) | |
output, err = res.communicate() | |
# todo: make the regex work for hosts that don't start with node | |
nodes = [] | |
for l in output.splitlines(): | |
r = re.match(r"^.* (\d+.\d+.\d+.\d+)/\d+.*(node\w+)\s+01:.*$", l) | |
if r: | |
nodes.append(r.group(1)) | |
result = { | |
"all": { | |
"hosts": nodes | |
} | |
} | |
if len(sys.argv) == 2 and sys.argv[1] == '--list': | |
print(json.dumps(result)) | |
elif len(sys.argv) == 3 and sys.argv[1] == '--host': | |
result = { | |
"ansible_ssh_user": "root", | |
"ansible_connection": "ssh" | |
# .. empty | |
} | |
print(json.dumps(result)) | |
else: | |
sys.stderr.write("Need an argument, either --list or --host <host>\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment