如何使用AWS Lambda停止所有空闲的EC2实例

时间:2019-07-19 11:55:29

标签: amazon-web-services amazon-ec2 aws-lambda

我正在尝试停止空闲30分钟的AWS EC2实例。我无法从cloudwatch获取实例ID。

我完全像这样link

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)   

Cloudwatch规则中的事件模式

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

错误

[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']

期望结果

Detect and stop EC2 idle insatnces.

0 个答案:

没有答案