配置 CloudWatch Events 以使用 Terraform 将输入发送到 Lambda 函数

Posted

技术标签:

【中文标题】配置 CloudWatch Events 以使用 Terraform 将输入发送到 Lambda 函数【英文标题】:Configure CloudWatch Events to send input to Lambda function with Terraform 【发布时间】:2020-04-10 04:04:03 【问题描述】:

我想。 我使用了以下脚本:

resource "aws_cloudwatch_event_rule" "aa-rule-event" 
  count               = "$var.count"
  name                = "$var.application_name-$element(var.names, count.index)"
  description         = "$element(var.descriptions, count.index)"
  schedule_expression = "$element(var.cron-expressions, count.index)"
  is_enabled          = "$element(var.rule-status-states, count.index)"


resource "aws_cloudwatch_event_target" "aa-rule-target" 
  count     = "$var.count"
  rule      = "$var.application_name-$element(var.names, count.index)"
  target_id = "CloudWatchToLambda"
  arn       = "arn:aws:lambda:$var.aws_region:$var.aws_account_number:function:$var.application_name-$element(var.target-lambda-function, count.index)"

我需要通过此 CloudWatch 事件向目标 Lambda 提供输入。我知道可以配置输入,但是如何在 Terraform 中配置呢?

【问题讨论】:

【参考方案1】:

aws_cloudwatch_event_target 资源采用可选的input parameter,它可以在调用 Lambda 函数时将 JSON blob 传递给与有效负载等效的目标。

resource "aws_cloudwatch_event_rule" "aa-rule-event" 
  count               = "$var.count"
  name                = "$var.application_name-$element(var.names, count.index)"
  description         = "$element(var.descriptions, count.index)"
  schedule_expression = "$element(var.cron-expressions, count.index)"
  is_enabled          = "$element(var.rule-status-states, count.index)"


resource "aws_cloudwatch_event_target" "aa-rule-target" 
  count     = "$var.count"
  rule      = "$var.application_name-$element(var.names, count.index)"
  target_id = "CloudWatchToLambda"
  arn       = "arn:aws:lambda:$var.aws_region:$var.aws_account_number:function:$var.application_name-$element(var.target-lambda-function, count.index)"
  input = <<JSON

  "foo": 
    "bar": [
      1,
      2
    ]
  

JSON

【讨论】:

我试过这个,但似乎无法在 lambda 函数(用 Go 编写)中检索输入值。是在某个地方的上下文中吗? 天哪!我的 func 处理程序签名错误——输入作为处理程序的第二个参数(不在上下文中),但它必须是正确的类型!我最初将 events.SNSEvent 作为类型(更典型),但在这种情况下,我使用的是自定义类型。

以上是关于配置 CloudWatch Events 以使用 Terraform 将输入发送到 Lambda 函数的主要内容,如果未能解决你的问题,请参考以下文章