Skip to content

Instantly share code, notes, and snippets.

@danielmacuare
Last active September 14, 2020 14:52
Show Gist options
  • Save danielmacuare/9bab9d82dadcc1c2a060a189a0e8acd8 to your computer and use it in GitHub Desktop.
Save danielmacuare/9bab9d82dadcc1c2a060a189a0e8acd8 to your computer and use it in GitHub Desktop.
AWS Lambda Function to Post an alert to a Slack channel every time Cloudwatch triggers the SNS-Backed Lambda
import logging
from json import dumps
from os import environ
from urllib3 import PoolManager
logging.getLogger().setLevel(logging.INFO)
def post_to_slack(event, context):
slack_channel = environ.get("SLACK_NET_CHANNEL")
logging.info("Event: " + str(event))
http = PoolManager()
slack_message = {
"text": "Sample message from Lambda - lambdaSlackNetAlerts - Network Alert - Traffic has exceeded your defined threshold!!"
}
response = http.request(
"POST",
slack_channel,
body=dumps(slack_message),
headers={"Content-Type": "application/json"},
)
res_text = response.data.decode("utf-8")
logging.info("Message posted to: #network-aws-alerts")
logging.info(f"Slack's Response:{res_text.upper()} - {response.status}")
if response.status == 200:
return {"statusCode": 200, "body": dumps("Lambda has executed correctly!")}
return {
"statusCode": f"{response.status}",
"body": dumps(f"Lambda Failed - Reason: {res_text}"),
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment