I'm using Terraform to allocate a Lambda function that's triggered by a request to an API Gateway on AWS. Here's my .tf file:
provider "aws" {
region = "us-east-1"
}
resource "aws_lambda_function" "w-scan-terraform" {
function_name = "w-scan-terraform"
filename = "artifact.zip"
runtime = "python3.9"
handler = "lambda_function.lambda_handler"
role = aws_iam_role.iam_for_lambda.arn
}
resource "aws_apigatewayv2_api" "w-scan-terraform" {
name = "w-scan-terraform"
protocol_type = "HTTP"
}
resource "aws_apigatewayv2_stage" "stage" {
api_id = aws_apigatewayv2_api.w-scan-terraform.id
name = "$default"
auto_deploy = true
lifecycle {
ignore_changes = [
deployment_id,
default_route_settings
]
}
}
resource "aws_apigatewayv2_route" "route" {
api_id = aws_apigatewayv2_api.w-scan-terraform.id
route_key = "ANY /{proxy }"
target = "integrations/${aws_apigatewayv2_integration.integration.id}"
}
resource "aws_apigatewayv2_integration" "integration" {
api_id = aws_apigatewayv2_api.w-scan-terraform.id
integration_type = "AWS_PROXY"
connection_type = "INTERNET"
integration_method = "POST"
integration_uri = aws_lambda_function.w-scan-terraform.invoke_arn
passthrough_behavior = "WHEN_NO_MATCH"
lifecycle {
ignore_changes = [
passthrough_behavior
]
}
}
resource "aws_iam_role" "iam_for_lambda" {
name = "iam_for_lambda"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
resource "aws_lambda_permission" "apigw" {
statement_id = "AllowAPIGatewayInvoke"
action = "lambda:InvokeFunction"
function_name = "${aws_lambda_function.w-scan-terraform.function_name}"
principal = "apigateway.amazonaws.com"
source_arn = "${aws_apigatewayv2_api.w-scan-terraform.execution_arn}/*/*"
}
output "api_url" {
value = aws_apigatewayv2_stage.stage.invoke_url
}
This correctly sets up the Lambda function, but something is off with the API Gateway. When I curl with the output URL (
CodePudding user response:
The TF code that you showed is correct. Most likely reason for the failure is your lambda function, which you haven't showed. You have to inspect lambda function logs in CloudWatch to check why it fails.
Edit:
The function should return:
return {
'statusCode': 200,
'body': 'SUCCESS'
}
CodePudding user response:
If anyone comes across this issue, I managed to fix it by greatly simplifying things. I switched out all the API Gateway clauses in the Terraform file with just:
resource "aws_apigatewayv2_api" "w-scan-terraform" {
name = "w-scan-terraform-api"
protocol_type = "HTTP"
target = aws_lambda_function.w-scan-terraform.arn
}
The tutorial I was following had implemented something more complex than what I needed.