我一直在ECS上运行容器,并在任务完成时使用AWS Cloudwatch事件通知我。所有基础结构都是使用Terraform创建的。但是,我无法在事件模式中获得正确的语法,因此仅通知我非零退出代码。
以下资源非常有用,每次我的一个容器退出时,它都会向SNS发送通知:
resource "aws_cloudwatch_event_rule" "container-stopped-rule" {
name = "container-stopped"
description = "Notification for containers that exit for any reason. (error)."
event_pattern = <<PATTERN
{
"source": [
"aws.ecs"
],
"detail-type": [
"ECS Task State Change"
],
"detail": {
"lastStatus": [
"STOPPED"
],
"stoppedReason" : [
"Essential container in task exited"
]
}
}
PATTERN
}
但是,我正在尝试略微修改模式,以便仅在容器退出并显示错误代码时通知我-由于我们收到的通知太多,我们已经开始调出电子邮件,有时却不t注意到容器错误退出的电子邮件通知:
resource "aws_cloudwatch_event_rule" "container-stopped-rule" {
name = "container-stopped"
description = "Notification for containers with exit code of 1 (error)."
event_pattern = <<PATTERN
{
"source": [
"aws.ecs"
],
"detail-type": [
"ECS Task State Change"
],
"detail": {
"containers": [
{
"exitCode": 1
}
],
"lastStatus": [
"STOPPED"
],
"stoppedReason" : [
"Essential container in task exited"
]
}
}
PATTERN
}
这在我terraform apply
时触发以下错误:
aws_cloudwatch_event_rule.container-stopped-rule:更新CloudWatch 事件规则失败:InvalidEventPatternException:事件模式不正确 有效。原因:匹配值必须为String,number,true,false或 在[来源:null (String)“ {” detail“:{” containers“:[{” exitCode“:1}],” lastStatus“:[” STOPPED“],” stoppedReason“:[” Essential 任务中退出的容器“]},”详细类型“:[” ECS任务状态 更改“],”源“:[” aws.ecs“]}”;行:1,列:27]状态码: 400
这让我感到困惑,因为我遵循AWS CloudWatch documentation for containers中列出的确切结构。我什至尝试在1
周围加上双引号,以防Terraform需要字符串而不是数字。
我还尝试使用AWS Console手动编辑事件模式JSON,但收到此错误:
验证错误。详细信息:事件模式包含无效值(可以 只能是非空数组或非空对象)
老实说,我在这方面有些困惑,不胜感激我的语法不正确的任何提示。
答案 0 :(得分:4)
事件模式语法很奇怪,我遇到了同样的问题。以下将起作用:
{
"source": [
"aws.ecs"
],
"detail-type": [
"ECS Task State Change"
],
"detail": {
"lastStatus": [
"STOPPED"
],
"stoppedReason": [
"Essential container in task exited"
],
"containers": {
"exitCode": [
1
]
}
}
}
我在Input Transformer中使用$.detail.group
在通知消息中获取任务族名称。
答案 1 :(得分:1)
根据https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/CloudWatchEventsandEventPatterns.html,
For a pattern to match an event, the event must contain all the field names listed in the pattern. The field names must appear in the event with the same nesting structure.
您可以尝试在此处https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_cwe_events.html像clusterArn
,containerInstanceArn
等添加更多字段列表器吗?