Introduction
Probably the most common question I get asked is how to organise terraform modules.
Terraform have great tutorials on getting started, but they glance over the best practice when it comes to organising the folder structure on your project.
This can be confusing for experienced engineers who often come from a background using tools like Cloud Formation, but are now looking to switch to terraform.
Sample Tree
While the exact configuration will vary per project, here is the general structure I use for your typical medium to large size project. It supports multiple environments cleanly and separates the logic into reusable modules.
.
├── envs
│ ├── dev
│ │ ├── main.tf
│ │ └── outputs.tf
│ └── prod
│ ├── main.tf
│ └── outputs.tf
└── modules
├── database
│ ├── LICENSE
│ ├── README.md
│ ├── main.tf
│ ├── outputs.tf
│ └── variables.tf
└── vpc
├── LICENSE
├── README.md
├── main.tf
├── outputs.tf
└── variables.tf
For large to enterprise size projects, the modules would likely be further split into their own repositories later. Premature optimisation is a dangerous game though, so this is my preferred starting point for new terraform projects.
Where do I run terraform commands?
So in these scenarios you would change directory to ./env/dev
or ./env/prod
and then run your usual terraform commands.
These environment main.tf
files are fairly bare and link out to the modules. Only deviating to pass in different modules and variables as required. For example our production database might be small
in dev, but large
in production, but still use the same underlying module for provisioning the database.
Summary
That’s it! This is just a quick article to highlight the folder structure I use on new terraform projects.
For further information on getting started then check out the official terraform documentation.