Search code examples
amazon-web-servicesamazon-cloudwatchaws-ecrpulumi

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


I am trying to capture PutImage event from a specific ECR repository using Cloudwatch to trigger a Lambda.

My problem is with eventPattern being typed as '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]
        }
    }),
});

and a resulting event rule looks like this:

{
   "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"
   ]
}

Object myTestRepo contains a valid Repository and is not a part of the problem that why it is not included here.

Q: How to catch PutImage for a specific repository?


Solution

  • The problem is caused by the type of myTestRepo.repository.name: it's not a string but a pulumi.Output<string>. Its value is unknown at the time when the program first runs, so you can't use it inside string interpolation.

    Instead, you can use apply function:

    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],
              },
        })),
    });
    

    You can learn more in the Outputs and Inputs docs.