How to stop all idle EC2 instances using AWS Lambda

+1 vote
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, 2019 in AWS by ushasree
4,605 views

2 answers to this question.

+1 vote
Please, provide instance ID there.
answered Aug 20, 2019 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?

+1 vote
Nice article, very informative!

I have a scenario where I am trying to Start/Stop EC2 Instance based on CPU Utilization of another EC2 Instance.

The scenario is:

 Start/Stop EC2 say instance Id: B from Lambda based on CPU utilization of different EC2 Instance Id: A  e.g.
1-EC2 - A CPU Utilization LT 20% - Stop EC2- B
2- EC2- A CPU Utilization GR 80% - Start EC2 - A
I tried CloudWatch Alarm but stop/start the same EC2 instance rather than different EC2 instance. I created Cloudwathc Rule to tridger Lambda from where I will Start/Stop EC2 instance(s) but Rule doesn't provide CPU Utilization based event triger rather on Scheduled Date/Time.
Do you have any experience or know any material/link where the similar work has been done.
I will really appreciate your help and prompt response.
Thanks
answered Jan 14, 2020 by Hamid
• 160 points
Hi, @Hamid Hassan

Can you please post this as another separate question?

Related Questions In AWS

0 votes
1 answer

How to stop EC2 instances using Boto3?

Hi@akhtar, To change the state of an EC2 ...READ MORE

answered Oct 7, 2020 in AWS by MD
• 95,460 points
2,278 views
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,170 points
2,840 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
• 58,020 points
2,790 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, 2019 in AWS by Priyaj
• 58,020 points
3,549 views
0 votes
1 answer
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP