Skip to content

Instantly share code, notes, and snippets.

@alex-leonhardt
Created January 12, 2020 15:01
Show Gist options
  • Save alex-leonhardt/7ffa8cce418278c092b174c32ef71da3 to your computer and use it in GitHub Desktop.
Save alex-leonhardt/7ffa8cce418278c092b174c32ef71da3 to your computer and use it in GitHub Desktop.
libvirt kvm ansible dynamic inventory script
#! /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