Slack has quickly become one of the standard messaging apps in the Enterprise. Many a companies use slack for communication amongst team members and IT departments like having slack channels for projects or critical system groups.
Since most of the people who are supposed to take action on a event are in a slack channel it is sometimes better to have notifications send directly to slack for server events.
One of the requirement I had recently was to create server alerts for checking API gateways and if the webservice was found to be down, to send alert to a slack channel.
To create such event based notification to slack, first you need to create an app in slack and then a webhook to expose it to the internet. Once that is done the remaining magic is done in plain old shell scripting
1. Create an APP in Slack
a) Goto https://api.slack.com/slack-apps
b) Create an App
c) Sign-in with your workspace
2. Create the Slack App and a webhook
a) Go to incoming webhooks and Activate incoming webhooks
You can see the sample of your webhook cURLthen
b) Create a channel in your Slack eg : testalerts and assign to step c below
c) Add new Webhook to workspacee Post To : #testalerts
d) Webhook URLS for Your Workspace
curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/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
3. Test by POST’ing data to your webhook and it should now come in your slack channel
$ curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/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
4. Write Shell Script to check a Webservice URL and check for HTTP 200 OK in the header
Shell Script #!/bin/bash ################################################################# # SHELL SCRIPT TO MONITOR PUBLIC URL AND REST API GATEWAY # Created By : Shadab Mohammad # Company : Whitehat Agency, Sydney # Created Date : 25/10/2018 # Modified Date : 29/10/2018 # ################################################################# ## Check ASIC WebService ## ################################################################# if curl -s --head --request GET https://abr.business.gov.au | grep "200 OK" > /dev/null; then echo "https://abr.business.gov.au is UP" else echo "https://abr.business.gov.au is DOWN" curl -X POST -H 'Content-type: application/json' --data '{"text":"https://abr.business.gov.au is DOWN"}' https://hooks.slack.com/services/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 fi
The above shell script checks the header for 200 OK message , if found it sends alert to the channel via the slack webhook. It can be added to crontab to check the status of the webservice every 5 minutes. If the Webservice is down it will send notification to the Slack channel.
One comment
Hi, Can we pass parameter to the text data?