Skip to content

Instantly share code, notes, and snippets.

@perfecto25
Created May 14, 2019 15:09
Show Gist options
  • Save perfecto25/14f833d5e420d2510c39d49143083597 to your computer and use it in GitHub Desktop.
Save perfecto25/14f833d5e420d2510c39d49143083597 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import json
import salt.client
import salt.config
import salt.loader
import salt.modules.smtp
notify = '[email protected]'
smtp = 'localhost'
__opts__ = salt.config.minion_config('/etc/salt/minion')
__grains__ = salt.loader.grains(__opts__)
caller = salt.client.Caller()
def run_highstate():
'''
runs a highstate locally with test=true
'''
try:
ret = caller.cmd('state.highstate', test='true')
except Exception as e:
ret = 'error: {}'.format(str(e))
return ret
return json.dumps(ret)
def send_email(drift, count):
'''
sends a notification with # of changes per host
'''
if notify:
salt.modules.smtp.send_msg(\
notify,\
json.dumps(drift, indent=4, sort_keys=True),\
subject='[highstate: {0}] {1} changes'.format(__grains__['id'], count),\
sender='saltstack@{}'.format(__grains__['id']),\
server=smtp,\
use_ssl=False)
def detect_changes():
'''
checks result of Highstate to see if there were drift changes,
creates a Change dictionary and emails the user with errors or changes
'''
result = json.loads(run_highstate())
drift = {}
count = 0
for item in result:
try:
changes = result[item]['result']
except KeyError:
continue
if not changes:
name = result[item]['name']
sls = result[item]['__sls__']
stateid = result[item]['__id__']
comment = result[item]['comment']
try:
change = result[item]['pchanges']
except KeyError:
change = ''
drift[name] = {}
drift[name]['comment'] = comment
drift[name]['change'] = change
drift[name]['formula'] = sls
count += 1
# if # of changes > 0, send email notification
if count > 0:
send_email(drift, count)
if __name__ == "__main__":
detect_changes()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment