Terraform AWS S3到Lambda通知触发器

时间:2018-09-21 17:43:33

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

我正在尝试编码要使用S3触发的lambda函数。 Lambda函数的创建成功,但是“ aws_s3_bucket_notification”资源在terraform:apply失败,错误为MethodNotAllowed,错误为status code 405

Error: Error applying plan:
20-Sep-2018 15:23:53    1 error(s) occurred:
20-Sep-2018 15:23:53    * aws_s3_bucket_notification.my-trigger: 1 error(s) occurred:
20-Sep-2018 15:23:53    * aws_s3_bucket_notification.my-trigger: Error putting S3 notification configuration: MethodNotAllowed: The specified method is not allowed against this resource.
20-Sep-2018 15:23:53            status code: 405, request id:<hidden>, host id:<hidden>

这是我设置通知触发器的代码:

resource "aws_s3_bucket_notification" "my-trigger" {
  bucket = "my-bucket"

  lambda_function {
    lambda_function_arn = "${aws_lambda_function.my-function.arn}"
    events              = ["s3:ObjectCreated:*"]
    filter_prefix       = "file-prefix"
    filter_suffix       = "file-extension"
  }
}

这是从S3触发Lambda的权限:

resource "aws_lambda_permission" "s3-lambda-permission" {
  statement_id  = "AllowExecutionFromS3Bucket"
  action        = "lambda:InvokeFunction"
  function_name = "${aws_lambda_function.my-function.arn}"
  principal     = "s3.amazonaws.com"
  source_arn    = "arn:aws:s3:::my-bucket"
}

提前谢谢!

1 个答案:

答案 0 :(得分:3)

所以我尝试了与您相同的设置,

...
// lambda resource

resource "aws_s3_bucket_notification" "my-trigger" {
    bucket = "k8-alb-ingress-access-logs"

    lambda_function {
        lambda_function_arn = "${aws_lambda_function.my-function.arn}"
        events              = ["s3:ObjectCreated:*"]
        filter_prefix       = "AWSLogs/"
        filter_suffix       = ".txt"
    }
}

resource "aws_lambda_permission" "test" {
  statement_id  = "AllowS3Invoke"
  action        = "lambda:InvokeFunction"
  function_name = "${aws_lambda_function.my-function.arn}"
  principal = "s3.amazonaws.com"
  source_arn = "arn:aws:s3:::my-bucket"
}

...

我的S3存储桶策略如下:

{
    "Version": "2012-10-17",
    "Id": "AWSConsole-AccessLogs-Policy-1534800162725",
    "Statement": [
        {
            "Sid": "AWSConsoleStmt-1534800162725",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::123456789012:root"
            },
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::k8-alb-ingress-access-logs/AWSLogs/890895631537/*"
        }
    ]
}

并且s3通知已成功创建。

所以我认为现在您应该检查两件事:

  1. 确保在您的s3通知之前实际创建了aws_lambda_permission。我正在使用terraform 0.10.2,但以前的版本中可能存在错误,因此该lambda权限不会在s3通知之前创建。

  2. 检查您的s3存储桶策略。可能明确拒绝了lambda访问。如果有的话,请确保将其清除。