将terraform cloudwatch规则作为lambda触发器

时间:2017-05-31 14:14:51

标签: amazon-web-services aws-lambda amazon-cloudwatch terraform

我正在尝试使用以下内容配置在特定日期/时间触发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规则 - &gt;保存 - &gt;配置详细信息 - &gt;更新而不更改任何东西,现在显示在lambda的触发器选项卡下,但仍然需要让其他人无法在此步骤中工作,

1 个答案:

答案 0 :(得分:6)

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

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

the AWS tutorial的第2步介绍了如何使用AWS CLI执行此操作。 Terraform等效的aws lambda add-permission命令是the aws_lambda_permission resource,可以与问题中的配置示例一起使用,如下所示:

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,其中需要更多手动配置。