Search code examples
amazon-web-servicesswaggerterraform

Terraform loop through Swagger Docs directory and create APIs


Question:

I want Terraform to loop through a directory containing Swagger docs (OpenAPI Specs) and create AWS Gateway REST APIs from them

The setup:

I have the following directory structure:

./
 ./swagger_docs/
              api-some-name swagger.yml
              api-some-other-name swagger.yml
              ... (many more)
 ./src/
              main.tf

Inside my main.tf I want to be able to consume the swagger_docs files to create AWS API Gateway resources.

Currently the main.tf looks like this:

provider "aws" {
  version = "~> 3.0"
  region = "eu-west-1"
}

locals {
  api_name = "api-some-name"
  template_file = file("../swagger_docs/${local.api_name} swagger.yml")
}

resource "aws_api_gateway_rest_api" "MyDemoAPI" {
  name        = "Some API Name"
  description = "Some description for the API"
  body = local.template_file
}

This successfully creates a single resource in AWS API Gateway.

How can I change this to loop through the swagger_docs directory, and consume all the swagger files, so that I don't have to do this manually?


Solution

  • You can use the fileset function to glob all of the files in that directory. Based on the information provided, this appears to be a root config, and not an explicit module. Therefore, we can use the function like the following:

    fileset(path.root, "../swagger_docs/*.yml")
    

    and this will return a List of all of the Swagger API documents in that directory. We can then iterate over it within your aws_api_gateway_rest_api resource like the following:

    resource "aws_api_gateway_rest_api" "MyDemoAPIs" {
      for_each = toset(fileset(path.root, "../swagger_docs/*.yml"))
    
      name        = regex(each.key, "(.*) swagger.yml")[0] # regular expression to capture the name of the api from the document file name
      description = "Some description for the API"
      body        = file(each.key) # content of specific swagger doc in the iterator
    }
    

    and this will create an AWS API Gateway resource for each Swagger document with dynamic content and name.