Software Engineering

How to connect an API Gateway to Inline Lambda in Terraform


To connect an API Gateway to an inline Lambda function using Terraform, you can follow these steps:

  1. Define your API Gateway and Lambda function resources in your Terraform configuration. Here’s an example:
resource "aws_api_gateway_rest_api" "my_api_gateway" {
  name = "MyApiGateway"
}

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"
}

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 {
    type             = "AWS_PROXY"
    http_method      = "POST"
    uri              = "arn:aws:apigateway:${var.region}:lambda:path/2015-03-31/functions/${aws_lambda_function.my_lambda_function.arn}/invocations"
  }
}

resource "aws_api_gateway_deployment" "my_api_gateway_deployment" {
  rest_api_id = aws_api_gateway_rest_api.my_api_gateway.id
  stage_name  = "prod"
}

resource "aws_lambda_function" "my_lambda_function" {
  function_name = "MyLambdaFunction"
  runtime       = "python3.8"
  handler       = "index.lambda_handler"
  inline_code   = <<EOF
    def lambda_handler(event, context):
        return {
            'statusCode': 200,
            'body': 'Hello from Lambda!'
        }
  EOF
}

resource "aws_lambda_permission" "my_lambda_permission" {
  statement_id  = "AllowAPIGatewayInvoke"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.my_lambda_function.arn
  principal     = "apigateway.amazonaws.com"
  source_arn    = "arn:aws:execute-api:${var.region}:${data.aws_caller_identity.current.account_id}:${aws_api_gateway

In the above example, the Lambda function is defined inline using the inline_code property. The code inside the lambda_handler function can be customized according to your requirements.

  1. Ensure you have the necessary provider configuration in your Terraform file, specifying the AWS provider and the desired region:
provider "aws" {
  region = "us-east-1"
}
  1. Run terraform init to initialize the Terraform configuration.

  2. Run terraform apply to create the API Gateway and Lambda function resources.

These steps will create an API Gateway that is connected to your inline Lambda function. Requests made to the API Gateway endpoint will be routed to your Lambda function for processing.