MAAS HTTP API with Python Requests
Brendan Donegan (Canonical/MAAS)
Brief introduction to MAAS
Python/Requests
Initial setup
$ virtualenv --python=python3 maashttp
$ . maashttp/bin/activate
$ pip install requests
$ pip install requests-oauthlib
API Key
Setting up
>>> import requests
>>> from requests_oauthlib import OAuth1
>>> MAAS_API = “http://192.168.122.230/MAAS/api/2.0/”
>>> consumer_key, key, secret = “<api key>”.split(“:”)
>>> oauth = OAuth1(consumer_key, resource_owner_key=key, resource_owner_secret=secret, signature_method=”PLAINTEXT”)
>>> APP_JSON_HEADER = {“Accept”: “application/json”}
API documentation
https://maas.ubuntu.com/docs2.1/api.html
Reading objects
>>> response = requests.get(MAAS_API + “/machines/”, auth=oauth, headers=APP_JSON_HEADER)
>>> response.ok
>>> pprint(response.json())
>>> response.status_code
>>> response.text
>>> system_id = response.json()[0][‘system_id’]
Reading specific objects
>>> response = requests.get(MAAS_API + “/machines/{system_id}/”.format(system_id=system_id), auth=oauth, headers=APP_JSON_HEADER)
>>> pprint(response.json())
Creating objects
>>> data = {‘architecture’: ‘amd64/generic’, ‘mac_addresses’: ‘00:00:00:ff:ff:ff’, ‘power_type’: ‘virsh’}
>>> response = requests.post(MAAS_API + “/machines/”, data=data, auth=oauth, headers=APP_JSON_HEADER)
>>> response.json()
…. <JSON representation of the created machine>
Performing operations
>>> response = requests.post(“/api/2.0/machines/?op=set_zone”, auth=oauth, headers=APP_JSON_HEADER)
>>>
Updating object
>>> data = {‘hostname’: ‘foo’}
>>> response = requests.put(MAAS_API + ‘/machines/{system_id}/’.format(system_id=system_id), auth=oauth, headers=APP_JSON_HEADER)
>>> response.json()
…
<updated section>
...
Deleting objects
>>> response = requests.delete(MAAS_API + “/machines/{system_id}/”.format(system_id=system_id))
>>> requests.ok
Questions?