aws-lambdaimportterraformaws-api-gatewayinfrastructure-as-code

How to integrate the lambdas uris in the AWS API Gateway Specification YAML?


I'm working on managing my AWS API Gateway resources with Terraform. I've already generated the specification.yaml file for my API Gateway directly from the AWS Management Console.

My questions are:

when I reference this specification.yaml file directly in my Terraform configuration to automatically generate the Terraform configuration for the API Gateway?

resource "aws_api_gateway_rest_api" "api-gateway" {
 name        = "name"
  api_key_source = "HEADER"
  body           = "${data.template_file.swagger_spec.rendered}"

  endpoint_configuration {
    types = ["REGIONAL"]
  }
}

data "template_file" "swagger_spec" {
  template = file("${var.path_api}specification.yaml")

}

how and where to add the aws integration with the lambdas uris so that Terraform manage these API Gateway resources using the referenced YAML file/the integration with lambdas?

Any guidance or examples on the best practices for this approach would be greatly appreciated. Thanks!


Solution

  • You should import your swagger file as a template_file, and supply vars that should be substituted, like the uris. Below you'll find a simplified example:

    resource "aws_lambda_function" "hello_world" {
      function_name = "hello-world"
    
      s3_bucket = "${var.s3_bucket}"
      s3_key    = "hello_world.zip"
    
      handler     = "lambda_function.lambda_handler"
      runtime     = "python3.10"
      memory_size = 256
      timeout     = 10
    }
    
    data "template_file" "swagger" {
      template = "${file("swagger.yaml")}"
    
      vars = {
        lambda_arn              = "${aws_lambda_function.hello_world.arn}"
        aws_region              = var.aws_region
      }
    }
    
    resource "aws_api_gateway_rest_api" "hello_world" {
      name           = "hello-world"
      description    = "Say hello world"
      api_key_source = "HEADER"
      body           = "${data.template_file.swagger.rendered}"
    
      endpoint_configuration {
        types = ["REGIONAL"]
      }
    }
    

    Below you'll find a small snippet from the swagger.yaml file. The variables ${aws_region} and ${lambda_arn} will be replaced by actual values.

      x-amazon-apigateway-integration:
        uri: "arn:aws:apigateway:${aws_region}:lambda:path/2015-03-31/functions/${lambda_arn}/invocations"
        passthroughBehavior: "when_no_match"
        httpMethod: "POST"
        type: "aws_proxy"
        contentHandling: "CONVERT_TO_TEXT"
      x-amazon-apigateway-auth:
        type: "NONE"
      x-amazon-apigateway-api-key-source: "HEADER"