Hierarchical resource creation in loop (AWS Provider)

Hoping for some advice on how to create hierarchical resources in a loop in Terraform v12x.
The exact use case I have is trying to create aws_api_gateway_resource in a parent child relationship.

I would like to model the hierarchy as a flat list [‘parent_path_step’, ‘child_path_step’], pass this list to a module and have the module use a looping construct in Terraform to build the path steps top down:

parent_path_step
    child_path_step

The hierarchy in the AWS provider is obtained via the parent_id property of the aws_api_gateway_resource. The first iteration of the loop has to refer to the root_id provided by the API Gatweway resource, the second iteration of the loop would have to refer to the id generated from the resource creation of ‘parent_path-step’. IE refer to the id returned by loop iteration [current - 1]

Any ideas on how I could achieve this please?

Cheers
AN

Hi @anovak-sbs,

The structure of the Amazon API Gateway resource types doesn’t really gel well with dynamic generation like you want to do here, because dependencies must be resolved before evaluating for_each.

However, I’ve seen it work to do certain things by dynamically generating an OpenAPI specification to populate the body argument of the aws_api_gateway_rest_api resource type, because unlike the native API gateway model the OpenAPI model consists of a flat map from endpoint paths to methods to operation definitions.

You can use the jsonencode function to dynamically generate a valid JSON-serialized OpenAPI definition from the result of an arbitrary Terraform expression, which can include for expressions to project your input data structure (which hopefully features URL paths represented as either strings or lists) into the shape OpenAPI expects.