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:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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:
1
2
3
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.