Skip to content

Instantly share code, notes, and snippets.

@chalisekrishna418
Created November 9, 2019 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chalisekrishna418/842659520b1d38c0eb61993a2437f33b to your computer and use it in GitHub Desktop.
Save chalisekrishna418/842659520b1d38c0eb61993a2437f33b to your computer and use it in GitHub Desktop.
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