DEV Community

Skyler
Skyler

Posted on

How to structure your Terraform project

Hi! This article is "Terraform beginners" friendly and for anyone curious about TF best practices. If you've learned anything, it would be awesome to share this article on Twitter or to react in the comments here :)

This time, we are going to talk about Terraform, more specifically, how to you organise your project/repository. What I'm going to share is "best practices" and how most companies I've seen use. If you do differently, please share!

.
|
├── modules                    
│   ├── database               # first module
│   ├── networking             # second module
│   └── ...
└── main.tf
└── version.tf
└── variables.tf
└── outputs.tf
Enter fullscreen mode Exit fullscreen mode

Let's look in details:

  • modules: This is where you put re-usable code. Let's say you need to call multiple times a database. Stick the configuration in /modules/database, call it from main.tf (or whatever name) and that's it, you've got code that's a bit more DRY!
  • main.tf: The best practice is to have a main.tf with either your whole configuration (if small), or the core of it and others .tf files (if long).
  • version.tf: This is the file where you put the required_providers and required_version versions. More information in this blog post.
  • variables.tf: This file does differ from companies to companies. Some companies use a variables file specific for each environment, some use this file only for the main generic one and use another directory which I will mention below.
  • outputs.tf: You don't always have outputs from your code. Outputs are what you want to access from somewhere else. Usually used for modules, so that you can access ID's, names and others from the resources you create in there. Example with an EKS cluster: You might want to access the endpoint. You can find outputs by looking at the section called "Attributes Reference".

Slightly advanced: add a config folder (the name does not matter).

.
|
├── config                  
│   ├── cli         
│   ├── dev         
│   └── ...
...
Enter fullscreen mode Exit fullscreen mode

We will use this example of a cli file:

storage_account:
   tier: Standard
Enter fullscreen mode Exit fullscreen mode

We'll make this works in a few steps:
1) Create a locals block:

locals {
   config_content = file("./config/${var.environemnt}.yaml")
   config = yamldecode(local.config_content)
}
Enter fullscreen mode Exit fullscreen mode

2) Then, in the code you would access by calling local.config.storage_account.tier.

I hope this made sense! I want to talk more about Terraform, as it's one of my favourite tech, feel free to give me questions or suggestions :).

Top comments (0)