我正在尝试使用Terraform部署AWS API Gateway和Lambda。网关只是我功能的代理。运行terraform apply
后,对端点的每个Web请求都会失败。
API网关将此错误消息记录到Cloudwatch:
由于配置错误,执行失败:Lambda函数的权限无效
但是现在变得很奇怪:如果我在AWS Web Console中按下了部署按钮,然后又一次部署(没有其他更改)API网关,那么一切正常。下一个“地形应用”再次部署aws_api_gateway_stage.staging
,这再次破坏了一切。
这是我的Terraform设置:
lambda.tf:
resource "aws_lambda_function" "contactform-api" {
filename = "deploy.zip"
function_name = "contactform-api"
handler = "main"
runtime = "go1.x"
role = "${aws_iam_role.lambda_role.arn}"
publish = "false"
timeout = "60"
}
resource "aws_iam_role" "lambda_role" {
name = "iam_for_lambda"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": "IAMRoleForLambda"
}
]
}
EOF
}
resource "aws_lambda_permission" "apigw" {
statement_id = "AllowExecutionFromAPIGateway"
action = "lambda:InvokeFunction"
function_name = "${aws_lambda_function.contactform-api.arn}"
principal = "apigateway.amazonaws.com"
source_arn = "${aws_api_gateway_rest_api.contactform.execution_arn}/*/*/*"
}
api_gateway.tf:
resource "aws_api_gateway_rest_api" "contactform" {
name = "ContactformAPI"
description = "Contactform REST API"
}
resource "aws_api_gateway_resource" "api" {
rest_api_id = "${aws_api_gateway_rest_api.contactform.id}"
parent_id = "${aws_api_gateway_rest_api.contactform.root_resource_id}"
path_part = "{proxy+}"
}
resource "aws_api_gateway_method" "api" {
rest_api_id = "${aws_api_gateway_rest_api.contactform.id}"
resource_id = "${aws_api_gateway_resource.api.id}"
http_method = "ANY"
authorization = "NONE"
}
resource "aws_api_gateway_integration" "lambda" {
rest_api_id = "${aws_api_gateway_rest_api.contactform.id}"
resource_id = "${aws_api_gateway_resource.api.id}"
http_method = "${aws_api_gateway_method.api.http_method}"
integration_http_method = "POST"
type = "AWS_PROXY"
uri = "${aws_lambda_function.contactform-api.invoke_arn}"
}
resource "aws_api_gateway_deployment" "staging" {
depends_on = ["module.cors", "aws_api_gateway_method.api", "aws_api_gateway_resource.api", "aws_api_gateway_integration.lambda"]
stage_name = "staging"
rest_api_id = "${aws_api_gateway_rest_api.contactform.id}"
}
resource "aws_api_gateway_stage" "staging" {
stage_name = "staging"
rest_api_id = "${aws_api_gateway_rest_api.contactform.id}"
deployment_id = "${aws_api_gateway_deployment.staging.id}"
}
答案 0 :(得分:0)
您正在将Lambda函数的ARN用作function_name
资源中的aws_lambda_permission
。
将其更改为名称而不是ARN应该可以为您解决:
resource "aws_lambda_permission" "apigw" {
statement_id = "AllowExecutionFromAPIGateway"
action = "lambda:InvokeFunction"
function_name = "${aws_lambda_function.contactform-api.function_name}"
principal = "apigateway.amazonaws.com"
source_arn = "${aws_api_gateway_rest_api.contactform.execution_arn}/*/*/*"
}
关于当您通过AWS控制台进行部署时为何起作用; AWS控制台可以为您神奇地设置权限,因此您无需通过Web UI来处理这些权限。当Terraform重新部署更改时,它将再次破坏它,因为Terraform需要明确声明Lambda函数的权限。