如何将 AWS cloudwatch 事件添加到基于带有 terraform 的容器映像的 aws_lambda_function?

How can I add a AWS cloudwatch event to a aws_lambda_function which is based on a container image with terraform?

我想实现我的基于 ecr 中 docker 图像的 lambda 函数是由计划的 cloudwatch 事件触发的。

问题是我无法从模块“lambda_function_container_image”附加 function_name myFunctionaws_lambda_permission.

当我有一个正常的 lambda 函数时它可以工作,但不能使用来自图像 URI 的 lambda 函数:

resource "aws_lambda_function" "myFunction" {
 
  function_name = "myFunction"
  role          = aws_iam_role.lambda_execution_role.arn
  handler       = "exports.handler"
  runtime       = "python3.8"
}

我有以下代码:

AWS CloudWatch 事件:

resource "aws_cloudwatch_event_rule" "every_five_minutes" {
    name = "every-five-minutes"
    description = "Fires every five minutes"
    schedule_expression = "rate(5 minutes)"
}

基于容器镜像的 Lambda 函数:

module "lambda_function_container_image" {
  source = "terraform-aws-modules/lambda/aws"

  function_name = "myFunction"
  description   = "awesome function"

  create_package = false

  image_uri    = "${data.aws_caller_identity.current.account_id}.dkr.ecr${var.aws_region}.amazonaws.com/container_name"
  package_type = "Image"
}

Lambda 权限:

resource "aws_lambda_permission" "allow_cloudwatch_to_call_myFunction" {
  statement_id  = "AllowExecutionFromCloudWatch"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.myFunction.function_name
  principal     = "events.amazonaws.com"
  source_arn    = aws_cloudwatch_event_rule.every_five_minutes.arn
}

当前 aws_lambda_permission 出现以下错误:

错误信息:

Error: Reference to undeclared resource
-> points to function_name in aws_lambda_permission

您需要通过您正在使用的 module 引用 function_name。根据 terraform-aws-modules/lambda/aws 的文档,该模块有一个名为 lambda_function_name.

的输出

这意味着,以下内容应该适合您:

resource "aws_lambda_permission" "allow_cloudwatch_to_call_myFunction" {
  [...]

  function_name = module.lambda_function_container_image.lambda_function_name

  [...]
}