= SaltStack Grains Python Function = * Adding a python function to salt grains, that can provide a value from each minion. * The requirement was to get the external ip from a minion 1. Write the python function that returns the grains value and place it in your salt stack dir structure in ''' ./salt/_grains/grains-external-ip.py''' * The actual python file name does not matter. {{{#!highlight python #!/usr/bin/python ''' Grain should return a dict, name of file does not matter ''' import requests import socket import logging log = logging.getLogger(__name__) def external_ip(): ''' Return the external IP address reported by ipecho.net ''' hostname = socket.gethostname().upper() log.debug("grain example hostname: " + hostname) # initialize a grains dictionary grains = {} try: r = requests.get('http://ipecho.net/plain') ip = r.content except: ip = '' grains['external_ip'] = ip grains['anothergrain'] = 'somevalue' return grains if __name__ == "__main__": print( external_ip() ) }}} 2. Once saved on a salt minion with '''sudo salt-call ''' or from salt master with ''' sudo salt "" ''' refresh grains and retrieve value. {{{ sudo salt "minion1" saltutil.sync_grains sudo salt "minion1" grains.get external_ip minion1: 71.43.13.6 }}} 3. once the grains function works, you might want to add it to the salt mine, to make it available to other nodes/minions. * Add to file pilla/common/mine.sls {{{ mine_functions: #external_ip calculated by salt/_grains/grains-get-externalip.py external_ip: - mine_function: grains.get - external_ip }}}