Python client API

There are several ways to access Salt programatically.

Calling Salt from shell scripts

Salt CLI tools can, of course, be called from shell scripts. Reference the help output to see what structured output formats are supported. For example:

salt '*' disk.usage --out=json

Calling Salt via a REST API

Salt provides a REST API, currently as a separate sister-project. It will be merged into Salt core.

https://github.com/saltstack/salt-api

This API utilizes Salt's Python interface documented below. It is also useful as a reference implementation.

Calling Salt from a Python application

Salt provides several entry points for interfacing with Python applications. These entry points are often referred to as *Client() APIs.

opts

Some clients require access to Salt's opts dictionary. (The dictionary representation of the master or minion config files.)

A common pattern for fetching the opts dictionary is to defer to environment variables if they exist or otherwise fetch the config from the default location.

import salt.config

master_opts = salt.config.master_config(
    os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))

minion_opts = salt.config.client_config(
    os.environ.get('SALT_MINION_CONFIG', '/etc/salt/minion'))

Salt's Python interface

LocalClient

class salt.client.LocalClient(c_path='/etc/salt/master', mopts=None)

The interface used by the salt CLI tool on the Salt Master

LocalClient is used to send a command to Salt minions to execute execution modules and return the results to the Salt Master.

Importing and using LocalClient must be done on the same machine as the Salt Master and it must be done using the same user that the Salt Master is running as. (Unless external_auth is configured and authentication credentials are included in the execution).

import salt.client

local = salt.client.LocalClient()
local.cmd('*', 'test.fib', [10])
cmd(tgt, fun, arg=(), timeout=None, expr_form='glob', ret='', kwarg=None, **kwargs)

Synchronously execute a command on targeted minions

The cmd method will execute and wait for the timeout period for all minions to reply, then it will return all minion data at once.

>>> import salt.client
>>> local = salt.client.LocalClient()
>>> local.cmd('*', 'cmd.run', ['whoami'])
{'jerry': 'root'}

With extra keyword arguments for the command function to be run:

local.cmd('*', 'test.arg', ['arg1', 'arg2'], kwarg={'foo': 'bar'})

Compound commands can be used for multiple executions in a single publish. Function names and function arguments are provided in separate lists but the index values must correlate and an empty list must be used if no arguments are required.

>>> local.cmd('*', [
        'grains.items',
        'sys.doc',
        'cmd.run',
    ],
    [
        [],
        [],
        ['uptime'],
    ])
Parameters:
  • tgt (string or list) -- Which minions to target for the execution. Default is shell glob. Modified by the expr_form option.
  • fun (string or list of strings) --

    The module and function to call on the specified minions of the form module.function. For example test.ping or grains.items.

    Compound commands
    Multiple functions may be called in a single publish by passing a list of commands. This can dramatically lower overhead and speed up the application communicating with Salt.

    This requires that the arg param is a list of lists. The fun list and the arg list must correlate by index meaning a function that does not take arguments must still have a corresponding empty list at the expected index.

  • arg (list or list-of-lists) -- A list of arguments to pass to the remote function. If the function takes no arguments arg may be omitted except when executing a compound command.
  • timeout -- Seconds to wait after the last minion returns but before all minions return.
  • expr_form --

    The type of tgt. Allowed values:

    • glob - Bash glob completion - Default
    • pcre - Perl style regular expression
    • list - Python list of hosts
    • grain - Match based on a grain comparison
    • grain_pcre - Grain comparison with a regex
    • pillar - Pillar data comparison
    • nodegroup - Match on nodegroup
    • range - Use a Range server for matching
    • compound - Pass a compound match string
  • ret -- The returner to use. The value passed can be single returner, or a comma delimited list of returners to call in order on the minions
  • kwarg -- A dictionary with keyword arguments for the function.
  • kwargs --

    Optional keyword arguments.

    Authentication credentials may be passed when using external_auth.

    • eauth - the external_auth backend
    • username and password
    • token
    >>> local.cmd('*', 'test.ping',
            username='saltdev', password='saltdev', eauth='pam')
    
Returns:

A dictionary with the result of the execution, keyed by minion ID. A compound command will return a sub-dictionary keyed by function name.

run_job(tgt, fun, arg=(), expr_form='glob', ret='', timeout=None, kwarg=None, **kwargs)

Asynchronously send a command to connected minions

Prep the job directory and publish a command to any targeted minions.

Returns:A dictionary of (validated) pub_data or an empty dictionary on failure. The pub_data contains the job ID and a list of all minions that are expected to return data.
>>> local.run_job('*', 'test.sleep', [300])
{'jid': '20131219215650131543', 'minions': ['jerry']}
cmd_async(tgt, fun, arg=(), expr_form='glob', ret='', kwarg=None, **kwargs)

Asynchronously send a command to connected minions

The function signature is the same as cmd() with the following exceptions.

Returns:A job ID or 0 on failure.
>>> local.cmd_async('*', 'test.sleep', [300])
'20131219215921857715'
cmd_subset(tgt, fun, arg=(), expr_form='glob', ret='', kwarg=None, sub=3, cli=False, **kwargs)

Execute a command on a random subset of the targeted systems

The function signature is the same as cmd() with the following exceptions.

Parameters:sub -- The number of systems to execute on
>>> SLC.cmd_subset('*', 'test.ping', sub=1)
{'jerry': True}
cmd_iter(tgt, fun, arg=(), timeout=None, expr_form='glob', ret='', kwarg=None, **kwargs)

Yields the individual minion returns as they come in

The function signature is the same as cmd() with the following exceptions.

Returns:A generator
>>> ret = local.cmd_iter('*', 'test.ping')
>>> for i in ret:
...     print i
{'jerry': {'ret': True}}
{'dave': {'ret': True}}
{'stewart': {'ret': True}}
cmd_iter_no_block(tgt, fun, arg=(), timeout=None, expr_form='glob', ret='', kwarg=None, **kwargs)

Blocks while waiting for individual minions to return.

The function signature is the same as cmd() with the following exceptions.

Returns:None until the next minion returns. This allows for actions to be injected in between minion returns.
>>> ret = local.cmd_iter('*', 'test.ping')
>>> for i in ret:
...     print i
None
{'jerry': {'ret': True}}
{'dave': {'ret': True}}
None
{'stewart': {'ret': True}}
get_cli_returns(jid, minions, timeout=None, tgt='*', tgt_type='glob', verbose=False, **kwargs)

Starts a watcher looking at the return data for a specified JID

Returns:all of the information for the JID
get_event_iter_returns(jid, minions, timeout=None)

Gather the return data from the event system, break hard when timeout is reached.

Salt Caller

class salt.client.Caller(c_path='/etc/salt/minion')

Caller is the same interface used by the salt-call command-line tool on the Salt Minion.

Importing and using Caller must be done on the same machine as a Salt Minion and it must be done using the same user that the Salt Minion is running as.

Usage:

import salt.client
caller = salt.client.Caller()
caller.function('test.ping')

# Or call objects directly
caller.sminion.functions['cmd.run']('ls -l')
function(fun, *args, **kwargs)

Call a single salt function

RunnerClient

class salt.runner.RunnerClient(opts)

The interface used by the salt-run CLI tool on the Salt Master

It executes runner modules which run on the Salt Master.

Importing and using RunnerClient must be done on the same machine as the Salt Master and it must be done using the same user that the Salt Master is running as.

Salt's external_auth can be used to authenticate calls. The eauth user must be authorized to execute runner modules: (@runner). Only the master_call() below supports eauth.

async(fun, low, user='UNKNOWN')

Execute the runner in a multiprocess and return the event tag to use to watch for the return

cmd(fun, arg, kwarg=None)

Execute a runner function

>>> opts = salt.config.master_config('/etc/salt/master')
>>> runner = salt.runner.RunnerClient(opts)
>>> runner.cmd('jobs.list_jobs', [])
{
    '20131219215650131543': {
        'Arguments': [300],
        'Function': 'test.sleep',
        'StartTime': '2013, Dec 19 21:56:50.131543',
        'Target': '*',
        'Target-type': 'glob',
        'User': 'saltdev'
    },
    '20131219215921857715': {
        'Arguments': [300],
        'Function': 'test.sleep',
        'StartTime': '2013, Dec 19 21:59:21.857715',
        'Target': '*',
        'Target-type': 'glob',
        'User': 'saltdev'
    },
}
get_docs()

Return a dictionary of functions and the inline documentation for each

low(fun, low)

Pass in the runner function name and the low data structure

runner.low({'fun': 'jobs.lookup_jid', 'jid': '20131219215921857715'})
master_call(**kwargs)

Execute a runner function through the master network interface (eauth).

This function requires that external_auth is configured and the user is authorized to execute runner functions: (@runner).

runner.master_call({
    'fun': 'jobs.list_jobs',
    'username': 'saltdev',
    'password': 'saltdev',
    'eauth': 'pam',
})

WheelClient

class salt.wheel.WheelClient(opts=None)

An interface to Salt's wheel modules

Wheel modules interact with various parts of the Salt Master.

Importing and using WheelClient must be done on the same machine as the Salt Master and it must be done using the same user that the Salt Master is running as. Unless external_auth is configured and the user is authorized to execute wheel functions: (@wheel).

call_func(fun, **kwargs)

Execute a wheel function

>>> opts = salt.config.master_config('/etc/salt/master')
>>> wheel = salt.wheel.Wheel(opts)
>>> wheel.call_func('key.list_all')
{'local': ['master.pem', 'master.pub'],
'minions': ['jerry'],
'minions_pre': [],
'minions_rejected': []}
get_docs()

Return a dictionary of functions and the inline documentation for each

master_call(**kwargs)

Execute a wheel function through the master network interface (eauth).

This function requires that external_auth is configured and the user is authorized to execute wheel functions: (@wheel).

>>> wheel.master_call(**{
    'fun': 'key.finger',
    'match': 'jerry',
    'eauth': 'auto',
    'username': 'saltdev',
    'password': 'saltdev',
})
{'data': {
    '_stamp': '2013-12-19_22:47:44.427338',
    'fun': 'wheel.key.finger',
    'jid': '20131219224744416681',
    'return': {'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}},
    'success': True,
    'tag': 'salt/wheel/20131219224744416681',
    'user': 'saltdev'
},
'tag': 'salt/wheel/20131219224744416681'}

CloudClient

class salt.cloud.CloudClient(path=None, opts=None, config_dir=None)

The client class to wrap cloud interactions

action(fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None)

Execute a single action via the cloud plugin backend

Examples:

client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'})
create(provider, names, **kwargs)

Create the named VMs, without using a profile

Example:

client.create(names=['myinstance'], provider='my-ec2-config',
kwargs={'image': 'ami-1624987f', 'size': 'Micro Instance',
'ssh_username': 'ec2-user', 'securitygroup': 'default', 'delvol_on_destroy': True})
destroy(names)

Destroy the named VMs

full_query(query_type='list_nodes_full')

Query all instance information

list_images(provider=None)

List all available images in configured cloud systems

list_locations(provider=None)

List all available locations in configured cloud systems

list_sizes(provider=None)

List all available sizes in configured cloud systems

low(fun, low)

Pass the cloud function and low data structure to run

profile(profile, names, **kwargs)

Pass in a profile to create, names is a list of vm names to allocate

query(query_type='list_nodes')

Query basic instance information

select_query(query_type='list_nodes_select')

Query select instance information

Current Salt release: 2014.1.6

Docs for previous releases on salt.rtfd.org.

Table Of Contents

Previous topic

salt.cloud.clouds.softlayer

Next topic

Peer Communication

Upcoming SaltStack Events