Skip to content

Instantly share code, notes, and snippets.

@mhemmings
Last active February 2, 2018 14:48
Show Gist options
  • Save mhemmings/09c2f4b06e959b5ddd312fcf4fdf67b7 to your computer and use it in GitHub Desktop.
Save mhemmings/09c2f4b06e959b5ddd312fcf4fdf67b7 to your computer and use it in GitHub Desktop.
Bulk create Cloudwatch alarms for 4xx/5xx API Gateway errors.
package main
import (
"fmt"
"log"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatch"
)
const (
Error4xx = "4XXError"
Error5xx = "5XXError"
)
type API struct {
Name string
Stages []Stage
}
type Stage struct {
Name string
Threshold4xx int64
Threshold5xx int64
}
var SNSARN = "arn:aws:sns:eu-west-1:<account>:<snsname>"
var apis = []API{
{
Name: "api",
Stages: []Stage{
{
Name: "staging",
Threshold4xx: 0,
Threshold5xx: 0,
},
{
Name: "production",
Threshold4xx: 20,
Threshold5xx: 0,
},
},
},
}
func main() {
var err error
svc := cloudwatch.New(session.New())
for _, api := range apis {
for _, stage := range api.Stages {
input4xx := makeInput(api.Name, stage.Name, Error4xx, stage.Threshold4xx)
_, err = svc.PutMetricAlarm(input4xx)
if err != nil {
log.Fatalf("Error creating %s %s 4xx: %v", api.Name, stage.Name, err)
}
input5xx := makeInput(api.Name, stage.Name, Error5xx, stage.Threshold5xx)
_, err = svc.PutMetricAlarm(input5xx)
if err != nil {
log.Fatalf("Error creating %s %s 5xx: %v", api.Name, stage.Name, err)
}
}
}
}
func makeInput(api string, stage string, metric string, threshold int64) *cloudwatch.PutMetricAlarmInput {
description := "Any"
if threshold > 0 {
description = "Elevated"
}
description = fmt.Sprintf("%s %s on %s [%s]", description, metric, api, stage)
return &cloudwatch.PutMetricAlarmInput{
AlarmActions: []*string{aws.String(SNSARN)},
AlarmDescription: aws.String(description),
AlarmName: aws.String(fmt.Sprintf("apigateway-%s-%s-%s", api, stage, strings.ToLower(metric))),
ComparisonOperator: aws.String("GreaterThanThreshold"),
Dimensions: []*cloudwatch.Dimension{
{
Name: aws.String("ApiName"),
Value: aws.String(api),
},
{
Name: aws.String("Stage"),
Value: aws.String(stage),
},
},
EvaluationPeriods: aws.Int64(1),
MetricName: aws.String(metric),
Namespace: aws.String("AWS/ApiGateway"),
Period: aws.Int64(60),
Statistic: aws.String("Sum"),
Threshold: aws.Float64(float64(threshold)),
TreatMissingData: aws.String("notBreaching"),
Unit: aws.String("Count"),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment