Skip to content

Instantly share code, notes, and snippets.

@totegamma
Created Jun 26, 2022
Embed
What would you like to do?
terraform {
backend "s3" {
bucket = "net.gammalab.terraform-test-tfstate"
key = "terraform.tfstate"
region = "ap-northeast-1"
}
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.27"
}
}
required_version = ">= 0.14.9"
}
provider "aws" {
region = "ap-northeast-1"
}
resource "aws_iam_role" "iam_for_lambda" {
name = "iam_for_lambda"
assume_role_policy = jsonencode({
Version = "2012-10-17",
Statement = [{
Action = "sts:AssumeRole",
Effect = "Allow",
Sid = "",
Principal = {
Service = "lambda.amazonaws.com"
}
}]
})
}
data "archive_file" "lambda_payload" {
type = "zip"
source_dir = "${path.module}/src"
output_path = "${path.module}/payload.zip"
}
resource "aws_lambda_function" "test_lambda" {
filename = data.archive_file.lambda_payload.output_path
function_name = "myTestFunction"
runtime = "nodejs16.x"
role = aws_iam_role.iam_for_lambda.arn
handler = "index.handler"
source_code_hash = data.archive_file.lambda_payload.output_base64sha256
}
resource "aws_apigatewayv2_api" "terraform_test" {
name = "test-terraform-http-api"
protocol_type = "HTTP"
}
resource "aws_apigatewayv2_stage" "terraform_test" {
api_id = aws_apigatewayv2_api.terraform_test.id
name = "serverless_lambda_stage"
auto_deploy = true
access_log_settings {
destination_arn = aws_cloudwatch_log_group.api_gw.arn
format = jsonencode({
requestId = "$context.requestId"
sourceIp = "$context.identity.sourceIp"
requestTime = "$context.requestTime"
protocol = "$context.protocol"
httpMethod = "$context.httpMethod"
resourcePath = "$context.resourcePath"
routeKey = "$context.routeKey"
status = "$context.status"
responseLength = "$context.responseLength"
integrationErrorMessage = "$context.integrationErrorMessage"
}
)
}
}
resource "aws_apigatewayv2_integration" "terraform_test" {
api_id = aws_apigatewayv2_api.terraform_test.id
integration_uri = aws_lambda_function.test_lambda.invoke_arn
integration_type = "AWS_PROXY"
integration_method = "POST"
}
resource "aws_apigatewayv2_route" "hello_world" {
api_id = aws_apigatewayv2_api.terraform_test.id
route_key = "GET /hello"
target = "integrations/${aws_apigatewayv2_integration.terraform_test.id}"
}
resource "aws_cloudwatch_log_group" "api_gw" {
name = "/aws/api_gw/${aws_apigatewayv2_api.terraform_test.name}"
retention_in_days = 30
}
resource "aws_lambda_permission" "api_gw" {
statement_id = "AllowExecutionFromAPIGateway"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.test_lambda.function_name
principal = "apigateway.amazonaws.com"
source_arn = "${aws_apigatewayv2_api.terraform_test.execution_arn}/*/*"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment