EPIQ

11 Steps to Reduce Redundancy in Terraform Code with Terragrunt

11 Steps to Reduce Redundancy in Terraform Code with Terragrunt

Redundancy can be a huge pain when it comes to Terraform code. Not only does it make your code difficult to read and understand, but it also makes it harder to maintain. If you’re like most Terraform users, you want to reduce the amount of redundant code in your configurations. This is where Terragrunt comes in. Terragrunt is a library that makes it easy to manage multiple Terraform configurations, and it includes support for modules, variables, and more. In this blog post, we will show you how to use Terragrunt to reduce redundancy in your Terraform code.

11 Steps to Reduce Redundancy in Terraform Code with Terragrunt

Redundancy can be a huge pain when it comes to Terraform code. Not only does it make your code difficult to read and understand, but it also makes it harder to maintain. If you’re like most Terraform users, you want to reduce the amount of redundant code in your configurations. This is where Terragrunt comes in. Terragrunt is a library that makes it easy to manage multiple Terraform configurations, and it includes support for modules, variables, and more. In this blog post, we will show you how to use Terragrunt to reduce redundancy in your Terraform code.

May 05, 2022

Author by surajg

 

The issue with the Terraform code

One of the biggest issues with Terraform code is redundancy. This can be a huge problem for two reasons. First, it makes your code more difficult to read and understand. Second, it makes it harder to maintain. If you’re like most Terraform users, you want to reduce the amount of redundant code in your configurations. This is where Terragrunt comes in.

Terragrunt is a library that makes it easy to manage multiple Terraform configurations, and it includes support for modules, variables, and more.

How Application Works?

First, you need to install Terragrunt. You can do this with the following command:

“`

brew install terragrunt

“`

Next, you need to create a new file called `terragrunt.hcl` in your project’s root directory. In this file, you will specify the location of your Terraform modules. For example:

“`hcl

module “my-app” {

source = “github.com/my-org/my-app”

}

“`

Now, you can run the `terragrunt apply` command to apply your Terraform code. This will download and install the necessary Terraform modules, and it will also run any other Terragrunt commands that you have specified.

How The Terraform code works

By first downloading and installing the necessary Terraform modules. Next, it will run any other Terragrunt commands that you have specified. Finally, it will apply your Terraform code.

By using Terragrunt, you can easily reduce the amount of redundancy in your Terraform code. This will make your code easier to read and understand, and it will also make it easier to maintain. Give it a try today!

Terragrunt is a great tool for managing Terraform code, but it’s not the only one out there. If you’re looking for more options, check out our list of the best Terraform tools.

What is Terragrunt?

Terragrunt is a Terraform wrapper that provides extra functionality, like the ability to keep your Terraform configurations DRY and maintainable. Terragrunt also makes it easy to work with multiple Terraform modules by providing a simple way to reference other modules.

If you’re new to Terraform, or if you’re looking for ways to improve your Terraform code, read on for a step-by-step guide to reducing redundancy in Terraform code with Terragrunt.

Here are the steps:

Step 1: Install Terragrunt

If you haven’t already, install Terragrunt by following the instructions on the Terraform website. Terragrunt is a Terraform wrapper, so it requires Terraform to be installed first.

Step 2: Define Your Terraform Code Structure

Terragrunt works best when your Terraform code is organized into modules. A module is a self-contained piece of Terraform code with a specific purpose. For example, you might have a module for creating an Amazon SNS topic, and another module for creating an Amazon SQS queue. Each module should be defined in its own directory. Within each module directory,

you should have a Terraform configuration file (usually named main.tf) and, optionally, any number of Terraform variable files.

Step 3: Create a Terragrunt Configuration File in Each Module Directory

In each module directory, create a terragrunt.hcl file. The terragrunt.hcl file contains settings for how Terragrunt should execute Terraform. For example, the following terragrunt.hcl file tells Terragrunt to use the Amazon AWS provider when running Terraform:

provider “aws” {

region = “${var.aws_region}”

}

The terragrunt.hcl file can also be used to reference other modules. For example, the following terragrunt.hcl file tells Terragrunt to use the Amazon SNS module defined in the sns directory:

module “sns” {

source = “./sns”

}

Step 4 : Initialize Terraform in Each Module Directory

After you’ve created a terragrunt.hcl file in each module directory, initialize Terraform by running the following command from the root of your Terraform code directory:

terragrunt init

This command will download any required Terraform providers and modules.

Step 5: Plan and Apply Your Terraform Code

Once Terraform is initialized, you can plan and apply your changes by running the following commands from the root of your Terraform code directory:

terragrunt plan

terragrunt apply

Step 6: Destroy Your Terraform Infrastructure

When you’re finished working with your Terraform infrastructure, you can destroy it by running the following command from the root of your Terraform code directory:

terragrunt destroy

Step 7 : Keep Your Terraform Code DRY with Terragrunt

Terragrunt provides a number of features that help keep your Terraform code DRY and maintainable. For example, Terragrunt supports the use of Terraform input variables, which allows you to reuse Terraform code without duplicating it.

To use input variables in Terragrunt, create a file named terraform.tfvars in your Terraform code directory and define your variables in that file. For example:

aws_region = “us-east-

variable “environment” {

default = “dev”

}

You can then reference these variables in your Terraform code using the “${var.variable_name}” syntax.

For example:

resource “aws_sns_topic” “my_topic” {

region = “${var.aws_region}”

name = “${format(“%s-%s”, var.environment, aws_sns_topic.my_topic)}”

}

Terragrunt will automatically populate the Terraform input variables from the terraform.tfvars file when you run the terragrunt plan and terragrunt apply commands.

You can also use Terragrunt to manage Terraform state files. By default, Terraform stores the state of your infrastructure in a local file named terraform.tfstate. This can be problematic if you’re working with a team of people, because it’s easy for two people to make changes to the same Terraform code and end up with conflicting state files.

Terragrunt supports storing Terraform state in a remote location, such as Amazon S three simple steps:

Step I: Install Terraform

Step II: Define Your Terraform Modules in Separate Directories

Step III: Create a Terragrunt Configuration File in Each Module Directory

Step IV: Initialize Terraform in Each Module Directory

Step V: Plan and Apply Your Terraform Code

Step VI: Destroy Your Terraform Infrastructure

By following these simple steps, you can use Terragrunt to manage your Terraform state files and keep your Terraform code DRY.

Decouple the logic of the Terraform code with its implementation

One Terraform best practice is to separate the Terraform code that declares the infrastructure resources from the Terraform code that implements the resources. This separation of concerns makes it easier to understand what the Terraform code is doing without having to understand all of the details about how each resource is implemented.

One way to achieve this separation of concerns is by using Terragrunt, which is a thin wrapper for Terraform that provides extra functionality for working with Terraform modules. Terragrunt allows you to keep your Terraform code in reusable modules and your resource implementation code in separate files. This separation of concerns makes it easier to understand what your Terraform code is doing and makes it easier to reuse your Terraform modules.

Terragrunt is a great tool for managing Terraform code, but it can be difficult to use if you’re not familiar with it. In this blog post, I’m going to show you how to use Terragrunt to reduce redundancy in your Terraform code.

Here are the steps:

Step I :

Create a Terraform module for each resource type that you want to manage with Terragrunt. For example, if you want to manage AWS EC² instances, create a module called “ecs” in the “modules” directory.

Step II:

Create a terragrunt configuration file for each Terraform module. The terragrunt configuration file should be named “terragrunt.hcl” and should be located in the root of the Terraform module directory.

In the terragrunt configuration file, specify the Terraform source for the module and set the “terragrunt_source” variable to “git::ssh://git@github.com/your-username/your-repo.git//path/to/module”. This will tell Terragrunt to fetch the Terraform code for the module from your Git repository.

Step III:

Set the “terragrunt_remote_state” variable to “s three s t a t e”. This will tell Terragrunt to use SThreeState to manage Terraform state for the module. SThreeState is a Terraform remote state management tool that allows you to keep your Terraform state in a central location and share it between multiple Terraform modules.

Step IV:

Set the “terragrunt_remote_state_key” variable to “your-repo/your-module”. This will tell Terragrunt to use the key “your-repo/your-module” when fetching Terraform state from SThreeState.

Step V:

Set the “terragrunt_local_state” variable to “false”. This will tell Terragrunt not to manage Terraform state locally for the module.

Step VI:

Set the “terragrunt_iam_role_arn” variable to “your-iam-role-arn”. This will tell Terragrunt to use the IAM role specified by the “your-iam-role-arn” when fetching Terraform state from SThreeState.

Step VII:

In the terragrunt configuration file, specify the Terraform variables for the module. The Terraform variables should be declared in a file named “variables.tf” and should be located in the root of the Terraform module directory.

Step VIII:

In the terragrunt configuration file, specify the Terraform outputs for the module. The Terraform outputs should be declared in a file named “outputs.tf” and should be located in the root of the Terraform module directory.

Step IX:

In the terragrunt configuration file, specify the Terraform resources for the module. The Terraform resources should be declared in a file named “resources.tf” and should be located in the root of the Terraform module directory.

Step X:

In the terragrunt configuration file, specify the Terraform provisioners for the module. The Terraform provisioners should be declared in a file named “provisioners.tf” and should be located in the root of the Terraform module directory.

Step XI:

Run “terragrunt apply” to apply the Terraform code in the module.

Terragrunt will fetch the Terraform code for the module from your Git repository, generate a Terraform plan, and apply the Terraform code.

You can use Terragrunt to manage Terraform modules that are stored in a central Git repository. This makes it easy to share Terraform modules between team members and reduces redundancy in your Terraform code.

Factorize version.tf and providers.tf

When you are using Terraform modules, it is best to factor out the “version.tf” and “providers.tf” files into a separate file called “versions.tf” and place it in the root of your Terraform code directory.

The “version.tf” file should contain the following Terraform code:

terraform {

required_version = “${var.terraform_version}”

}

variable “terraform_version” {

default = “0.12.24”

}

The “providers.tf” file should contain the following Terraform code:

provider “aws” {

version = “${var.aws_provider_version}”

region = “${var.aws_region}”

}

variable “aws_provider_version” {

default = “~> v0.13”

}

variable “aws_region” {

default = “us-east- > 01”

}

Factoring out the Terraform version and provider information into a separate file will make it easier to manage your Terraform code and reduce redundancy. Terraform modules should be written using Terraform 0.12 or later. The AWS provider should be used with Terraform 0.13 or later.

Migrate the main.tf file to Terragrunt

If you’re using Terraform, chances are that you’re also using Terragrunt to manage your Terraform code. Terragrunt is a great tool for keeping your Terraform code DRY (Don’t Repeat Yourself).

One way to reduce redundancy in your Terraform code is to migrate your main.tf file to Terragrunt. This will allow you to keep all of your Terraform code in one place, and it will also make it easier to manage your dependencies.

Here’s how you can do it:

First, create a new file called terragrunt.hcl in the root of your project directory.

Next, copy the contents of your main.tf file into the terragrunt.hcl file.

Finally, update the Terraform block in your terragrunt.hcl file to point to the new location of your Terraform code.

What about the input values passed to the module on call?

The nice thing about Terragrunt is that it will automatically pass any input values declared in your Terraform module to the Terraform binary. This means that you don’t need to declare them again in your terragrunt.hcl file.

And that’s it! By migrating your main.tf file to Terragrunt, you can reduce redundancy in your Terraform code and make it easier to manage your dependencies.

Define the staging environment

Now that we have our Terraform code written, it’s time to move on to the next phase:

Creating a staging environment:

Creating a staging environment is important for several reasons. First, it allows us to test our code in a safe and isolated environment before deploying it to production. Second, it gives us a chance to verify that all of the Terraform resources we’ve created are working as expected. Finally, it provides us with a fallback option in case something goes wrong when we deploy our code to production.

There are many ways to create a staging environment, but for this blog post, we’ll focus on using Terragrunt. Terragrunt is a tool that helps you manage Terraform code, and it’s especially useful for creating and maintaining staging environments.

To create a staging environment with Terragrunt, you first need to define a terragrunt.hcl file in your Terraform code directory. The terragrunt.hcl file is used to configure Terraform runs, and it’s where you’ll specify the location of your Terraform state files and any Terraform variables that you want to override. In the terragrunt.hcl file, you’ll also need to specify the backend type (we recommend using S three) and the region in which you want to deploy your code.

Once you’ve defined the Terrgrunt configuration file, you can initialize your Terraform working directory and deploy your code to the staging environment using the following commands:

terragrunt init

terragrunt apply

Initializing your Terraform working directory will download any Terraform modules that you’ve specified in your Terraform code. Once the Terraform modules have been downloaded, Terragrunt will run a terraform init command to initialize them. After initializing the Terraform modules, Terragrunt will run a terraform apply command to deploy your code to the staging environment.

You can access your newly created staging environment by going to the AWS console and navigating to the region in which you deployed your code. From there, you should see all of the Terraform resources that you created in your Terraform code.

Now that we’ve covered the basics of creating a staging environment, let’s move on to the next step:

Creating a production environment:

Creating a production environment is similar to creating a staging environment, but there are a few key differences that you need to be aware of. First, you’ll need to create a new Terraform state file for your production code. This is because Terraform state files are environment-specific, and you don’t want your staging and production environments to share the same state file. Second, you’ll need to specify different values for some of the Terraform variables that you’re overriding in your terragrunt.hcl file. For example, you’ll need to use a different AWS region when deploying your code to production.

Once you’ve created a new Terraform state file and updated your Terrgrunt configuration file, you can deploy your code to the production environment using the following commands:

terragrunt init –reconfigure

terragrunt apply

The terragrunt init –reconfigure command will download any new Terraform modules and initialize them. The terraform apply command will then deploy your code to the production environment.

You can access your newly created production environment by going to the AWS console and navigating to the region in which you deployed your code. From there, you should see all of the Terraform resources that you created in your Terraform code.

Merging infrastructure repositories of all our APIs

We Terraform to manage our AWS infrastructure and Terragrunt to keep our Terraform code DRY. Our API repositories each have their own Terraform code in a directory called “terraform”. When we merge pull requests into master, we run a script that automatically runs Terraform fmt on all the files in the “terraform” directories of the merged branches. This has caught a lot of redundant Terraform code that can be easily removed with Terragrunt’s terragrunt apply-all command.

Here are the steps we follow to reduce redundancy in our Terraform code with Terragrunt:

First, we create a new file called main.tf in the root of our repository. This fil changes to master.

By following these steps, we are able toe contains all of our Terraform code that we want to share across all of our API repositories. We then add the following lines to our main.tf file:

module “api” {

source = “../terraform-modules/api”

}

This tells Terraform to look for the module in the ../terraform-modules/api directory. Next, we run the terragrunt apply-all command in the root of our repository. This will apply all of the Terraform code in the main.tf file to each of our API repositories. Finally, we commit and push our changes to master.

Conclusion:

So, Terraform is great and all but it has some issues with its codebase that we need to address. We’ve talked about the application itself and how to refactor the Terraform code for better maintainability. But what about the input values passed to the module on call? How do we handle that? And what about our staging environment? Stay tuned for part 3 where we will cover all of that and more! In the meantime, if you have any questions or want us to help you get started with Terragrunt, Contact us today to get started.

 

 

Case Studies

Schedule a free consultation

     

Author

EPIQ

Leave a comment

Your email address will not be published.