Learn how to join an API Gateway to Inline Lambda in Terraform

To attach an API Gateway to an inline Lambda operate utilizing Terraform, you may observe these steps:

  1. Outline your API Gateway and Lambda operate assets 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/features/${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': 'Hi there from Lambda!'

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 operate is outlined inline utilizing the inline_code property. The code contained in the lambda_handler operate could be custom-made in keeping with your necessities.

  1. Guarantee you have got the required supplier configuration in your Terraform file, specifying the AWS supplier and the specified area:
supplier "aws" {
  area = "us-east-1"
  1. Run terraform init to initialize the Terraform configuration.

  2. Run terraform apply to create the API Gateway and Lambda operate assets.

These steps will create an API Gateway that’s linked to your inline Lambda operate. Requests made to the API Gateway endpoint can be routed to your Lambda operate for processing.

Leave a Reply

Your email address will not be published. Required fields are marked *