aws terraform cloudwatch 规则作为 lambda 触发器

aws terraform cloudwatch rule as lambda trigger

我正在尝试配置将在特定 day/time 上触发 lambda 函数的 cloudwatch 规则,具体如下:

resource "aws_lambda_function" "cleanup_daily" {
  filename          = "name"
  function_name     = "name"
  role              = "arn<removed>"
  handler           = "snapshotcleanup.lambda_handler"
  source_code_hash  = "${base64sha256(file("file_name"))}"
  runtime           = "python2.7"
  timeout           = "20"
  description       = "desc"
}

resource "aws_cloudwatch_event_rule" "daily_rule" {
  name                = "name"
  description         = "desc"
  schedule_expression = "cron(....)"
}

resource "aws_cloudwatch_event_target" "daily_target" {
  rule  = "${aws_cloudwatch_event_rule.daily_rule.name}"
  arn   = "${aws_lambda_function.cleanup_daily.arn}"
}

但是 lambda 函数没有 运行。如果我查看 lambda 并检查触发器选项卡,那里什么也没有。如果我查看 cloudwatch 规则并查看 Targets 下的 lambda 函数,如果我单击它,我将被重定向到该函数本身。有什么想法这里可能有什么问题吗?

对于其中一个 cloudwatch 规则,我单击了编辑 -> 保存 -> 配置详细信息 -> 更新而不更改任何内容,现在它显示在 lambda 的触发选项卡下,但仍然需要让其他人工作 w/o这一步,

每当不同的 AWS 服务交互时,有必要使用 AWS IAM 授予它们必要的访问权限。

在这种情况下,Cloudwatch Events 必须有权执行相关的 Lambda 函数。

the AWS tutorial describes how to do this using the AWS CLI. The Terraform equivalent of the aws lambda add-permission command is the aws_lambda_permission resource的第2步,可与问题中的配置示例一起使用,如下所示:

data "aws_caller_identity" "current" {
  # Retrieves information about the AWS account corresponding to the
  # access key being used to run Terraform, which we need to populate
  # the "source_account" on the permission resource.
}

resource "aws_lambda_permission" "allow_cloudwatch" {
  statement_id   = "AllowExecutionFromCloudWatch"
  action         = "lambda:InvokeFunction"
  function_name  = "${aws_lambda_function.cleanup_daily.function_name}"
  principal      = "events.amazonaws.com"
  source_account = "${data.aws_caller_identity.current.account_id}"
  source_arn     = "${aws_cloudwatch_event-rule.daily_rule.arn}"
}

AWS Lambda 权限是对 IAM 角色和策略的抽象。有关 IAM 角色和策略的一些一般背景信息,请参阅 my longer answer to another question,其中需要更多手动配置。