Pulumi:如何为存储库创建 CloudWatch 事件规则

Pulumi: how to create a CloudWatch event rule for a repository

我正在尝试使用 Cloudwatch 从特定的 ECR 存储库捕获 PutImage 事件以触发 Lambda。

我的问题是 eventPattern 被输入为 'string':

export const myTestRepo = ECRTemplate('my-test-repo');

export const eventRule = new aws.cloudwatch.EventRule("putimagerule", {
    eventPattern: JSON.stringify({
        "detail-type": [
            "AWS API Call via CloudTrail"
        ],
        "source": ["aws.ecr"],
        "detail": {
            "eventName": ["PutImage"],
            "repositoryName": [myTestRepo.repository.name]
        }
    }),
});

结果事件规则如下所示:

{
   "detail":{
      "eventName":[
         "PutImage"
      ],
      "repositoryName":[
         "Calling [toJSON] on an [Output\u003cT\u003e] is not supported.\n\nTo get the value of an Output as a JSON value or JSON string consider either:\n    1: o.apply(v =\u003e v.toJSON())\n    2: o.apply(v =\u003e JSON.stringify(v))\n\nSee https://pulumi.io/help/outputs for more details.\nThis function may throw in a future version of @pulumi/pulumi."
      ]
   },
   "detail-type":[
      "AWS API Call via CloudTrail"
   ],
   "source":[
      "aws.ecr"
   ]
}

对象 myTestRepo 包含一个有效的存储库并且不是问题的一部分,为什么它不包括在这里。

问:如何捕获特定存储库的 PutImage

问题出在行 "repositoryName": [myTestRepo.repository.name]

尝试

export const myTestRepo = ECRTemplate('my-test-repo');

export const eventRule = new aws.cloudwatch.EventRule("putimagerule", {
    eventPattern: {
        "detail-type": [
            "AWS API Call via CloudTrail"
        ],
        "source": ["aws.ecr"],
        "detail": {
            "eventName": ["PutImage"],
            "repositoryName": [myTestRepo.repository.name.apply(v => v.toJSON()]
        }
    });

问题是由 myTestRepo.repository.name 的类型引起的:它不是 string,而是 pulumi.Output<string>。它的值在程序第一次运行时是未知的,所以你不能在字符串插值中使用它。

相反,您可以使用 apply 函数:

const eventRule = new aws.cloudwatch.EventRule("putimagerule", {
    eventPattern: myTestRepo.repository.name.apply(repositoryName =>
        JSON.stringify({
          "detail-type": [
              "AWS API Call via CloudTrail",
          ],
          "source": ["aws.ecr"],
          "detail": {
              eventName: ["PutImage"],
              repositoryName: [repositoryName],
          },
    })),
});

您可以在 Outputs and Inputs 文档中了解更多信息。