Using Terragrunt’s generate block to make your Terraform DRY

--

As you write more Terraform modules for your Infrastructure as Code (IaC), you will notice some repetitions across all your modules. An example of this is the providerblock. Terragrunt’s generate block can be used to eliminate this repetition and keep your Terraform DRY.

Example Time

Let’s say you have the following directory structure for your IaC

terragrunt/
- terragrunt.hcl
- vpc/
- terragrunt.hcl
- security_groups/
- terragrunt.hcl
modules/
- vpc/
- main.tf
- security_groups/
- main.tf

At the beginning of your modules/vpc/main.tf and modules/security_groups/main.tf files, you would probably have the provider block like so:

provider "aws" {
region = "ap-southeast-1"
}

In this example, we have 2 modules — vpc and security_groups and both have the provider block. Now imagine that as you add more infrastructure and more modules, you will be repeating the provider block across many more modules! That can be a lot of repetition.

Terragrunt to the rescue!

We can use Terragrunt’s generate block to cut down on the repetition. In our terragrunt/terragrunt.hcl file, we can add the generateblock below:

--

--

Government Digital Products, Singapore
Government Digital Products, Singapore

Published in Government Digital Products, Singapore

Be Happy, Be Awesome! We deliver high-quality digital services to citizens and businesses in Singapore 😊

Salihan Zaol-kefli
Salihan Zaol-kefli

Written by Salihan Zaol-kefli

Software Engineer, Amateur Writer, Casual Gamer

No responses yet