Search code examples
pythonsalt-project

saltstack - execute a state inside a reactor written in python


I am trying to create a reactor in Python + Jinja to react to some event. The documentation has fairly good examples on how to create reactors using the YAML format. However, the documentation for creating a reactor in Python is quite lacking.

Here is what I got so far:

#!jinja|py

"""
reactors can be also complete Python programs instead of Jinja + YAML
"""


def run():
    '''
    I can have fairly complex logic here, but it is all executed on the
    master. 
    '''
    # I can define variable like this
    var = "{{ data['id'] }}"  # this is the id of the minion that sent the signal

    # I can call a salt module like this:
    __salt__['pkg.install']('figlet')  # this will install figlet on the master 
    return {}

The documentation states

The SLS file should contain a function called run which returns high state data.

But so far I fail to see how I can target the desired minion from this dictionary. I know I can use the salt API, but I would like to avoid this at the moment.

Can someone here give an example how you can call a state and target and a minion by returning the correct high state data?


Solution

  • So, it turns out, my way of accessing the context data was wrong. There is no need to wrap the python script in Jinja. Unfortunately this is undocumented at the moment. If you write a state or a returner in Python everything that was inside

    {{ data }} # in Jinja + YAML
    

    Is now available with a global variable called (not suprisingly) data. This variable is a dictionary too.

    #!py
    
    def run():
        '''
        '''
        # I can define variable like this
        var = data['id']   # this is the id of the minion that sent the signal
    
        return {}