无法从 SNS 触发 AWS Lambda

Unable to trigger AWS Lambda from SNS

我正在尝试从 SNS codestar-notifications .

创建 AWS lambda 触发器

在使用控制台创建触发器时,它会自动添加对 SNS 主题的订阅。 。此外,这在另一个方向上起作用,即如果我通过显式添加其 arn 为 SNS 创建订阅作为 Lambda 函数,它会自动将触发器链接到 Lambda 函数。

但是当使用 terraform 创建如下订阅时:

resource "aws_sns_topic_subscription" "subscribe_lambda_to_first_topic" {
  topic_arn = module.first_topic.sns-topic-detail.arn
  protocol  = "lambda"
  endpoint  = module.lambda_function.lambda_function.arn
}

它不会在 AWS Lambda 中创建触发器。

我尝试使用 Terraform 中的事件源映射创建触发器,如下所示

resource "aws_lambda_event_source_mapping" "lambda_source" {
 event_source_arn  = module.first_topic.sns-topic-detail.arn
 function_name     = module.lambda_function.lambda_function.arn
 starting_position = "LATEST"
}

它给我一个错误,说它只适用于

Error: error creating Lambda Event Source Mapping (arn:aws:sns:us-west-2:619867110810:codestar-notifications-emc-sns-to-lambda): InvalidParameterValueException: Unrecognized event source, must be kinesis, dynamodb stream or sqs. Unsupported source arn : arn:aws:sns:us-west-2:619867110810:codestar-notifications-emc-sns-to-lambda { RespMetadata: { StatusCode: 400, RequestID: "83bf57cb-b50d-49a8-9547-72fac69778d1" }, Message_: "Unrecognized event source, must be kinesis, dynamodb stream or sqs. Unsupported source arn : arn:aws:sns:us-west-2:619867110810:codestar-notifications-emc-sns-to-lambda", Type: "User" }

with aws_lambda_event_source_mapping.lambda_source, on main.tf line 43, in resource "aws_lambda_event_source_mapping" "lambda_source": 43: resource "aws_lambda_event_source_mapping" "lambda_source" {

aws_lambda_event_source_mapping 不适用于 SNS,就像错误消息所说的那样。相反,您像以前一样使用 aws_sns_topic_subscription

但是,您忘记了 aws_lambda_permission 应该是(来自文档的通用形式 - 您需要根据自己的设置进行调整):

resource "aws_lambda_permission" "with_sns" {
  statement_id  = "AllowExecutionFromSNS"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.func.function_name
  principal     = "sns.amazonaws.com"
  source_arn    = aws_sns_topic.default.arn
}