neulab/tldr huggingface dataset:
salt.thorium.check.len_ne(name, value) Only succeed if the length of the given register location is not equal to the given value.
foo: check.len_ne: - value: 42
salt.thorium.check.lt(name, value) Only succeed if the value in the given register location is less than the given value
foo: check.lt: - value: 42
salt.thorium.check.lte(name, value) Only succeed if the value in the given register location is less than or equal the given value
foo: check.lte: - value: 42
salt.thorium.check.ne(name, value) Only succeed if the value in the given register location is not equal to the given value
foo: check.ne: - value: 42
salt.thorium.file Writes matches to disk to verify activity, helpful when testing
Normally this is used by giving the name of the file (without a path) that the data will be saved to. If for instance you use foo as the name:
foo: file.save
Then the file will be saved to:
<salt cachedir>/thorium/saves/foo
You may also provide an absolute path for the file to be saved to:
/tmp/foo.save: file.save
Files will be saved in JSON format. However, JSON does not support set()``s.  If you are saving a register entry that contains a ``set(), then it will fail to save to JSON format. However, you may pass data through a filter which makes it JSON compliant:
foo: file.save: filter: True
Be warned that if you do this, then the file will be saved, but not in a format that can be re-imported into Python.
salt.thorium.file.save(name, filter=False) Save the register to <salt cachedir>/thorium/saves/<name>, or to an absolute path.
If an absolute path is specified, then the directory will be created non-recursively if it doesn't exist.
/tmp/foo: file.save
salt.thorium.key The key Thorium State is used to apply changes to the accepted/rejected/pending keys
salt.thorium.key.timeout(name, delete=0, reject=0) If any minion's status is older than the timeout value then apply the given action to the timed out key. This example will remove keys to minions that have not checked in for 300 seconds (5 minutes)
clean_keys: key.timeout: - require: - status: statreg - delete: 300
salt.thorium.local Run remote execution commands via the local client
salt.thorium.local.cmd(name, tgt, func, arg=(), tgt_type='glob', ret='', kwarg=None, **kwargs) Execute a remote execution command
run_remote_ex: local.cmd: - tgt: '*' - func: test.ping
run_remote_ex: local.cmd: - tgt: '*' - func: test.sleep - arg: - 30
run_remote_ex: local.cmd: - tgt: '*' - func: test.sleep - kwarg: length: 30
salt.thorium.reg Used to manage the thorium register. The thorium register is where compound values are stored and computed, such as averages etc.
salt.thorium.reg.clear(name) Clear the namespace from the register
clearns: reg.clear: - name: myregister
salt.thorium.reg.delete(name) Delete the namespace from the register
deletens: reg.delete: - name: myregister
salt.thorium.reg.list_(name, add, match, stamp=False, prune=0) Add the specified values to the named list
If stamp is True, then the timestamp from the event will also be added if prune is set to an integer higher than 0, then only the last prune values will be kept in the list.
salt.thorium.reg.mean(name, add, match) Accept a numeric value from the matched events and store a running average of the values in the given register. If the specified value is not numeric it will be skipped
foo: reg.mean: - add: data_field - match: my/custom/event
salt.thorium.reg.set_(name, add, match) Add a value to the named set
foo: reg.set: - add: bar - match: my/custom/event
salt.thorium.runner React by calling asynchronous runners
salt.thorium.runner.cmd(name, func=None, arg=(), **kwargs) Execute a runner asynchronous:
run_cloud: runner.cmd: - func: cloud.create - arg: - my-ec2-config - myinstance
run_cloud: runner.cmd: - func: cloud.create - kwargs: provider: my-ec2-config instances: myinstance
salt.thorium.status This thorium state is used to track the status beacon events and keep track of the active status of minions
salt.thorium.status.reg(name) Activate this register to turn on a minion status tracking register, this register keeps the current status beacon data and the time that each beacon was last checked in.
salt.thorium.timer Allow for flow based timers. These timers allow for a sleep to exist across multiple runs of the flow
salt.thorium.timer.hold(name, seconds) Wait for a given period of time, then fire a result of True, requiring this state allows for an action to be blocked for evaluation based on time
hold_on_a_moment: timer.hold: - seconds: 30
salt.thorium.wheel React by calling asynchronous runners
salt.thorium.wheel.cmd(name, fun=None, arg=(), **kwargs) Execute a runner asynchronous:
run_cloud: wheel.cmd: - fun: key.delete - match: minion_id
token modules ┌─────────────┬────────────────────────────┐ │localfs      │ Stores eauth tokens in the │ │             │ filesystem of the master.  │ ├─────────────┼────────────────────────────┤ │rediscluster │ Provide token storage in   │ │             │ Redis cluster.             │ └─────────────┴────────────────────────────┘
salt.tokens.localfs Stores eauth tokens in the filesystem of the master. Location is configured by the master config option 'token_dir'
salt.tokens.localfs.get_token(opts, tok) Fetch the token data from the store.
• opts -- Salt master config options
• tok -- Token value to get
Returns Token data if successful. Empty dict if failed.
salt.tokens.localfs.list_tokens(opts) List all tokens in the store.
Parameters opts -- Salt master config options
Returns List of dicts (tokens)
salt.tokens.localfs.mk_token(opts, tdata) Mint a new token using the config option hash_type and store tdata with 'token' attribute set to the token.  This module uses the hash of random 512 bytes as a token.
• tdata -- Token data to be stored with 'token' attribute of this dict set to the token.
Returns tdata with token if successful. Empty dict if failed.
salt.tokens.localfs.rm_token(opts, tok) Remove token from the store.
• tok -- Token to remove
Returns Empty dict if successful. None if failed.
salt.tokens.rediscluster Provide token storage in Redis cluster.
To get started simply start a redis cluster and assign all hashslots to the connected nodes.  Add the redis hostname and port to master configs as eauth_redis_host and eauth_redis_port.  Default values for these configs are as follow:
eauth_redis_host: localhost eauth_redis_port: 6379
• redis-py-cluster Python package
salt.tokens.rediscluster.get_token(opts, tok) Fetch the token data from the store.
salt.tokens.rediscluster.list_tokens(opts) List all tokens in the store.
Returns List of dicts (token_data)
salt.tokens.rediscluster.mk_token(opts, tdata) Mint a new token using the config option hash_type and store tdata with 'token' attribute set to the token.  This module uses the hash of random 512 bytes as a token.
salt.tokens.rediscluster.rm_token(opts, tok) Remove token from the store.
master tops modules ┌────────────────┬───────────────────────────┐ │cobbler         │ Cobbler Tops              │ ├────────────────┼───────────────────────────┤ │ext_nodes       │ External Nodes Classifier │ ├────────────────┼───────────────────────────┤ │mongo           │ Read tops data from a     │ │                │ mongodb collection        │ ├────────────────┼───────────────────────────┤ │reclass_adapter │ Read tops data from a     │ │                │ reclass database          │ ├────────────────┼───────────────────────────┤ │saltclass       │ Saltclass Configuration   │ ├────────────────┼───────────────────────────┤ │varstack_top    │ Use Varstack to provide   │ │                │ tops data                 │ └────────────────┴───────────────────────────┘
salt.tops.cobbler Cobbler Tops Cobbler Tops is a master tops subsystem used to look up mapping information from Cobbler via its API. The same cobbler.* parameters are used for both the Cobbler tops and Cobbler pillar modules.
master_tops: cobbler: {} cobbler.url: https://example.com/cobbler_api #default is http://localhost/cobbler_api cobbler.user: username # default is no username cobbler.password: password # default is no password
Module Documentation salt.tops.cobbler.top(**kwargs) Look up top data in Cobbler for a minion.
salt.tops.ext_nodes External Nodes Classifier The External Nodes Classifier is a master tops subsystem that retrieves mapping information from major configuration management systems. One of the most common external nodes classifiers system is provided by Cobbler and is called cobbler-ext-nodes.
The cobbler-ext-nodes command can be used with this configuration:
master_tops: ext_nodes: cobbler-ext-nodes
It is noteworthy that the Salt system does not directly ingest the data sent from the cobbler-ext-nodes command, but converts the data into information that is used by a Salt top file.
Any command can replace the call to 'cobbler-ext-nodes' above, but currently the data must be formatted in the same way that the standard 'cobbler-ext-nodes' does.
See (admittedly degenerate and probably not complete) example:
classes: - basepackages - database
The above essentially is the same as a top.sls containing the following:
base: '*': - basepackages - database
salt.tops.ext_nodes.top(**kwargs) Run the command configured
salt.tops.mongo Read tops data from a mongodb collection
This module will load tops data from a mongo collection. It uses the node's id for lookups.
Configuring the Mongo Tops Subsystem master_tops: mongo: collection: tops id_field: _id re_replace: "" re_pattern: \.example\.com states_field: states environment_field: environment
Module Documentation salt.tops.mongo.top(**kwargs) Connect to a mongo database and read per-node tops data.
• collection (*) -- The mongodb collection to read data from. Defaults to 'tops'.
• states_field (*) -- The name of the field providing a list of states.
• environment_field (*) -- The name of the field providing the environment.  Defaults to environment.
salt.tops.reclass_adapter Read tops data from a reclass database
This master_tops plugin provides access to the reclass database, such that state information (top data) are retrieved from reclass.
To use the plugin, add it to the master_tops list in the Salt master config and tell reclass by way of a few options how and where to find the inventory:
master_tops: reclass: storage_type: yaml_fs inventory_base_uri: /srv/salt
If you are also using reclass as ext_pillar plugin, and you want to avoid having to specify the same information for both, use YAML anchors (take note of the differing data types for ext_pillar and master_tops):
salt.tops.reclass_adapter.top(**kwargs) Query reclass for the top data (states of the minions).
salt.tops.saltclass Saltclass Configuration master_tops: saltclass: path: /srv/saltclass
Description This module clones the behaviour of reclass (‐ http://reclass.pantsfullofunix.net/), without the need of an external app, and add several features to improve flexibility.  Saltclass lets you define your nodes from simple yaml files (.yml) through hierarchical class inheritance with the possibility to override pillars down the tree.
Features • Define your nodes through hierarchical class inheritance
Reuse your reclass datas with minimal modifications
• applications => states
• parameters => pillars
• Use Jinja templating in your yaml definitions
Access to the following Salt objects in Jinja
• __opts__
• __salt__
• __grains__
• __pillars__
• minion_id
• Chose how to merge or override your lists using ^ character (see examples)
• Expand variables ${} with possibility to escape them if needed ${} (see examples)
• Ignores missing node/class and will simply return empty without breaking the pillar module completely - will be logged
An example subset of datas is available here: http://git.mauras.ch/salt/saltclass/src/master/examples
┌───────────────────────────┬─────────────────────────────┐ │Terms usable in yaml files │ Description                 │ ├───────────────────────────┼─────────────────────────────┤ │classes                    │ A list of classes that will │ │                           │ be processed in order       │ ├───────────────────────────┼─────────────────────────────┤ │states                     │ A list of states that will  │ │                           │ be returned by master_tops  │ │                           │ function                    │ ├───────────────────────────┼─────────────────────────────┤ │pillars                    │ A yaml dictionary that will │ │                           │ be returned by the          │ │                           │ ext_pillar function         │ ├───────────────────────────┼─────────────────────────────┤ │environment                │ Node saltenv that will be   │ │                           │ used by master_tops         │ └───────────────────────────┴─────────────────────────────┘
A class consists of:
• zero or more parent classes
• zero or more states
• any number of pillars
A child class can override pillars from a parent class.  A node definition is a class in itself with an added environment parameter for saltenv definition.
Class names Class names mimic salt way of defining states and pillar files.  This means that default.users class name will correspond to one of these:
• <saltclass_path>/classes/default/users.yml
• <saltclass_path>/classes/default/users/init.yml
Saltclass file hierarchy A saltclass tree would look like this:
<saltclass_path> ├── classes │   ├── app │   │   ├── borgbackup.yml │   │   └── ssh │   │       └── server.yml │   ├── default │   │   ├── init.yml │   │   ├── motd.yml │   │   └── users.yml │   ├── roles │   │   ├── app.yml │   │   └── nginx │   │       ├── init.yml │   │       └── server.yml │   └── subsidiaries │       ├── gnv.yml │       ├── qls.yml │       └── zrh.yml └── nodes ├── geneva │   └── gnv.node1.yml ├── lausanne │   ├── qls.node1.yml │   └── qls.node2.yml ├── node127.yml └── zurich ├── zrh.node1.yml ├── zrh.node2.yml └── zrh.node3.yml
Saltclass Examples <saltclass_path>/nodes/lausanne/qls.node1.yml
environment: base
classes: {% for class in ['default'] %} - {{ class }} {% endfor %} - subsidiaries.{{ __grains__['id'].split('.')[0] }}
<saltclass_path>/classes/default/init.yml
classes: - default.users - default.motd
states: - openssh
pillars: default: network: dns: srv1: 192.168.0.1 srv2: 192.168.0.2 domain: example.com ntp: srv1: 192.168.10.10 srv2: 192.168.10.20
<saltclass_path>/classes/subsidiaries/gnv.yml
pillars: default: network: sub: Geneva dns: srv1: 10.20.0.1 srv2: 10.20.0.2 srv3: 192.168.1.1 domain: gnv.example.com users: adm1: uid: 1210 gid: 1210 gecos: 'Super user admin1' homedir: /srv/app/adm1 adm3: uid: 1203 gid: 1203 gecos: 'Super user adm
Variable expansions Escaped variables are rendered as is: ${test}
Missing variables are rendered as is: ${net:dns:srv2}
pillars: app: config: dns: srv1: ${default:network:dns:srv1} srv2: ${net:dns:srv2} uri: https://application.domain/call?\${test} prod_parameters: - p1 - p2 - p3 pkg: - app-core - app-backend
List override Not using ^ as the first entry will simply merge the lists
pillars: app: pkg: - ^ - app-frontend
NOTE: Known limitation
Currently you can't have both a variable and an escaped variable in the same string as the escaped one will not be correctly rendered - '${xx}' will stay as is instead of being rendered as '${xx}'
salt.tops.saltclass.top(**kwargs) Compile tops
salt.tops.varstack_top Use Varstack to provide tops data
This master_tops plugin provides access to the varstack hierarchical yaml files, so you can user varstack as a full external node classifier and store state information (top data) in it.
Configuring Varstack To use varstack as a master top external node classifier, install varstack as documented. Then, add to your master's configuration:
Varstack will then use /path/to/the/config/file/varstack.yaml (usually /etc/varstack.yaml) to determine which configuration data to return as adapter information. From there you can take a look at the README of varstack to learn how this file is evaluated. The ENC part will just return the 'states' dictionary for the node.
Ie, if my.fqdn.yaml file contains:
--- states: - sudo - openssh - apache - salt.minion
these will be returned as {'base': ['sudo', 'openssh', 'apache', 'salt.minion']} and managed by salt as if given from a top.sls file.
salt.tops.varstack_top.top(**kwargs) Query varstack for the top data (states of the minions).
wheel modules ┌─────────────┬─────────────────────────────┐ │config       │ Manage the master           │ │             │ configuration file          │ ├─────────────┼─────────────────────────────┤ │error        │ Error generator to enable   │ │             │ integration testing of salt │ │             │ wheel error handling        │ ├─────────────┼─────────────────────────────┤ │file_roots   │ Read in files from the      │ │             │ file_root and save files to │ │             │ the file root               │ ├─────────────┼─────────────────────────────┤ │key          │ Wheel system wrapper for    │ │             │ the Salt key system to be   │ │             │ used in interactions with   │ │             │ the Salt Master             │ │             │ programmatically.           │ ├─────────────┼─────────────────────────────┤ │minions      │ Wheel system wrapper for    │ │             │ connected minions           │ ├─────────────┼─────────────────────────────┤ │pillar_roots │ The pillar_roots wheel      │ │             │ module is used to manage    │ │             │ files under the pillar      │ │             │ roots directories on the    │ │             │ master server.              │ └─────────────┴─────────────────────────────┘
salt.wheel.config Manage the master configuration file
salt.wheel.config.apply(key, value) Set a single key
NOTE: This will strip comments from your config file
salt.wheel.config.update_config(file_name, yaml_contents) Update master config with yaml_contents.
Writes yaml_contents to a file named file_name.conf under the folder specified by default_include.  This folder is named master.d by default. Please look at include-configuration for more information.
Example low data:
data = { 'username': 'salt', 'password': 'salt', 'fun': 'config.update_config', 'file_name': 'gui', 'yaml_contents': {'id': 1}, 'client': 'wheel', 'eauth': 'pam', }
salt.wheel.config.values() Return the raw values of the config file
salt.wheel.error Error generator to enable integration testing of salt wheel error handling
salt.wheel.error.error(name=None, message='') If name is None Then return empty dict
salt-wheel error salt-wheel error.error name="Exception" message="This is an error."
salt.wheel.file_roots Read in files from the file_root and save files to the file root
salt.wheel.file_roots.find(path, saltenv='base') Return a dict of the files located with the given path and environment
salt.wheel.file_roots.list_env(saltenv='base') Return all of the file paths found in an environment
salt.wheel.file_roots.list_roots() Return all of the files names in all available environments
salt.wheel.file_roots.read(path, saltenv='base') Read the contents of a text file, if the file is binary then
salt.wheel.file_roots.write(data, path, saltenv='base', index=0) Write the named file, by default the first file found is written, but the index of the file can be specified to write to a lower priority file root
salt.wheel.key Wheel system wrapper for the Salt key system to be used in interactions with the Salt Master programmatically.
The key module for the wheel system is meant to provide an internal interface for other Salt systems to interact with the Salt Master. The following usage examples assume that a WheelClient is available:
import salt.config import salt.wheel opts = salt.config.master_config('/etc/salt/master') wheel = salt.wheel.WheelClient(opts)
Note that importing and using the WheelClient must be performed on the same machine as the Salt Master and as the same user that runs the Salt Master, unless external_auth is configured and the user is authorized to execute wheel functions.
The function documentation starts with the wheel reference from the code sample above and use the WheelClient functions to show how they can be called from a Python interpreter.
The wheel key functions can also be called via a salt command at the CLI using the saltutil execution module.
salt.wheel.key.accept(match, include_rejected=False, include_denied=False) Accept keys based on a glob match. Returns a dictionary.
match  The glob match of keys to accept.
include_rejected To include rejected keys in the match along with pending keys, set this to True. Defaults to False.
include_denied To include denied keys in the match along with pending keys, set this to True. Defaults to False.
>>> wheel.cmd('key.accept', ['minion1']) {'minions': ['minion1']}
salt.wheel.key.accept_dict(match, include_rejected=False, include_denied=False) Accept keys based on a dict of keys. Returns a dictionary.
match  The dictionary of keys to accept.
Example to move a list of keys from the minions_pre (pending) directory to the minions (accepted) directory:
>>> wheel.cmd('key.accept_dict', { 'minions_pre': [ 'jerry', 'stuart', 'bob', ], }) {'minions': ['jerry', 'stuart', 'bob']}
salt.wheel.key.delete(match) Delete keys based on a glob match. Returns a dictionary.
match  The glob match of keys to delete.
>>> wheel.cmd_async({'fun': 'key.delete', 'match': 'minion1'}) {'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
salt.wheel.key.delete_dict(match) Delete keys based on a dict of keys. Returns a dictionary.
match  The dictionary of keys to delete.
>>> wheel.cmd_async({'fun': 'key.delete_dict', 'match': { 'minions': [ 'jerry', 'stuart', 'bob', ], }}) {'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
salt.wheel.key.finger(match, hash_type=None) Return the matching key fingerprints. Returns a dictionary.
match  The key for with to retrieve the fingerprint.
>>> wheel.cmd('key.finger', ['minion1']) {'minions': {'minion1': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}
salt.wheel.key.finger_master(hash_type=None) Return the fingerprint of the master's public key
>>> wheel.cmd('key.finger_master') {'local': {'master.pub': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}
salt.wheel.key.gen(id_=None, keysize=2048) Generate a key pair. No keys are stored on the master. A key pair is returned as a dict containing pub and priv keys. Returns a dictionary containing the pub and priv keys with their generated values.
id_    Set a name to generate a key pair for use with salt. If not specified, a random name will be specified.
keysize The size of the key pair to generate. The size must be 2048, which is the default, or greater. If set to a value less than 2048, the key size will be rounded up to 2048.
>>> wheel.cmd('key.gen') {'pub': '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBC ... BBPfamX9gGPQTpN9e8HwcZjXQnmg8OrcUl10WHw09SDWLOlnW+ueTWugEQpPt\niQIDAQAB\n -----END PUBLIC KEY-----', 'priv': '-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA42Kf+w9XeZWgguzv ... QH3/W74X1+WTBlx4R2KGLYBiH+bCCFEQ/Zvcu4Xp4bIOPtRKozEQ==\n -----END RSA PRIVATE KEY-----'}
salt.wheel.key.gen_accept(id_, keysize=2048, force=False) Generate a key pair then accept the public key. This function returns the key pair in a dict, only the public key is preserved on the master. Returns a dictionary.
id_    The name of the minion for which to generate a key pair.
force  If a public key has already been accepted for the given minion on the master, then the gen_accept function will return an empty dictionary and not create a new key. This is the default behavior. If force is set to True, then the minion's previously accepted key will be overwritten.
>>> wheel.cmd('key.gen_accept', ['foo']) {'pub': '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBC ... BBPfamX9gGPQTpN9e8HwcZjXQnmg8OrcUl10WHw09SDWLOlnW+ueTWugEQpPt\niQIDAQAB\n -----END PUBLIC KEY-----', 'priv': '-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA42Kf+w9XeZWgguzv ... QH3/W74X1+WTBlx4R2KGLYBiH+bCCFEQ/Zvcu4Xp4bIOPtRKozEQ==\n -----END RSA PRIVATE KEY-----'}
We can now see that the foo minion's key has been accepted by the master:
>>> wheel.cmd('key.list', ['accepted']) {'minions': ['foo', 'minion1', 'minion2', 'minion3']}
salt.wheel.key.gen_keys(keydir=None, keyname=None, keysize=None, user=None) Generate minion RSA public keypair
salt.wheel.key.gen_signature(priv, pub, signature_path, auto_create=False, keysize=None) Generate master public-key-signature
salt.wheel.key.key_str(match) Return information about the key. Returns a dictionary.
match  The key to return information about.
>>> wheel.cmd('key.key_str', ['minion1']) {'minions': {'minion1': '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0B ... TWugEQpPt\niQIDAQAB\n-----END PUBLIC KEY-----'}}
salt.wheel.key.list_(match) List all the keys under a named status. Returns a dictionary.
match  The type of keys to list. The pre, un, and unaccepted options will list unaccepted/unsigned keys. acc or accepted will list accepted/signed keys. rej or rejected will list rejected keys.  Finally, all will list all keys.
>>> wheel.cmd('key.list', ['accepted']) {'minions': ['minion1', 'minion2', 'minion3']}
salt.wheel.key.list_all() List all the keys. Returns a dictionary containing lists of the minions in each salt-key category, including minions, minions_rejected, minions_denied, etc. Returns a dictionary.
>>> wheel.cmd('key.list_all') {'local': ['master.pem', 'master.pub'], 'minions_rejected': [], 'minions_denied': [], 'minions_pre': [], 'minions': ['minion1', 'minion2', 'minion3']}
salt.wheel.key.master_key_str() Returns master's public key. Returns a dictionary
>>> wheel.cmd('key.master_key_str') {'local': {'master.pub': '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0B ... TWugEQpPt\niQIDAQAB\n-----END PUBLIC KEY-----'}}
salt.wheel.key.name_match(match) List all the keys based on a glob match
salt.wheel.key.reject(match, include_accepted=False, include_denied=False) Reject keys based on a glob match. Returns a dictionary.
match  The glob match of keys to reject.
include_accepted To include accepted keys in the match along with pending keys, set this to True. Defaults to False.
>>> wheel.cmd_async({'fun': 'key.reject', 'match': 'minion1'}) {'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
salt.wheel.key.reject_dict(match, include_accepted=False, include_denied=False) Reject keys based on a dict of keys. Returns a dictionary.
match  The dictionary of keys to reject.
>>> wheel.cmd_async({'fun': 'key.reject_dict', 'match': { 'minions': [ 'jerry', 'stuart', 'bob', ], }}) {'jid': '20160826201244808521', 'tag': 'salt/wheel/20160826201244808521'}
salt.wheel.minions Wheel system wrapper for connected minions
salt.wheel.minions.connected() List all connected minions on a salt-master
salt.wheel.pillar_roots The pillar_roots wheel module is used to manage files under the pillar roots directories on the master server.
salt.wheel.pillar_roots.find(path, saltenv='base') Return a dict of the files located with the given path and environment
salt.wheel.pillar_roots.list_env(saltenv='base') Return all of the file paths found in an environment
salt.wheel.pillar_roots.list_roots() Return all of the files names in all available environments
salt.wheel.pillar_roots.read(path, saltenv='base') Read the contents of a text file, if the file is binary then
salt.wheel.pillar_roots.write(data, path, saltenv='base', index=0) Write the named file, by default the first file found is written, but the index of the file can be specified to write to a lower priority file root
Python client API Salt provides several entry points for interfacing with Python applications.  These entry points are often referred to as *Client() APIs. Each client accesses different parts of Salt, either from the master or from a minion. Each client is detailed below.
SEE ALSO: There are many ways to access Salt programmatically.
Salt can be used from CLI scripts as well as via a REST interface.
See Salt's outputter system to retrieve structured data from Salt as JSON, or as shell-friendly text, or many other formats.
See the state.event runner to utilize Salt's event bus from shell scripts.
Salt's netapi module provides access to Salt externally via a REST interface.  Review the netapi module documentation for more information.
Salt's opts dictionary 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.
salt.config.client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None) Load Master configuration data
import salt.config master_opts = salt.config.client_config('/etc/salt/master')
Returns a dictionary of the Salt Master configuration file with necessary options needed to communicate with a locally-running Salt Master daemon.  This function searches for client specific configurations and adds them to the data from the master configuration.
This is useful for master-side operations like LocalClient.
salt.config.minion_config(path, env_var='SALT_MINION_CONFIG', defaults=None, cache_minion_id=False, ignore_config_errors=True, minion_id=None, role='minion') Reads in the minion configuration file and sets up special options
This is useful for Minion-side operations, such as the Caller class, and manually running the loader interface.
import salt.config minion_opts = salt.config.minion_config('/etc/salt/minion')
Salt's Loader Interface Modules in the Salt ecosystem are loaded into memory using a custom loader system. This allows modules to have conditional requirements (OS, OS version, installed libraries, etc) and allows Salt to inject special variables (__salt__, __opts__, etc).
Most modules can be manually loaded. This is often useful in third-party Python apps or when writing tests. However some modules require and expect a full, running Salt system underneath. Notably modules that facilitate master-to-minion communication such as the mine, publish, and peer execution modules. The error KeyError: 'master_uri' is a likely indicator for this situation. In those instances use the Caller class to execute those modules instead.
Each module type has a corresponding loader function.
salt.loader.minion_mods(opts, context=None, utils=None, whitelist=None, initial_load=False, loaded_base_name=None, notify=False, static_modules=None, proxy=None) Load execution modules
Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module.
• opts (dict) -- The Salt options dictionary
• context (dict) -- A Salt context that should be made present inside generated modules in __context__
• utils (dict) -- Utility functions which should be made available to Salt modules in __utils__. See utils_dirs in salt.config for additional information about configuration.
• whitelist (list) -- A list of modules which should be whitelisted.
• initial_load (bool) -- Deprecated flag! Unused.
• loaded_base_name (str) -- A string marker for the loaded base name.
• notify (bool) -- Flag indicating that an event should be fired upon completion of module loading.
import salt.config import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = salt.loader.utils(__opts__) __salt__ = salt.loader.minion_mods(__opts__, utils=__utils__) __salt__['test.ping']()
salt.loader.raw_mod(opts, name, functions, mod='modules') Returns a single module loaded raw and bypassing the __virtual__ function
__opts__ = salt.config.minion_config('/etc/salt/minion') testmod = salt.loader.raw_mod(__opts__, 'test', None) testmod['test.ping']()
salt.loader.states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None) Returns the state modules
• functions (dict) -- A dictionary of minion modules, with module names as keys and funcs as values.
__opts__ = salt.config.minion_config('/etc/salt/minion') statemods = salt.loader.states(__opts__, None, None)
salt.loader.grains(opts, force_refresh=False, proxy=None, context=None) Return the functions for the dynamic grains and the values for the static grains.
Since grains are computed early in the startup process, grains functions do not have __salt__ or __proxy__ available.  At proxy-minion startup, this function is called with the proxymodule LazyLoader object so grains functions can communicate with their controlled device.
__opts__ = salt.config.minion_config('/etc/salt/minion') __grains__ = salt.loader.grains(__opts__) print __grains__['id']
salt.loader.grain_funcs(opts, proxy=None, context=None) Returns the grain functions
__opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__)
Salt's Client Interfaces LocalClient class salt.client.LocalClient(c_path='/etc/salt/master', mopts=None, skip_perm_errors=False, io_loop=None, keep_loop=False, auto_reconnect=False, listen=False) 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).
NOTE: The LocalClient uses a Tornado IOLoop, this can create issues when using the LocalClient inside an existing IOLoop. If creating the LocalClient in partnership with another IOLoop either create the IOLoop before creating the LocalClient, or when creating the IOLoop use ioloop.current() which will return the ioloop created by LocalClient.
local = salt.client.LocalClient() local.cmd('*', 'test.fib', [10])
cmd(tgt, fun, arg=(), timeout=None, tgt_type='glob', ret='', jid='', full_return=False, 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'], ])
• tgt (string or list) -- Which minions to target for the execution. Default is shell glob. Modified by the tgt_type 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.
• tgt_type --
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
• pillar_pcre - Pillar data comparison with a regex
• nodegroup - Match on nodegroup
• range - Use a Range server for matching
• compound - Pass a compound match string
• ipcidr - Match based on Subnet (CIDR notation) or IPv4 address.
Changed in version 2017.7.0: Renamed from expr_form to tgt_type
• 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.
• full_return -- Output the job return only (default) or the full return including exit code and other job metadata.
Optional keyword arguments.  Authentication credentials may be passed when using external_auth.
For example: local.cmd('*', 'test.ping', username='saltdev', password='saltdev', eauth='pam').  Or: local.cmd('*', 'test.ping', token='5871821ea51754fdcea8153c1c745433')
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.
cmd_async(tgt, fun, arg=(), tgt_type='glob', ret='', jid='', 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_batch(tgt, fun, arg=(), tgt_type='glob', ret='', kwarg=None, batch='10%', **kwargs) Iteratively execute a command on subsets of minions at a time
Parameters batch -- The batch identifier of systems to execute on
Returns A generator of minion returns
>>> returns = local.cmd_batch('*', 'state.highstate', batch='10%') >>> for ret in returns: ...     print(ret) {'jerry': {...}} {'dave': {...}} {'stewart': {...}}
cmd_iter(tgt, fun, arg=(), timeout=None, tgt_type='glob', ret='', kwarg=None, **kwargs) Yields the individual minion returns as they come in
Normally cmd_iter() does not yield results for minions that are not connected. If you want it to return results for disconnected minions set expect_minions=True in kwargs.
Returns A generator yielding the individual minion returns
>>> 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, tgt_type='glob', ret='', kwarg=None, show_jid=False, verbose=False, **kwargs)
Yields the individual minion returns as they come in, or None when no returns are available.
Returns A generator yielding the individual minion returns, or None when no returns are available. This allows for actions to be injected in between minion returns.
>>> ret = local.cmd_iter_no_block('*', 'test.ping') >>> for i in ret: ...     print(i) None {'jerry': {'ret': True}} {'dave': {'ret': True}} None {'stewart': {'ret': True}}
cmd_subset(tgt, fun, arg=(), tgt_type='glob', ret='', kwarg=None, subset=3, cli=False, progress=False, full_return=False, **kwargs) Execute a command on a random subset of the targeted systems
• subset -- The number of systems to execute on
• cli -- When this is set to True, a generator is returned, otherwise a dictionary of the minion returns is returned
>>> SLC.cmd_subset('*', 'test.ping', subset=1) {'jerry': True}
get_cli_returns(jid, minions, timeout=None, tgt='*', tgt_type='glob', verbose=False, show_jid=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.
run_job(tgt, fun, arg=(), tgt_type='glob', ret='', timeout=None, jid='', kwarg=None, listen=False, **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']}
Salt Caller class salt.client.Caller(c_path='/etc/salt/minion', mopts=None) Caller is the same interface used by the salt-call command-line tool on the Salt Minion.
Changed in version 2015.8.0: Added the cmd method for consistency with the other Salt clients.  The existing function and sminion.functions interfaces still exist but have been removed from the docs.
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.
import salt.client caller = salt.client.Caller() caller.cmd('test.ping')
Note, a running master or minion daemon is not required to use this class.  Running salt-call --local simply sets file_client to 'local'. The same can be achieved at the Python level by including that setting in a minion config file.
New in version 2014.7.0: Pass the minion config as the mopts dictionary.
import salt.client import salt.config __opts__ = salt.config.minion_config('/etc/salt/minion') __opts__['file_client'] = 'local' caller = salt.client.Caller(mopts=__opts__)
cmd(fun, *args, **kwargs) Call an execution module with the given arguments and keyword arguments
caller.cmd('test.arg', 'Foo', 'Bar', baz='Baz')
caller.cmd('event.send', 'myco/myevent/something', data={'foo': 'Foo'}, with_env=['GIT_COMMIT'], with_grains=True)
Salt Proxy Caller class salt.client.ProxyCaller(c_path='/etc/salt/proxy', mopts=None) ProxyCaller is the same interface used by the salt-call with the args --proxyid <proxyid> command-line tool on the Salt Proxy Minion.
Importing and using ProxyCaller 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.
import salt.client caller = salt.client.ProxyCaller() caller.cmd('test.ping')
import salt.client import salt.config __opts__ = salt.config.proxy_config('/etc/salt/proxy', minion_id='quirky_edison') __opts__['file_client'] = 'local' caller = salt.client.ProxyCaller(mopts=__opts__)
NOTE: To use this for calling proxies, the is_proxy functions requires that --proxyid be an argument on the commandline for the script this is used in, or that the string proxy is in the name of the script.
RunnerClient class salt.runner.RunnerClient(opts, context=None) 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.
asynchronous(fun, low, user='UNKNOWN', pub=None, local=True) Execute the function in a multiprocess and return the event tag to use to watch for the return
cmd(fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False) Execute a function
cmd_async(low) Execute a runner function asynchronously; eauth is respected
This function requires that external_auth is configured and the user is authorized to execute runner functions: (@runner).
runner.eauth_async({ 'fun': 'jobs.list_jobs', 'username': 'saltdev', 'password': 'saltdev', 'eauth': 'pam', })
cmd_sync(low, timeout=None, full_return=False) Execute a runner function synchronously; eauth is respected
runner.eauth_sync({ '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).
>>> wheel.cmd('key.finger', ['jerry']) {'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}
cmd_async(low) Execute a function asynchronously; eauth is respected
This function requires that external_auth is configured and the user is authorized
>>> wheel.cmd_async({ 'fun': 'key.finger', 'match': 'jerry', 'eauth': 'auto', 'username': 'saltdev', 'password': 'saltdev', }) {'jid': '20131219224744416681', 'tag': 'salt/wheel/20131219224744416681'}
cmd_sync(low, timeout=None, full_return=False) Execute a wheel function synchronously; eauth is respected
This function requires that external_auth is configured and the user is authorized to execute runner functions: (@wheel).
>>> wheel.cmd_sync({ 'fun': 'key.finger', 'match': 'jerry', 'eauth': 'auto', 'username': 'saltdev', 'password': 'saltdev', }) {'minions': {'jerry': '5d:f6:79:43:5e:d4:42:3f:57:b8:45:a8:7e:a4:6e:ca'}}
CloudClient class salt.cloud.CloudClient(path=None, opts=None, config_dir=None, pillars=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
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
client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True)
destroy(names) Destroy the named VMs
extra_action(names, provider, action, **kwargs) Perform actions with block storage devices
client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} )
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
map_run(path=None, **kwargs) To execute a map
min_query(query_type='list_nodes_min') Query select instance information
profile(profile, names, vm_overrides=None, **kwargs) Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides
>>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}}
query(query_type='list_nodes') Query basic instance information
select_query(query_type='list_nodes_select') Query select instance information
SSHClient class salt.client.ssh.client.SSHClient(c_path='/etc/salt/master', mopts=None, disable_custom_roster=False) Create a client object for executing routines via the salt-ssh backend
cmd(tgt, fun, arg=(), timeout=None, tgt_type='glob', kwarg=None, **kwargs) Execute a single command via the salt-ssh subsystem and return all routines at once
cmd_iter(tgt, fun, arg=(), timeout=None, tgt_type='glob', ret='', kwarg=None, **kwargs) Execute a single command via the salt-ssh subsystem and return a generator
netapi modules Introduction to netapi modules netapi modules provide API-centric access to Salt. Usually externally-facing services such as REST or WebSockets, XMPP, XMLRPC, etc.
In general netapi modules bind to a port and start a service. They are purposefully open-ended. A single module can be configured to run as well as multiple modules simultaneously.
netapi modules are enabled by adding configuration to your Salt Master config file and then starting the salt-api daemon. Check the docs for each module to see external requirements and configuration settings.
Communication with Salt and Salt satellite projects is done using Salt's own Python API. A list of available client interfaces is below.
Prior to Salt's 2014.7.0 release, netapi modules lived in the separate sister projected salt-api. That project has been merged into the main Salt project.
SEE ALSO: The full list of netapi modules