Create a Slack Chat bot using AWS services
Slack is a single place for messaging, tools and files — helping everyone save time and collaborate together.
Slack Connect furthers the idea of shared channels that let companies collaborate, allowing up to 20 organizations to work seamlessly together with apps, chat, and more.
Chat bots can interact with users, respond to queries, post notifications and so on. This article will create a rather simple bot, which will post to a Slack channel. The trigger to post to a slack channel will be a high CPU utilization of an EC2 instance.
Once you sign-up on Slack, you can either create a new channel where you want the notifications to be posted to, or, you can post the notifications to the default #general channel.
Now, go to Apps and search for Incoming WebHooks. WebHooks will enable content to be posted on Slack. They use HTTP requests with a JSON payload containing the message and other details.
Add the WebHook, choose the channel, add Incoming WebHook Integration and copy the WebHook URL.
- Create a High CPU Utilization CloudWatch Alarm. A 1 minute period can be chosen if detailed monitoring is turned on.
2. Now, create a lambda function which will be triggered by the SNS notification in the above created alarm. This lambda function will post the relevant message to the desired Slack Channel. AWS provides a blueprint for this purpose. Search for cloudwatch-alarm-to-slack-python.
3. The WebHook URL can be encrypted and then used inside this lambda function. This function uses AWS KMS to decrypt the encrypted WebHook URL. Create or select and existing execution role, select the SNS notification used in the CloudWatch Alarm and enable the trigger.
4. The python code and instructions are already provided by the lambda blueprint.
To test this, you can load your CPU using stress.
Enable EPEL repo, install stress, and, stress!
sudo amazon-linux-extras install epel -ysudo yum install stress -ystress --cpu <n> --timeout <x>
This command will generate a thread to max out a single CPU core. Essentially, it spawns ‘n’ workers spinning on sqrt() function for x seconds. “cpu” refers to the number of threads used for performing the test.
Since, a single core single thread instance(t2.micro) is being used, this command will max out the CPU.
stress --cpu 1 --timeout 300
If you do not want to wait for the CloudWatch Alarm to trigger, use the below command to alter the alarm state:
aws cloudwatch set-alarm-state --alarm-name CPUThresholdBreachAlarm --state-value ALARM --state-reason "Manually Triggering the alarm"