Skip to content

Instantly share code, notes, and snippets.

@cyuste
Last active February 25, 2021 21:26
Show Gist options
  • Save cyuste/2908b285bd8d9b0fa0689ec2d90183d6 to your computer and use it in GitHub Desktop.
Save cyuste/2908b285bd8d9b0fa0689ec2d90183d6 to your computer and use it in GitHub Desktop.
alarms using ec2 actions
import * as cdk from "@aws-cdk/core";
import getEnv from "../../config";
import * as ec2 from "@aws-cdk/aws-ec2";
import * as sns from "@aws-cdk/aws-sns";
import * as cw from "@aws-cdk/aws-cloudwatch";
import { EmailSubscription } from "@aws-cdk/aws-sns-subscriptions";
import { SnsAction, Ec2InstanceActions, Ec2Action } from "@aws-cdk/aws-cloudwatch-actions";
import { Stack, StackProps, Duration } from "@aws-cdk/core";
export class TestStack extends Stack {
constructor(
scope: cdk.Construct,
id: string,
props: StackProps
) {
super(scope, id, props);
// VPC
const vpc = ec2.Vpc.fromLookup(this, "import-vpc", {
vpcName: getEnv(this, "vpcName"),
});
//SG
const securityGroup = new ec2.SecurityGroup(this, "ec2-sg-common", {
vpc,
});
securityGroup.addIngressRule(
ec2.Peer.ipv4("192.168.0.0/16"),
ec2.Port.tcp(22),
"Allow ssh Traffic"
);
const instance = new ec2.Instance(this, id, {
instanceType: new ec2.InstanceType("t2.nano"),
vpc: vpc,
machineImage: ec2.MachineImage.lookup({
name: getEnv(this, "amiMaster"),
owners: [getEnv(this, "amiAccount"),],
}),
keyName: 'vy-qa',
securityGroup
});
// Alarm creation
const alarm = new cw.Alarm(this, "statusAlarm", {
metric: new cw.Metric({
namespace: "AWS/EC2",
metricName: "StatusCheckFailed",
dimensions: {
InstanceId: instance.instanceId,
},
period: Duration.minutes(5),
statistic: "max",
}),
threshold: 0.5,
evaluationPeriods: 1,
});
// When alarm goes from OK to KO, it will trigger REBOOT action
alarm.addAlarmAction(
new Ec2Action(Ec2InstanceActions.REBOOT)
);
// SNS topic creation that will send an email on Publish event
const autorecoveryTopic = new sns.Topic(this, "AutorecoveryTopic", {
displayName: "Autorecovery Alarms",
});
autorecoveryTopic.addSubscription(
new EmailSubscription("[email protected]")
);
const emailAction = new SnsAction(autorecoveryTopic);
// Alarm will publish in SNS topic when its triggered (OK->KO) and comes back to normal (KO->OK)
alarm.addAlarmAction(emailAction);
alarm.addOkAction(emailAction);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment