Skip to content

Instantly share code, notes, and snippets.

@zackferrofields
Last active March 31, 2018 01:46
Show Gist options
  • Save zackferrofields/a8c0d5159d3f2fc0b135bad59b790b40 to your computer and use it in GitHub Desktop.
Save zackferrofields/a8c0d5159d3f2fc0b135bad59b790b40 to your computer and use it in GitHub Desktop.
AWS CodeDeploy trigger Lambda Slack message
'''
Follow these steps to configure the webhook in Slack:
1. Navigate to https://<your-team-domain>.slack.com/services/new
2. Search for and select "Incoming WebHooks".
3. Choose the default channel where messages will be sent and click "Add Incoming WebHooks Integration".
4. Copy the webhook URL from the setup instructions and use it in the next section.
To encrypt your secrets use the following steps:
1. Create or use an existing KMS Key - http://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html
2. Click the "Enable Encryption Helpers" checkbox
3. Paste <SLACK_HOOK_URL> into the kmsEncryptedHookUrl environment variable and click encrypt
Note: You must exclude the protocol from the URL (e.g. "hooks.slack.com/services/abc123").
4. Give your function's role permission for the kms:Decrypt action.
Example:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1443036478000",
"Effect": "Allow",
"Action": [
"kms:Decrypt"
],
"Resource": [
"<your KMS key ARN>"
]
}
]
}
'''
from __future__ import print_function
import boto3
import json
import logging
import os
from base64 import b64decode
from urllib2 import Request, urlopen, URLError, HTTPError
# The base-64 encoded, encrypted key (CiphertextBlob) stored in the kmsEncryptedHookUrl environment variable
ENCRYPTED_HOOK_URL = os.environ['kmsEncryptedHookUrl']
# The Slack channel to send a message to stored in the slackChannel environment variable
SLACK_CHANNEL = os.environ['slackChannel']
HOOK_URL = "https://" + boto3.client('kms').decrypt(CiphertextBlob=b64decode(ENCRYPTED_HOOK_URL))['Plaintext']
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info("Event: " + str(event))
message = json.loads(event['Records'][0]['Sns']['Message'])
logger.info("Message: " + str(message))
application = message.get('applicationName', 'App')
name = message['eventTriggerName']
status = message['status']
id = message['deploymentId']
time = message['completeTime'] if message.get('completeTime', False) else message['createTime']
overview = message.get('deploymentOverview', False)
color = ''
if overview:
overview = eval(overview)
if overview.get('Succeeded', False):
color = 'good'
elif overview.get('Failed', False):
color = 'danger'
else:
color = 'warning'
slack_message = {
'channel': SLACK_CHANNEL,
'attachments': [
{
'color': color,
'title': "%s - %s (%s)" % (application, name, id),
"fields": [
{
"title": "Status",
"value": status,
"short": True
},
{
"title": "Time",
"value": time,
"short": True
}
],
}
]
}
req = Request(HOOK_URL, json.dumps(slack_message))
try:
response = urlopen(req)
response.read()
logger.info("Message posted to %s", slack_message['channel'])
except HTTPError as e:
logger.error("Request failed: %d %s", e.code, e.reason)
except URLError as e:
logger.error("Server connection failed: %s", e.reason)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment