Terraform folder structure

Viewed 1602

I am new to terraform, moving from cloudformation and need a help in folder structure. I am creating bunch of aws services and have the folders structured as below. Is this the right way?

Development
     |
     services
         |
        lambda_function
          |
          main.tf
          vars.tf
          output.tf
        ecs
          |
          main.tf
          vars.tf
          output.tf

Question is, if we import existing VPC information, should it be in each layers? like a separate tf? or part of main.tf. There are many services who having the folder structure will help rather 3000 lines of single main.tf. Thanks

2 Answers

I can definitely recommend reading through the Modules Overview tutorial and related resources, as reusing local modules is really the centerpiece for managing Terraform project configurations.

According to that, you seem to be on the right track for achieving reuse if you have correctly abstracted each service out as a module and declaring instances of these will fit in nicely with your Terraform project configuration. You can also take a look at the terraform-google-modules GitHub org repositories for inspiration on how to correctly write individual modules and reuse them across other higher-order modules.

As this is a bit of an art and everyone's needs are different based on their project and how teams are organized, there are a lot of Terraform projects hosted on GitHub that you can find by searching for terraform blocks in HCL files. I'd also like to point out that some project configurations that are out there might have benefited from using Terraform workspaces, in favor of having separate project configurations for things like separate testing/staging/production environments, so might be useful to cover that concept.

Like Filip Dupanović said, read the best practice guide on Hashicorp's site, but for folder structure, the gist of them are:

  • put your resources in a main.tf file
  • put inputs in variables.tf
  • put outputs in outputs.tf
  • put any private sub-modules you make (private means they are not intended for use in other modules) in a modules sub-folder.
  • create an examples folder that contains examples in subfolders.
  • create a README that describes the module's use. Consider using terraform-docs to generate part of it.

Example for mymodule in the git repo terraform-aws-mymodule:

terraform-aws-mymodule
 +- examples
 |   +- simple
 |      + main.tf
 +- modules
 |   +- lambda_function
 |       + main.tf
 |       + variables.tf
 |       + outputs.tf
 |   +- ecs
 |       + main.tf
 |       + variables.tf
 |       + outputs.tf
 + main.tf
 + variables.tf
 + outputs.tf
 + README.md
Related