Skip to content

Instantly share code, notes, and snippets.

@brh55
Last active December 1, 2023 09:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save brh55/9d44b0e15f85de9bb14f614dcab9d443 to your computer and use it in GitHub Desktop.
Save brh55/9d44b0e15f85de9bb14f614dcab9d443 to your computer and use it in GitHub Desktop.
Minimum Terraform for AWS API Gateway <-> Lambda
import json
def handler(event, context):
return {
"statusCode": 200,
'headers': {'Content-Type': 'application/json'},
"body": json.dumps('Hi!')
}
# As long as your lambda adheres to expected API Gateway format, this is all you'll need
# API Gateway
# Define the use of rest API
resource "aws_api_gateway_rest_api" "api" {
name = format("app_name-%s", terraform.workspace)
}
# The resource for the endpoint
resource "aws_api_gateway_resource" "lambda" {
path_part = "ENDPOINT_HERE"
parent_id = aws_api_gateway_rest_api.api.root_resource_id
rest_api_id = aws_api_gateway_rest_api.api.id
}
# How the gateway will be interacted from clientt
resource "aws_api_gateway_method" "lambda" {
rest_api_id = aws_api_gateway_rest_api.api.id
resource_id = aws_api_gateway_resource.lambda.id
http_method = "GET"
authorization = "NONE"
}
# Integration between lambda and terraform
resource "aws_api_gateway_integration" "redirect" {
rest_api_id = aws_api_gateway_rest_api.api_gateway_rest_api.id
resource_id = aws_api_gateway_resource.lambda.id
http_method = aws_api_gateway_method.lambda.http_method
# Lambda invokes requires a POST method
integration_http_method = "POST"
type = "AWS_PROXY"
uri = aws_lambda_function.lambda.invoke_arn
}
# Define Lambda
resource "aws_lambda_function" "lambda" {
filename = var.zip_file
function_name = "lambda"
handler = "lambda.handler"
role = aws_iam_role.iam_role.arn
runtime = "python3.7" # change accordingly
source_code_hash = local.source_code_hash
}
# Define lambda permissions to grant API gateway, source arn is not needed
resource "aws_lambda_permission" "allow_api_gateway" {
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.lambda.function_name
principal = "apigateway.amazonaws.com"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment