[英]How to stop all idle EC2 instances using AWS Lambda
我一直在嘗試檢測並關閉空閑的 AWS EC2 實例(<10% CPU)。
Lambda 代碼(使用 IAM 角色 AmazonEC2FullAccess 設置):
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']
期待結果:
檢測並停止 EC2 空閑運行實例。
傳遞給 AWS Lambda function 的event
參數包含多個Records
。 您可以通過使用print(event)
調試 function 來查看這一點。
因此,您的代碼應該遍歷每個Record
:
def lambda_handler(event, context):
for record in event['Records']:
instance_id = record['detail']['instance-id']
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.