Create Salt Modules to tackle common tasks

Aside from remote execution and configuration management, salt also provides an interface to write custom execution modules and states.

Here’s a basic example execution module:

/srv/salt/_modules/example_cmd.py

#!/usr/bin/env python
# -\*- coding: utf-8 -\*-

'''
This is a Salt module for running a short example command.
'''

# Import salt libs
import time
import salt.utils

def test():
    '''This is just a test fuction, confirming the module works.'''
    return True

def start():
    '''
    Runs the command.
    
    salt '\*' example\_cmd.start parameters
    '''
    cmd = 'some command here'
    ret = \_\_salt\_\_\['cmd.run'\](cmd)
    return ret

def status():
    '''
    Gets the example\_cmd process count.

    salt 'loadtest\*' example\_cmd.status
    '''
    cmd = 'echo $((\`ps aux | grep example\_cmd | wc -l\`-1))'
    ret = \_\_salt\_\_\['cmd.run'\](cmd)
    return ret


def stop():
    '''
    Stops the example command.

    salt '\*' example\_cmd.stop
    '''
    cmd = 'killall -9 example\_cmd'
    ret = \_\_salt\_\_\['cmd.run'\](cmd)
    return ret


if \_\_name\_\_ == "\_\_main\_\_":
    '''
    By default just run the test() block.
    '''
    test()

In the example above you’ll see four basic functions defined: test(), start(), status(), and stop(). Each function has a brief comment, a command to run, a call to salt’s cmd.run module, and a return value. These are easily run by calling example_cmd.start. Further down, you can also see a call to if __name__ == "__main__" which is called if no functions are set… so if just example_cmd is called.

You can turn this into your own basic module by changing cmd = '[insert command here]'.

You could use a custom execution module in combination with Salt’s scheduler or event system.

For official SaltStack module documentation, check out the latest documentation on execution modules and the latest documentation on custom state modules.