Differences between revisions 1 and 2
Revision 1 as of 2019-06-16 10:37:24
Size: 1412
Editor: PieterSmit
Comment:
Revision 2 as of 2019-06-16 10:37:52
Size: 1405
Editor: PieterSmit
Comment:
Deletions are marked like this. Additions are marked like this.
Line 49: Line 49:

}}}

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
  • 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.
         1 #!/usr/bin/python
         2 '''
         3 Grain should return a dict, name of file does not matter
         4 '''
         5 import requests
         6 import socket
         7 import logging
         8 log = logging.getLogger(__name__)
         9 
        10 def external_ip():
        11     '''
        12     Return the external IP address reported by ipecho.net
        13     '''
        14     hostname = socket.gethostname().upper()
        15     log.debug("grain example hostname: " + hostname)
        16     # initialize a grains dictionary
        17     grains = {}
        18 
        19     try:
        20         r = requests.get('http://ipecho.net/plain')
        21         ip = r.content
        22     except:
        23         ip = ''
        24 
        25     grains['external_ip'] = ip
        26     grains['anothergrain'] = 'somevalue'
        27     return grains
        28 
        29 
        30 if __name__ == "__main__":
        31     print( external_ip() )
      
  • Once saved on a salt minion with sudo salt-call or from salt master with sudo salt "<Minion>" refresh grains and retrieve value.

    • sudo salt "minion1" saltutil.sync_grains
      sudo salt "minion1" grains.get external_ip
      minion1:
          71.43.13.6

SaltStack/GrainsPythonFunction (last edited 2019-06-16 10:57:22 by PieterSmit)