简体   繁体   中英

Create a cloudwatch event rule target to a lambda function with different inputs in Terraform

I created a CloudWatch event rule to trigger a lambda function to run in schedule. Howerver, I want the rule run with 2 different input values.

Eg: input1 is: {"namequery": "top-10-ip", "s3bucket": "stg-log", "query": "SELECT client_ip from ip_tables limit 10"}

and input2 is: {"namequery": "countError", "s3bucket": "stg-log", "query": "SELECT error from error_logs"}

My expected result is like this image: expected result

My Terraform code:

resource "aws_cloudwatch_event_rule" "athena_sender" {
  name                = "${var.app_name}-${var.env_name}-lambda-athena-sender"
  description         = "${var.app_name}-${var.env_name} athena sender"
  schedule_expression = var.options_athena_sender["schedule_expression"]
}

resource "aws_cloudwatch_event_target" "athena_sender1" {
  rule      = aws_cloudwatch_event_rule.athena_sender.name
  target_id = aws_lambda_function.athena_sender_function.id
  arn       = aws_lambda_function.athena_sender_function.arn
  input     = <<JSON
    {
      "namequery": "${var.options_athena_sender["namequery1"]}",
      "s3bucket": "${aws_s3_bucket.s3_logs.bucket}",
      "query": "${var.options_athena_sender["query1"]}"
    }
  JSON
}

resource "aws_cloudwatch_event_target" "athena_sender2" {
  rule      = aws_cloudwatch_event_rule.athena_sender.name
  target_id = aws_lambda_function.athena_sender_function.id
  arn       = aws_lambda_function.athena_sender_function.arn
  input     = <<JSON
    {
      "namequery": "${var.options_athena_sender["namequery2"]}",
      "s3bucket": "${aws_s3_bucket.s3_logs.bucket}",
      "query": "${var.options_athena_sender["query2"]}"
    }
  JSON

  depends_on = [aws_cloudwatch_event_target.athena_sender1]  // delay creation of the second athena sender CW event to prevent ConcurrentModificationException
}

However, it sounds like Terraform do not recognize the differences and it only create only 1 target.

Hope that anyone can help me, thank you so much!

This probably happens because you are using same target_id in both cases:

target_id = aws_lambda_function.athena_sender_function.id

Please change it to have different ids for different rules, eg:

target_id = "${aws_lambda_function.athena_sender_function.id}1"

and

target_id = "${aws_lambda_function.athena_sender_function.id}2"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM