Skip to content

Instantly share code, notes, and snippets.

@mikemccracken
Last active August 29, 2015 14:04
Show Gist options
  • Save mikemccracken/e9f645112fae6194ce2b to your computer and use it in GitHub Desktop.
Save mikemccracken/e9f645112fae6194ce2b to your computer and use it in GitHub Desktop.
Quick script to discover virsh nodes named 'maas-node-*' and slurp them into maas.
#!/usr/bin/python
from __future__ import unicode_literals
import getpass
import libvirt
import urllib2
import gzip
import json
import StringIO
from xml.dom.minidom import parseString
from apiclient.maas_client import (
MAASClient,
MAASDispatcher,
MAASOAuth,
)
def get_client(url, creds):
[consumer_key, token, secret] = creds.split(':')
auth = MAASOAuth(consumer_key=consumer_key, resource_token=token,
resource_secret=secret)
return MAASClient(auth, MAASDispatcher(), url)
creds = getpass.getpass('MAAS key:')
client = get_client('http://localhost/MAAS/api/1.0/', creds)
user = raw_input("username")
hhost = 'qemu+ssh://{}@192.168.100.1/system'.format(user)
conn = libvirt.open(hhost)
domains = conn.listAllDomains()
def add_maas_node(name, mac):
nd = {'architecture': 'amd64',
'mac_addresses': [mac],
'hostname': name,
'power_type': 'virsh',
'power_parameters_power_address': hhost,
'power_parameters_power_id': name,
'nodegroup': ''}
try:
resp = client.post('nodes/', 'new', **nd).read()
print(resp)
system_id = json.loads(resp)['system_id']
print(system_id)
except urllib2.HTTPError as e:
try:
if 'gzip' in e.headers['Content-Encoding']:
print(gzip.GzipFile(fileobj=StringIO.StringIO(e.read()), mode='rb').read())
except KeyError:
print(e.read())
for node in domains:
node_name = node.name()
if "maas-node-" not in node_name:
print("skipping {}".format(node_name))
continue
node_xml = parseString(node.XMLDesc(0))
node_mac1 = node_xml.getElementsByTagName('interface')[0].getElementsByTagName('mac')[0].getAttribute('address')
add_maas_node(node_name, node_mac1)
print("added {}".format(node_name))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment