Skip to content

Eventbridge trigger with cloud trail event

0

i want to send a sns notification whenver a new ami is created in a specific name i thought of using event bridge rule to get the createImage event and send sns i defined the rule as below and sns id configured proeprly. But when ever i create the ami it not working, no sns mail sent

resource "aws_cloudwatch_event_rule" "ami_creation_rule" {
  name        = "detect-ami-creation"
  description = "Detects the creation of AMIs with the name AMI-checking"
  event_pattern = jsonencode({
    "source": ["aws.ec2"],
    "detail-type": ["AWS API Call via CloudTrail"],
    "detail": {
      "eventSource": "ec2.amazonaws.com",
      "eventName": "CreateImage",
      "requestParameters": {
        "name": "AMI-checking"# AMI name to detect
      }
    }
  })
}
2 Answers
1

In EventBridge event patterns, string matching is done with arrays, with the square bracket syntax [ ]. You also seem to have JSON syntax inside a json_encode() function call, but I believe the purpose of the function is to be able to describe the structure as a Terraform object and to have the function convert it to JSON syntax.

I'd suggest starting with formatting the rule and json_encode() function call in the way that is shown in the documentation examples: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_event_rule#example-usage

You'll need to make sure that the string literals you want the pattern to match are provided as arrays.

One of the comparisons would be, for example,

name = ["AMI-checking"]

instead of without square brackets that an array would require as:

name = "AMI-checking"

or in JSON notation:

"name": "AMI-checking"

I haven't got Terraform set up to test this, but I think the rule would look something like this:

resource "aws_cloudwatch_event_rule" "ami_creation_rule" {
  name        = "detect-ami-creation"
  description = "Detects the creation of AMIs with the name AMI-checking"
  event_pattern = jsonencode({
    source = ["aws.ec2"]
    detail-type = ["AWS API Call via CloudTrail"]
    detail = {
      eventSource = ["ec2.amazonaws.com"]
      eventName = ["CreateImage"]
      requestParameters {
        name = ["AMI-checking"]
      }
    }
  })
}
EXPERT
answered 9 months ago
EXPERT
reviewed 9 months ago
  • I came to the same conclusion. The answer is spot on.

0

Hi,

you have a full example for another service (SQS CreateQueue) in this article: https://repost.aws/knowledge-center/automate-eventbridge-rule-cloudtrail-api

Best,

Didier

AWS
EXPERT
answered 9 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.