Saltstack custom execution modules

From wikinotes
Revision as of 14:26, 30 July 2021 by Will (talk | contribs) (→‎Documentation)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Documentation

official docs https://docs.saltstack.com/en/latest/ref/modules/index.html
writing new modules https://docs.saltproject.io/en/latest/topics/development/modules/developing.html

Locations

<file_roots>/modules_/*.py location of modules
/etc/salt/master configure additional module directories

Usage

salt-call yourmodule.function                               # call module
salt-call yourmodule.function  paramA paramB 'paramC=blah'  # call module with arguments
salt '*target*'  yourmodule.function                        # from master, run on minions
{% do salt.yourmodule.function(...) %}                      # from statefile, run your module

Configuration

No configuration is needed to define your own execution modules.

By default, all locations on the file_roots are checked for a directory called _modules. Any valid python file within that directory can be run by saltstack.

You may add additional file_roots locations within the /etc/salt/master configuration file

file_roots:
    base:
        - /your/new/dir
        - /another/new/dir
        - /srv/salt

Syntax

There is almost nothing magical about execution modules.

  • You can return regular python datatypes (lists, dictionaries, etc)
  • you can require arguments, or define keyword arguments

Similar to saltstack custom states, without any imports, you can access saltstack's internal information using variables that are magically added to the scope.

__salt__['cmd.execute']('ls -la')  # run other salt modules
__grains__['os_family']            # obtain grains
__states__['file.touch'](...)      # run statefiles


Example module:

#!/usr/bin/env python
#### <file_roots>/modules_/greetings.py

def print_hello(yourname):
    return 'Hello {}'.format(yourname)
salt-call greetings.print_hello 'will'   # run module on local machine