Terraform 脚本 api_gateway 与 lambda 集成

问题描述 投票:0回答:1

我创建了以下 terraform 脚本 -

provider "aws" {
    region = "eu-west-2"
}

resource "aws_lambda_function" "my_lambda_function" {
    function_name              = "Lambda-Demo-AG"
    package_type               = "Image"
    image_uri                  = "###########"
    role                       = aws_iam_role.role.arn
    memory_size                = 256
    timeout                    = 30
    tracing_config {
        mode = "PassThrough"
    } 
}

# IAM
data "aws_iam_policy_document" "assume_role" {
  statement {
    effect = "Allow"

    principals {
      type        = "Service"
      identifiers = ["lambda.amazonaws.com"]
    }

    actions = ["sts:AssumeRole"]
  }
}

resource "aws_iam_role" "role" {
  name               = "myrole"
  assume_role_policy = data.aws_iam_policy_document.assume_role.json
}

resource "aws_lambda_permission" "apigw_lambda" {
  statement_id  = "AllowExecutionFromAPIGateway"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.my_lambda_function.function_name
  principal     = "apigateway.amazonaws.com"

  source_arn = aws_api_gateway_rest_api.api.arn
}

###API Gateway####

# API Gateway
resource "aws_api_gateway_rest_api" "api" {
  name = "myapi"
}

resource "aws_api_gateway_resource" "resource" {
  path_part   = "resource"
  parent_id   = aws_api_gateway_rest_api.api.root_resource_id
  rest_api_id = aws_api_gateway_rest_api.api.id
}

resource "aws_api_gateway_method" "method" {
  rest_api_id   = aws_api_gateway_rest_api.api.id
  resource_id   = aws_api_gateway_resource.resource.id
  http_method   = "GET"
  authorization = "NONE"
}

resource "aws_api_gateway_integration" "integration" {
  rest_api_id             = aws_api_gateway_rest_api.api.id
  resource_id             = aws_api_gateway_resource.resource.id
  http_method             = aws_api_gateway_method.method.http_method
  integration_http_method = "POST"
  type                    = "AWS_PROXY"
  uri                     = aws_lambda_function.my_lambda_function.invoke_arn
}

resource "aws_api_gateway_deployment" "apideploy" {
   depends_on = [
     aws_api_gateway_integration.integration,
   ]

   rest_api_id = aws_api_gateway_rest_api.api.id
   stage_name  = "test"
}

当我点击 API 时,由于某种原因,lambda 函数没有被触发。我收到的消息是{“message”:“内部服务器错误”}。这是当我点击路径时,例如 https://#########.execute-api.eu-west-2.amazonaws.com/test/resource 当我点击根 https://# 时########.execute-api.eu-west-2.amazonaws.com/test 尽管没有设置身份验证,但我收到 {"message":"Missing Authentication Token"} ?我进入 API 网关的控制台,可以看到集成了正确的 Lambda。如果我进入 Lambda 控制台,则指定的 Lambda 函数在图表 UI 中没有 api 网关作为触发器。我配置了 cloudwatch,但看不到正在调用 lambda 函数。

知道为什么会发生这种情况吗?

amazon-web-services lambda terraform aws-api-gateway integration
1个回答
0
投票

我发现了这个问题 - 我在 aws_lambda_permissions 中设置 source_arn 的方式存在问题。我改变了这一点,我就能够调用 lambda 函数。

© www.soinside.com 2019 - 2024. All rights reserved.