MCPcopy Create free account
hub / github.com/aws-samples/aws-cdk-examples / handler

Function handler

python/ec2-alarms-to-opsitem/lambda/alarm.py:10–66  ·  view source on GitHub ↗
(event, context)

Source from the content-addressed store, hash-verified

8logger.setLevel(logging.INFO)
9
10def handler(event, context):
11 logger.info(event)
12 alarm_action_str = 'arn:aws:sns:' + os.environ['region'] + ':' + os.environ['acct'] + ':' + os.environ['topic']
13 instanceid = event['detail']['instance-id']
14
15 ec2 = boto3.client('ec2')
16
17 try:
18 response = ec2.describe_instances(
19 Filters=[
20 {
21 'Name': 'tag:OpsItemAlarm',
22 'Values': ['false',]
23 },
24 ],
25 InstanceIds=[instanceid],
26 DryRun=False
27 )
28 except:
29 logger.info("Exception")
30
31 logger.info(response)
32
33 contflag = len(response['Reservations'])
34 if contflag == 0:
35 print("No instance found or already properly tagged: " + instanceid)
36 else:
37 print(response['Reservations'])
38 cloudwatch = boto3.client('cloudwatch')
39 response = cloudwatch.put_metric_alarm(
40 AlarmName= 'StatusCheckFailed' + '-' + instanceid,
41 ComparisonOperator="GreaterThanThreshold",
42 EvaluationPeriods=1,
43 TreatMissingData="notBreaching",
44 MetricName="StatusCheckFailed",
45 Namespace="AWS/EC2",
46 Period=300,
47 Statistic="Average",
48 Threshold=1.0,
49 ActionsEnabled=True,
50 AlarmActions=[alarm_action_str],
51 AlarmDescription='Alarm Ec2 StatusCheckFails',
52 Dimensions=[{
53 'Name': "InstanceId",
54 'Value': instanceid},],
55 Unit='Seconds'
56 )
57 response = ec2.create_tags(
58 Resources=[instanceid],
59 Tags=[
60 {
61 'Key': 'OpsItemAlarm',
62 'Value': 'Yes',
63 },
64 ]
65 )
66 print("Tag Updated for instance: " + instanceid)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected