In this article, we will discuss how to create an AWS lambda function to send Slack notifications when the CPU utilization of an AWS instance reaches 50%.
AWS Lambda is a serverless compute service offered by Amazon Web Services (AWS). It lets you run code without having to provision or manage servers yourself.
It is event-driven i.e. your code executes in response to events triggered by other AWS services like a file upload completed in s3, an HTTP request from Amazon API Gateway or various other triggers.
In this, we will be discussing how to set up Amazon Cloudwatch to monitor and collect metrics from an EC2 instance, Cloudwatch alarms based on those metrics to trigger a notification when a certain threshold or condition is met, Amazon Simple Notification service to receive these notifications and finally a lambda function subscribed to the SNS topic, which will process the notification and send a slack message.
To follow along with this, the reader should have basic knowledge and understanding of
Create a new go project and call it whatever you want, I called mine “lambdaFunction” in your main.go file, paste the following piece of code
import ( "bytes" "context" "encoding/json" "fmt" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "net/http" ) type slackMessage struct { Text string `json:"text"` } func handleRequest(ctx context.Context, snsEvent events.SNSEvent) error { webhookURL := "https://hooks.slack.com/services/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" for _, record := range snsEvent.Records { snsRecord := record.SNS sendSlackNotification(webhookURL, snsRecord.Message) } return nil } func sendSlackNotification(webhookURL, message string) { slackMessage := slackMessage{Text: "Cpu usage is above 50%" + message} slackBody, _ := json.Marshal(slackMessage) req, err := http.NewRequest(http.MethodPost, webhookURL, bytes.NewBuffer(slackBody)) if err != nil { fmt.Printf("Error creating request: %v\n", err) return } req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Error sending request: %v\n", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Printf("Error response from slack: %v\n", resp.StatusCode) } else { fmt.Printf("Successfully sent Slack notification: %v\n", resp.StatusCode) } } func main() { lambda.Start(handleRequest) }
Run go mod
Let's try to understand what going on
The handleRequest function
sendSlackNotification function
To obtain the Slack webhook URL that allows you to send messages to Slack, navigate to https://api.slack.com/apps. Make sure you are signed in to your Slack account before proceeding.
The next step is to create a deployment package for our Go app
We will build the application.
#!/bin/sh ./main
Make the bootstrap file executable
Uploading the lamba function
In the next step, we'll configure a trigger for the Lambda function. This trigger defines the event that will prompt the function to send a message to Slack
As I mentioned earlier that trigger will be when cpu usage of a virtual machine is >= 50%
To achieve this functionality, the first step involves creating an EC2 instance.
When this is done we need to configure Cloudwatch to monitor and collect metrics
In the condition section
We will head back to our lambda function
To test that this works, we need to put our VM under a sort of stress test. This test generates a high CPU load. To perform this test we are going to be using the “stress” tool in linux.
First and foremost we need to install "stress" tool in our EC2 inatance.connect to the EC2 instance and Run the following commands
sudo apt-get update
sudo apt-get install stress
Use the following command to stress test your CPU
stress --cpu 4 --timeout 300
This example uses 4 CPU workers(number of parallel processes or threads) for 300 seconds(5 mins). You can adjust the number of workers and seconda as it suits you.
Open Slack and wait you should get an alert that looks like this
While running your stress test, you might notice the state of Cloudwatch change to “insufficient data” which might cause the alarm to delay for a bit. To fix this
I trust you found this enjoyable and informative. Should there be any errors or if any part was not explained clearly or you think I missed something, please feel free to reach out. Your feedback is highly valued. Thank You!
the link to the github repository is found Here
The above is the detailed content of Send Slack Notifications with Go AWS Lambda Functions. For more information, please follow other related articles on the PHP Chinese website!