概述
AWS 成本预算把实际或预测支出与固定金额比较,越过阈值时发送通知,但不会停止资源。它的价值是给团队争取发现异常负载的时间;真正限制花费还需要 SCP 或服务配额。建议同时配置两个通知:实际支出达到 80% 时提前预警,预测月末支出达到 100% 时提示趋势。预测告警在阈值附近可能反复触发,应把预测通知发到成本评审渠道,而不是直接当作值班告警。
步骤
在 infra/budget 中创建 Terraform 模块,固定 AWS provider 版本,并定义 alert_email 和 monthly_limit_usd 变量。先运行:
terraform -chdir=infra/budget init
创建 SNS 主题、邮件订阅,以及只允许本账户 Budgets 服务发布、同时保留账户所有者管理权限的主题策略。策略中 principal 为 budgets.amazonaws.com,并用 aws:SourceAccount 限制账户:
resource "aws_sns_topic" "budget_alerts" {
name = "monthly-cost-budget-alerts"
}
resource "aws_sns_topic_subscription" "email" {
topic_arn = aws_sns_topic.budget_alerts.arn
protocol = "email"
endpoint = var.alert_email
}
resource "aws_budgets_budget" "monthly" {
name = "monthly-account-budget"
budget_type = "COST"
limit_amount = tostring(var.monthly_limit_usd)
limit_unit = "USD"
time_unit = "MONTHLY"
depends_on = [aws_sns_topic_policy.budget_alerts]
notification {
comparison_operator = "GREATER_THAN"
threshold = 80
threshold_type = "PERCENTAGE"
notification_type = "ACTUAL"
subscriber_sns_topic_arns = [aws_sns_topic.budget_alerts.arn]
}
notification {
comparison_operator = "GREATER_THAN"
threshold = 100
threshold_type = "PERCENTAGE"
notification_type = "FORECASTED"
subscriber_sns_topic_arns = [aws_sns_topic.budget_alerts.arn]
}
}
depends_on 确保主题策略先于预算创建,避免 Budgets 校验发布权限时策略尚未生效。应用时传入真实邮箱:
terraform -chdir=infra/budget apply -var="alert_email=$ALERT_EMAIL" -var="monthly_limit_usd=500"
验证
用 aws budgets describe-budget 确认名称、500 USD 限额和 MONTHLY 周期;用 aws sns list-subscriptions-by-topic 确认邮件订阅已从 PendingConfirmation 变为已确认。再执行一次 aws sns publish 发送测试消息,确认邮箱能收到。这只验证 SNS 投递,不能证明 Budgets 服务有发布权限;还需要主题策略和一次真实阈值触发来覆盖完整链路。可在沙箱账户临时把限额设到当前支出以下,等待下一次预算评估。
注意事项
预算数据每天只刷新数次,不是实时计费。账户级预算无法指出是哪个团队或服务超支,应配合成本标签、服务过滤或 Cost Anomaly Detection。不要把预算当作沙箱账户的唯一花费控制,也不要把告警发给已经离职的邮箱。SNS 邮件不适合作为值班通道,生产环境应订阅 HTTPS 端点并接入 PagerDuty 或 Slack。