可以使用AWS Budgets的Webhooks功能,在警告阈值被触发时向SNS主题发送一个JSON消息。SNS主题可以通过AWS Lambda函数将消息传递给必要的服务或应用程序,并触发必要的操作,比如停止EC2实例或终止ECS任务。
示例代码:
import boto3
# set up AWS credentials and create SNS client
session = boto3.Session(profile_name='my_profile')
sns = session.client('sns', region_name='us-east-1')
# create SNS Topic
sns_topic_arn = sns.create_topic(Name='billing_alert_topic')['TopicArn']
import json
import boto3
def lambda_handler(event, context):
# extract budget details and alert threshold from JSON message
budget_details = event['budget']
alert_threshold = event['alertThreshold']
# check if costs exceeded the alert threshold
cost_exceeds_threshold = float(budget_details['budgetedAndActualAmounts']['actualAmount']) >= float(alert_threshold)
# if costs exceed threshold, terminate EC2 instance with specified instance id
if cost_exceeds_threshold:
instance_id = 'i-12345'
ec2 = boto3.resource('ec2', region_name='us-east-1')
ec2.Instance(instance_id).terminate()
将SNS主题绑定到Budgets预算提醒操作的Webhook中,并指定Lambda函数作为处理程序。
手动修改预算并使其超过警告阈值,触发Lambda函数并自动在AWS中终止EC2实例。