Terraform API Gateway v2 Authorizer - 自动授予 API 网关权限以调用您的 Lambda 函数

Terraform API Gateway v2 Authorizer - Automatically grant API Gateway permission to invoke your Lambda function

在 AWS 控制台中,可以创建具有 true/false 值的 API 网关授权方“自动授予 API 网关

但是,我没有看到此标志通过 Terraform 中的 AWS 提供商为 aws_apigatewayv2_authorizer 资源公开。

有没有办法通过 Terraform 进行设置?

在 terraform 中,您需要手动创建 IAM 语句才能完成这项工作。最简单的方法是使用与您的 lambda 关联的资源策略:

resource "aws_lambda_permission" "my_authorizer_lambda_permission" {
    statement_id  = "AllowAPIGatewayInvoke"
    action        = "lambda:InvokeFunction"
    function_name = aws_lambda_function.onconnect.function_name
    principal     = "apigateway.amazonaws.com"

    source_arn    = "${aws_apigatewayv2_api.my_api.execution_arn}/authorizers/${aws_apigatewayv2_authorizer.my_authorizer.id}"
}

我与 hashicorp/aws@4.8.0 提供者有同样的问题。为了解决这个问题,我必须创建一个 IAM 角色并将授权者中的角色分配为 authorizer_credentials_arn

data "aws_iam_policy_document" "apig_lambda_policy" {
  statement {
    actions = [
      "lambda:InvokeFunction",
    ]
    effect    = "Allow"
    resources = [aws_lambda_function.authorizer_lambda.arn]
    sid       = "ApiGatewayInvokeLambda"
  }
}

data "aws_iam_policy_document" "apig_lambda_role_assume" {
  statement {
    actions = [
      "sts:AssumeRole",
    ]
    effect = "Allow"
    principals {
      type        = "Service"
      identifiers = ["apigateway.amazonaws.com"]
    }
  }
}

resource "aws_iam_role" "apig_lambda_role" {
  name               = "apigateway-authorize-lambda-role"
  assume_role_policy = data.aws_iam_policy_document.apig_lambda_role_assume.json
}

resource "aws_iam_policy" "apig_lambda" {
  name   = "apig-lambda-policy"
  policy = data.aws_iam_policy_document.apig_lambda_policy.json
}

resource "aws_iam_role_policy_attachment" "apig_lambda_role_to_policy" {
  role       = aws_iam_role.apig_lambda_role.name
  policy_arn = aws_iam_policy.apig_lambda.arn
}

resource "aws_apigatewayv2_authorizer" "auth" {
  api_id                            = aws_apigatewayv2_api.api.id
  authorizer_type                   = "REQUEST"
  authorizer_uri                    = aws_lambda_function.authorizer_lambda.invoke_arn
  authorizer_credentials_arn        = aws_iam_role.apig_lambda_role.arn
  authorizer_payload_format_version = "2.0"
  authorizer_result_ttl_in_seconds  = 1
  enable_simple_responses           = true
  identity_sources                  = ["$request.header.Authorization"]
  name                              = "lambda-authorizer"
}