Skip to content

Instantly share code, notes, and snippets.

@timoguin
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timoguin/8cc68cac25848c95ac61 to your computer and use it in GitHub Desktop.
Save timoguin/8cc68cac25848c95ac61 to your computer and use it in GitHub Desktop.
Slack Module and Returner (basic)
# Part of a custom deploy module that will notify Slack at the end of the deployment run
# Copyright [2014] [Tim O'Guin]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def _notify_slack(commit, slot, slack_channel='operations'):
'''
Prepare the data structure for sending a notification to Slack
'''
data = {
'text': 'New deployment to _{}_ environment'.format(__salt__['grains.get']('environment', 'undefined')),
'attachments': [
{
'color': 'good',
'fields': [
{
'title': 'Rev:',
'value': commit[:8],
'short': True
}
],
},
{
'color': 'good',
'fields': [
{
'title': 'Slot:',
'value': slot,
'short': True
}
],
},
],
}
data.update({'channel': slack_channel})
notify = __salt__['slack.notify'](data=data)
return
# -*- coding: utf-8 -*-
# Copyright [2014] [Tim O'Guin]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Module for sending notifications to Slack.
'''
# Import system modules
import logging
import json
import requests
# Import Salt libs
import salt
log = logging.getLogger(__name__)
def _get_endpoint_url():
'''
Fetch pillar config
'''
slack = __salt__['pillar.get']('slack', None)
if slack['webhook_url'] is None:
return False
return slack['webhook_url']
def notify(data, url=None, **kwargs):
'''
Send a notification to a Slack webhook endpoint.
Expects properly formated JSON data as the main argument. If the URL isn't
specified, try to find it in pillar.
CLI Example:
.. code-block:: bash
salt '*' slack.notify "{'text': 'slack test', 'username': 'saltstack'}"
'''
if url is None:
url = _get_endpoint_url()
if not url:
raise Exception('Failed to configure Slack module')
# default to saltstack for the Slack username if it isn't defined
if not data.has_key('username'):
data.update({'username': 'saltstack'})
headers = {'Content-Type': 'application/json'}
r = requests.post(url, data=json.dumps(data), headers=headers)
if r.status_code == requests.codes.ok: return True
else: return False
# -*- coding: utf-8 -*-
# Copyright [2014] [Tim O'Guin]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Slack returner
Uses slack module. Currently only returns a simple message. Needs support added for
the full ret dict.
'''
# Import system modules
import logging
# Import Salt libs
import salt
log = logging.getLogger(__name__)
def returner(ret):
data = {}
fun = ret['fun']
fun_args = ' '.join(ret['fun_args'])
success = 'ran successfully' if ret['success'] else 'failed'
minion_id = ret['id']
#comment = ret['return'][ret['return'].keys()[0]]['comment']
text = 'Command *{0} {1}* {2} on {3}'.format( \
fun,
fun_args,
success,
minion_id
)
data['text'] = text
try:
__salt__['slack.notify'](data=data)
except Exception as e:
log.error('Failed to notify Slack: {}'.format(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment