To attach an API Gateway to an inline Lambda perform utilizing Terraform, you may comply with these steps:
- Outline your API Gateway and Lambda perform sources in your Terraform configuration. Right here’s an instance:
useful resource "aws_api_gateway_rest_api" "my_api_gateway" {
title = "MyApiGateway"
}
useful resource "aws_api_gateway_resource" "my_api_gateway_resource" {
rest_api_id = aws_api_gateway_rest_api.my_api_gateway.id
parent_id = aws_api_gateway_rest_api.my_api_gateway.root_resource_id
path_part = "myresource"
}
useful resource "aws_api_gateway_method" "my_api_gateway_method" {
rest_api_id = aws_api_gateway_rest_api.my_api_gateway.id
resource_id = aws_api_gateway_resource.my_api_gateway_resource.id
http_method = "GET"
authorization = "NONE"
integration {
kind = "AWS_PROXY"
http_method = "POST"
uri = "arn:aws:apigateway:${var.area}:lambda:path/2015-03-31/capabilities/${aws_lambda_function.my_lambda_function.arn}/invocations"
}
}
useful resource "aws_api_gateway_deployment" "my_api_gateway_deployment" {
rest_api_id = aws_api_gateway_rest_api.my_api_gateway.id
stage_name = "prod"
}
useful resource "aws_lambda_function" "my_lambda_function" {
function_name = "MyLambdaFunction"
runtime = "python3.8"
handler = "index.lambda_handler"
inline_code = <<EOF
def lambda_handler(occasion, context):
return {
'statusCode': 200,
'physique': 'Whats up from Lambda!'
}
EOF
}
useful resource "aws_lambda_permission" "my_lambda_permission" {
statement_id = "AllowAPIGatewayInvoke"
motion = "lambda:InvokeFunction"
function_name = aws_lambda_function.my_lambda_function.arn
principal = "apigateway.amazonaws.com"
source_arn = "arn:aws:execute-api:${var.area}:${information.aws_caller_identity.present.account_id}:${aws_api_gateway
Within the above instance, the Lambda perform is outlined inline utilizing the inline_code
property. The code contained in the lambda_handler
perform will be custom-made in line with your necessities.
- Guarantee you’ve the mandatory supplier configuration in your Terraform file, specifying the AWS supplier and the specified area:
supplier "aws" {
area = "us-east-1"
}
-
Run
terraform init
to initialize the Terraform configuration. -
Run
terraform apply
to create the API Gateway and Lambda perform sources.
These steps will create an API Gateway that’s linked to your inline Lambda perform. Requests made to the API Gateway endpoint will likely be routed to your Lambda perform for processing.