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() )
- The actual python file name does not matter.
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
- 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
- Add to file pilla/common/mine.sls