How to stop all idle EC2 instances using AWS Lambda

0 votes
import boto3
def put_cpu_alarm(instance_id):
    cloudWatch   = boto3.client('cloudwatch')
    cloudWatch.put_metric_alarm(
        AlarmName          = f'CPU_ALARM_{instance_id}',
        AlarmDescription   = 'Alarm when server CPU does not exceed 10%',
        AlarmActions       = ['arn:aws:automate:us-east-1:ec2:stop'],
        MetricName         = 'CPUUtilization',
        Namespace          = 'AWS/EC2' ,
        Statistic          = 'Average',
        Dimensions         = [{'Name': 'InstanceId', 'Value': instance_id}],
        Period             = 300,
        EvaluationPeriods  = 3,
        Threshold          = 10,
        ComparisonOperator = 'LessThanOrEqualToThreshold',
        TreatMissingData   = 'notBreaching'
    )
def lambda_handler(event, context):
    instance_id = event['detail']['instance-id']
    ec2 = boto3.resource('ec2')
    instance = ec2.Instance(instance_id)
    put_cpu_alarm(instance_id)

Event pattern in Cloudwatch Rule

{
  "source": [
    "aws.ec2"
  ],
  "detail-type": [
    "EC2 Instance State-change Notification"
  ],
  "detail": {
    "state": [
      "running"
    ]
  }
}

Error I am getting,

[ERROR] KeyError: 'detail'
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 19, in lambda_handler
    instance_id = event['detail']['instance-id']

Expecting result:

Detect and stop EC2 idle instances.
Aug 13 in AWS by ushasree
390 views

1 answer to this question.

+1 vote
Please, provide instance ID there.
answered Aug 20 by Yash Verma
 instance_id = event['detail']['instance-id']

'instance_id' will have the ID of the instance but what should I mention in the 'detail' section?

Related Questions In AWS

0 votes
1 answer

How to set-up DynamoDB trigger using AWS Lambda?

Well this code worked for me. You ...READ MORE

answered Aug 20, 2018 in AWS by Archana
• 4,110 points
779 views
0 votes
1 answer

How to access AWS Lambda environment variables using Java?

In Spring Core change the PropertySourcesPlaceholderConfigurer class can ...READ MORE

answered Oct 24, 2018 in AWS by Priyaj
• 57,300 points
832 views
0 votes
1 answer

How to Pass the VPC ID while creating the Ec2 instance in AWS using Python Boto3

import boto3 ec2 = boto3.resource('ec2') instance = ec2.create_instances( ...READ MORE

answered Jan 29 in AWS by Priyaj
• 57,300 points
427 views
0 votes
1 answer
0 votes
1 answer