Skip to content

Instantly share code, notes, and snippets.

@chalisekrishna418 chalisekrishna418/main.go Secret
Created Nov 9, 2019

Embed
What would you like to do?
Lambda to read SNS event and send message to Slack using incoming webhook.
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
// NotifySlack sends message to Slack reading context
func NotifySlack(ctx context.Context, snsEvent events.SNSEvent) error {
var data map[string]string
var attachment string
for _, record := range snsEvent.Records {
snsRecord := record.SNS
fmt.Printf("[%s %s] Message = %s \n", record.EventSource, snsRecord.Timestamp, snsRecord.Message)
attachment = snsRecord.Message
}
json.Unmarshal([]byte(attachment), &data)
webhookURL := "https://hooks.slack.com/services/XXXXXXXXXXX/YYYYYYYYYYY/ZZZZZZZZZZZZZZZZZZZZZZZ"
requestBody, err := json.Marshal(map[string]interface{}{
"text": "*" + data["NewStateValue"] + ":* " + data["AlarmName"],
"blocks": []interface{}{
map[string]interface{}{
"type": "section",
"text": map[string]string{
"type": "mrkdwn",
"text": "*RDS Free Storage Notification* \n" +
"*" + data["NewStateValue"] + ":* " + data["AlarmName"],
},
},
map[string]interface{}{
"type": "section",
"text": map[string]string{
"type": "mrkdwn",
"text": "> *AccountId:* " + data["AWSAccountId"] + "\n" +
"> *AWS Region:* " + data["Region"] + "\n" +
"> *Reason:* " + data["NewStateReason"],
},
},
},
})
if err != nil {
fmt.Printf("%s", err)
return err
}
resp, err := http.Post(webhookURL, "application/json", bytes.NewBuffer(requestBody))
if err != nil {
fmt.Printf("%s", err)
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Print(string(body))
return nil
}
func main() {
lambda.Start(NotifySlack)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.