首页 文章

将terraform cloudwatch规则作为lambda触发器

提问于
浏览
2

我正在尝试使用以下内容配置在特定日期/时间触发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的触发器选项卡下,但仍然需要让其他人无法使用此步骤,

1 回答

  • 6

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

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

    the AWS tutorial的第2步描述了如何使用AWS CLI执行此操作 . aws lambda add-permission 命令的Terraform等效项是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,其中需要更多手动配置 .

相关问题