Skip to content

Instantly share code, notes, and snippets.

@UtahDave
Created February 25, 2013 05:20
Show Gist options
  • Save UtahDave/5027922 to your computer and use it in GitHub Desktop.
Save UtahDave/5027922 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*
"""
Client module to Salt-API REST server.
"""
__author__ = 'Bruno Clermont'
__email__ = '[email protected]'
__version__ = (0, 0, 1)
import logging
import requests
logger = logging.getLogger('salt_rest_client')
class Salt(object):
"""
Client that communicate with a Salt-API REST server.
Example:
.. code-block:: python
>> salt = Salt('myuser', 'mypass', 'https://salt.example.com')
>> salt.execute('test.ping', '*')
{u'return': [{u'X': True,
u'Y': True,
u'Z': True}]}
:param username: Unix user name
:type username: string
:param password: user password
:type password: string
:param root_url: URL of your salt-api server such as https://1.1.1.1
:type root_url: string
"""
def __init__(self, username, password, root_url):
self.username = username
self.password = password
self.root_url = root_url.rstrip('/')
self.token = self.get_auth_token()
def get_auth_token(self):
"""
Authenticate on the remote Salt-API server.
:return: auth token
:rtype: basestring or None if couldn't authenticate
"""
url = self.root_url + '/login'
req = requests.post(url,
data=dict(username=self.username,
password=self.password,
eauth='pam'),
allow_redirects=False)
if req.ok:
return req.headers['x-auth-token']
else:
logger.warning("failed to log with user: %s: %s", self.username,
req.content)
def minions(self, minion_id=None):
return self._get_request('minions', minion_id)
def jobs(self, job_id=None):
return self._get_request('jobs', job_id)
def _get_request(self, resource, resource_id=None):
if resource_id is not None:
url = '/%s/%s/' % (resource, resource_id)
else:
url = '/%s/' % resource
req = requests.get(self.root_url + url,
headers={'X-Auth-Token': self.token,
'Accept': 'application/json'})
return req.json()
def execute(self, function, target):
"""
Execute a salt function to specified targets.
:param function: Salt module and function, such as test.ping
:type function: string
:param target: target(s) of minions, such as '*'
:type target: string
:return: results or None if failed
:rtype: dict
"""
req = requests.post(self.root_url + '/',
data={'fun': function, 'tgt': target,
'client': 'local'},
headers={'X-Auth-Token': self.token,
'Accept': 'application/json'})
if req.ok:
return req.json()
else:
logger.error("Couldn't execute '%s' on '%s': %s", function,
target, req.content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment