How to use Terragrunt? | jhooq (2023)


Terragrunt is an additional wrapper built on top of Terraform. terraform is greatinfrastructure as codeTool to manage your cloud infrastructure. But as project size grows and you need to manage multiple environments (development, test, staging, production, etc.), you'll find that Terraform has a lot of gaps to manage a large and complex project.

Challenges with Terraform -If you manage the infrastructure of multiple environments (development, test, staging and production, etc.) with Terraform, here are the challenges you can solve with Terraform:

  1. code redundancy -Multiple copies of the same code for each environment.
  2. Manual code update -If the same variables are used for all environments, you must remember and manually update each variable.

Terragrunt for gruntswas designed to improve the deficiencies around Terraform to effectively manage infrastructure code, allowing developers to use the same code without any duplication, keeping Terraform code dry. Terragrunt not only helps you manage your Terraform workspaces effectively, but can also help you with various Terraform modules, remote Terraform state management, etc.

This guide will help you get started with Terragrunt and you will find what you are looking forsample codesfor your reference. It will be a very beginner's guide for anyone who wants to learn Terragrunt and in this guide we will give a basic example of how to do it.Configuring EC2 instance with Terragrunt for DEV and TEST

Index

  1. How do I install Terragrunt?
  2. Write your first Terragrunt implementation using the ec2-instance module.
  3. Execution: Terragrunt plans, Terragrunt applies and Terragrunt destroys
  4. Verify the EC2 instance on AWS manually using the AWS console and using the Terragrunt output
  5. Delete AWS resources with - Terragrunt Destroy
  6. File handling and local values
  7. Input handling and variable precedence
  8. Summary

1. How do I install Terragrunt?

Before installationground gruntsMust meet a prerequisite through installationTerraformarbecause Terragrunt is just a wrapper around Terraform, so using TerragruntYou must install Terraform.

There are a few ways to install Terragrunt:

1.1 Manually download the Terragrunt binary

  1. Descargar- Navigate to the GitHub release pages ofgruntwork-io/terragruntand download the binary based on the operating system of your choice.(At the time of writing this blog v0.37.1 was the latest from Gruntwork)
    How to use Terragrunt? | jhooq (1)
  2. rename- Change the name of the downloaded binary toBoden.
  3. make executable- Change the permission of the binary to make it executable.
1chmod u+x terragrunt
  1. Move the binary to/usr/local/bin(Linux y Mac)
1mv terragrunt /usr/local/bin/terragrunt

Here is my screenshot of/usr/local/bindirectory after installation -

How to use Terragrunt? | jhooq (2)

1.2 Install Terragrunt using the package manager

If you don't want to install Terragrunt manually, you can opt for the package manager based on your choice of OS.

  1. windows-For windows you can trustchocolate milkPackaging Manager -
1choco installs terragrunt
  1. MacOSFor Mac, you can install it usingSelf made-
1Prepare to install Terragrunt
  1. Linux-For Linux you can use homebrew like Mac or use manual installation. ForArch-LinuxUsers can use the following installation command:
1Pacman-S Terraground
  1. FreeBSDGericName- You can install it withPackage-
1Terragrunt installation package

1.3 Check the installation of Terragrunt

After installing Terragrunt, you can verify the installation by running the following command

1Terragrunt version
(Video) Getting started with Terragrunt

How to use Terragrunt? | jhooq (3)

(*Note: at the time of writing this post, the latest version of Terragrunt is v1.2.0)


2. Write your first Terragrunt implementation using the ec2-instance module

NOlast stepWe installed Terragrunt together with Terraform. Now we have the following problem.How do I use Terragrunt to implement cloud infrastructure?

But before answering the question, there are a few points you should know about Terragrunt:

  1. Terragrunt never recommends code duplication.
  2. Terragrunt relies heavily onModuleso we can keep our code dry without messing it up with duplicate code

What configurations are required to write your first Terragrunt implementation?

  1. Terraform-AWSModule (Note: If you work with Google Cloud, seeGoogle module)
  2. You will need itterragrunt.hclto write Terragrunt configuration
  3. use commands -Terragrunt Plan, Terragrunt Enforcement, Terragrunt Exit, Terragrunt Destruction

2.1 Package structure for my Terragrunt project

To keep things simple I'll use the basic example where we're goingSet up an EC2 instance in DEV and TEST environments with Terragrunt

  1. Project structure -Here is the screenshot of my project structure:

How to use Terragrunt? | jhooq (4)

  1. EC2-Instance-Module -To use Terragrun we need to know the modules that we are going to use in our project. But since this is an initial project that we are doing, I have decided to continue.EC2 module.

Here are some opening lines from him.terrgrunt.hclwhere you should mention the reference ofEC2 module-

1#ruta - /terragrunt-ec2/dev/terragrunt.hcl23Terraformar{4 Those = "tfr:///terraform-aws-modules/ec2-instance/aws?version=4.0.0"5}

Nut-

  1. As you can see, we refer to the remote EC2 module with -

Quell-URI -"tfr:///terraform-aws-modules/ec2-instance/aws?version=4.0.0"

  1. Provider Details-The next shot we need to add insideterragrunt.hcland theprovider settings. The provider configuration generally consists of three important elements:
  • Profile
  • Region
  • Credentials: In my current setup I am usingshared_credentials_fileVogelcredentialsbut you can useaccess keymisecret keyrather

Here is the example configuration for the provider that we will use within theterragrunt.hcl-

1#ruta - /terragrunt-ec2/dev/terragrunt.hcl23To generate"Offerer" {4 Far = "proveedor.tf"5 if_exists = "overwrite_terragrunt"6 Content = << FEO7provider "aws" {8profile="Standard"9region = "eu-central-1"10shared_credentials_file = "/Benutzer/rwagh/credenciales"11# access_key = "<insert_your_access_key>"12# secret_key = "<insert_your_secret_key>"13}14weekend15}

walnuts -

  1. The provider can be optional and can be avoided if theprueba.tfthe configuration already exists in itENTwoPROOFSurroundings.

  2. Old provider settings overwrite any existing local provider settings

  3. Start-Next we have to define thestartConfiguration, as we need to provide some required inputs for each Terragrunt implementation. So for our case ofEC2We need the following mandatory parameters:

    • ami
    • Sign
1#ruta - /terragrunt-ec2/dev/terragrunt.hcl23start = {4 ami = "ami-0767046d1677be5a0"5 Sign = {6 Name = "Tutorial Terragrunt: EC2"7 }8}
(Video) How to use Terraform and Terragrunt with Infrastructure Code

2.2 Here is my finished terragrunt.hcl

In the previous steps we reviewed all the configuration parameters necessary to establish theterragrunt.hcl. Here is my completeterragrunt.hcl-

1#ruta - /terragrunt-ec2/dev/terragrunt.hcl23Terraformar{4 Those = "tfr:///terraform-aws-modules/ec2-instance/aws?version=4.0.0"5}678To generate"Offerer" {9 Far = "proveedor.tf"10 if_exists = "overwrite_terragrunt"11 Content = << FEO12provider "aws" {13profile="Standard"14region = "eu-central-1"15shared_credentials_file = "/Benutzer/rwagh/credenciales"sixteen# access_key = "<insert_your_access_key>"17# secret_key = "<insert_your_secret_key>"18}19weekend20}212223start = {24 ami = "ami-0767046d1677be5a0"25 Sign = {26 Name = "Tutorial Terragrunt: EC2"27 }28}

3rd Run – Terragrunt Plan, Terragrunt Application, Terragrunt Exit, and Terragrunt Destruction

3.1 Start of Terragrunt

Let's apply the Terragrunt configuration to create EC2 instances. The first command you should run isbegan to throw.Before executing thehe enters the countrycommand, you must change to the directory in which theterragrunt.hclis available.

1he enters the country

And it should produce output -

How to use Terragrunt? | jhooq (5)

3.2 Mass levels

The next command you can run isthe foundationswhich is also similarterraforming plantDomain. Othe foundationsThe command validates your Terragrunt configuration and returns information about how many resources need to be added, updated, or destroyed.

As it is the first time that we are going to create oneEC2So the example should show that 1 function was added.

1the foundations

Here is the output of the Terragrunt plan command:

How to use Terragrunt? | jhooq (6)
How to use Terragrunt? | jhooq (7)

3.3 Using Terragrunt

If all the Terragrunt settings are correct and there are no errors associated with them, you can simply runApply Terragruntcommand that creates oneEC2 instance

1Apply Terragrunt

Here is the output of the Terragrunt apply command:

How to use Terragrunt? | jhooq (8)
How to use Terragrunt? | jhooq (9)

If you see similar output in your console, it means that you have successfully run your Terragrunt and your EC2 instance has been created. In the next step, we will verify the EC2 instance by signing in to the AWS console.


4. Verify the EC2 instance on AWS

4.1 Manual verification by logging into the AWS console

Let's sign in to the AWS console with the correct region, and then go to the EC2 dashboard.

How to use Terragrunt? | jhooq (10)
(Video) What is Terragrunt and how to use Terragrunt? | Terragrunt Tutorial

As you can see in the screenshot above, we have an EC2 instance running. you can clickinstancesLink for more details about the running instance.

How to use Terragrunt? | jhooq (11)

Here are a few things to check:

  1. Sign- NOterragrunt.hclWe specify the values ​​of the labels asTutorial on Terragrunt: EC2and the same tag name that we can see in the AWS EC2 dashboard.
  2. Instance status -If you successfully started the instance, the state should work.

4.2 Check with the Terragrunt exit command

Terragrunt also offers another useful commandExit Terragruntto review the details of the resources you deployed with Terragrunt.

As in our use case, we create oneEC2 instance, then we could also check the execution details of the EC2 instance using the commandExit Terragrunt

1Exit Terragrunt

Here are the details of the running instance:

How to use Terragrunt? | jhooq (12)


5. Delete AWS resources with -terragrunt Destroy

Now the final command for Terragrunt is:Destroy Terragrunt. In all the previous steps we configured and startedEC2Example. After successfully verifying the instance, let's try to delete/destroy itEC2 instanceandDestroy TerragruntDomain.

Go to the terminal and just run the following command:

1Destroy Terragrunt

After the execution ofDestroy TerragruntCommand successful, then you should see the following output in your terminal:

How to use Terragrunt? | jhooq (13)

How to use Terragrunt? | jhooq (14)

You have now successfully deleted your EC2 instanceDestroy TerragruntDomain.


6. Handling files and local values

We have now seen how to get started with Terragrunt, but there is one more important feature of Terragrunt that you should know about.stock files. With Terragrunt you canstock filesSo you can define both general input variables and specific environment variables.

For example -We took two environments for this tutorial i.e. DEVELOPMENT and TEST. To make our Terragrunt configuration more generic, we can create a common oneshared environment.yamlthat we can put in the root of the project. All common input variables can be defined there.

In addition, we can also create environment-specific values ​​files, i.e. H.-dev-environment.yaml, Testumgebung. Yamlfor DEV and TEST

(Video) Terragrunt? Probably not.

Here is the screenshot of my project structure:

How to use Terragrunt? | jhooq (15)

After creating the values ​​files, we need to define some common variablesDEV, TESTEas well as setting some environment-specific variables for each environment.

  1. Set some variables in common-environment.yaml-As you know this is just a tutorial so let's set one upshared variable for EC2 instance type
1#ruta - /terragrunt-ec2/common-environment.yaml23locations:4 instance type: "t2.micro"
  1. How to add common-environment.yaml?-In the previous step we defined a common variableinstance typebut to use this variable insideterragrunt.hclyou have to useyamldecodefunction within theVerbotenBlock.

Example -

1 #ruta - /terragrunt-ec2/common-environment.yaml23locations{4 env_vars =yamldecode(5archive("pssearch_in_parent_folders("common-environment.yaml")}"),6 )7}

After including theshared environment.yamlWe need to use the variableinstance typeinsidestartSection fromterragrunt-hcl. you can use the samelocationsRules we use when referring to themlocationsinterformar

Example -

1#ruta - /terragrunt-ec2/common-environment.yaml2 3start = {4 ami = "ami-00c90dbdc12232b58"5 instance type =local.env_vars.locals.instance_type6 Sign = {7 Name = "Tutorial Terragrunt: EC2"8 }9}

7. Input handling and variable precedence

Let's take the same example to dig deeper into the input parameters we defined inHCL-Boden. oinput blockHere you can set values ​​for the input parameters of the module.

There are some rules on how you should createinput block-

  1. the block must start withstart

Example -

1start = {2 ami = "ami-00c90dbdc12232b58"3 instance type = "t2.micro"4}
  1. You need to create an input block on it.terragrunt.hcl
  2. as soon as you runApply Terragruntcommand Any values ​​you set in the input block are passed to your module as environment variables.
  3. TF_VAR_XXX- If you have already hiredVariablen.tfWithin your Terraform project or modules, block inputs do not override the values ​​in the block inputs.

7.1 Override variable precedence in Terragrunt

The substitution priority of the variables is the same as in Terraform. However, if the same variables have been defined more than once, the last assigned value will be used.

But if you are interested in knowing the classification, follow these instructions:

  1. Terragrunt will try to load the variables from the beginningEnvironment Variables
  2. Look for the same variables interraform.tfvars
  3. He will also look inside.terraform.tfvars.json
  4. Everything defined in it.auto.tfvars/.auto.tfvars.jsonthey are processed in the order of their file names
  5. All as option files-var/-var-Dateifrom the command line takes precedence

8. Summary

If you have followed all the steps in this blog, I can safely say that you have a good understanding of the basics of Terragrunt and can continue with your Terragrunt implementation. Let's summarize what we've learned so far:

  1. We installed Terragrunt along with Terraform and also reviewed the Terragrunt installation
  2. Set up a small EC2 instance using the Terragrunt EC2 instance module
  3. In addition to the EC2 instance, we also saw how you can design your project structure for different environments (dev, test, staging, production).
  4. We also configure the specific environmentterragrunt.hclforENTwlike thisPROOFSurroundings
  5. If you consider this post as a beginner's Terragrunt tutorial, you'll have a better understanding of how to:
    • include module
    • Definelocationsin your Terragrunt project
    • writeOffererBlock
    • WriteVerboteninput block module
  6. In the blog post, we also discuss how you can outsourceshared environment.yamlso you can adjustvariable localas well as defineSurroundingsspecific variables.

I still have some Terragrunt ideas, so I'll be doing a few more Terragrunt posts in the coming months and will update the list here.Here are my upcoming Terragrunt posts:

  1. Configuring the S3 bucket and remote state file with Terragrunt
  2. Create your own module on Github for Terragrunt
  3. Terragrunt Goto Guide with more examples on - Dependencies, Merge

My Terraform and Terragrunt repositoryYou can find the same code that I used on my blog on GitHubrepository:https://github.com/rahulwagh/Terraform-Topics

(Video) Connecting Terraform to Terragrunt


see more information-ground grunts-

  1. How to use Terragrunt?

Videos

1. Terraform tools review - terragrunt (part 1)
(Anton Babenko)
2. Terragrunt (part 1)
(Anton Babenko)
3. Terraform — Terragrunt
(ExamPro)
4. Terragrunt Command | Terragrunt Tutorial | Getting Start with Terragrunt
(S3CloudHub)
5. How to use Terragrunt Run All to Keep your Terraform code DRY
(env0)
6. How to create AWS RDS Terraform Module and integrate with Terragrunt
(Pablo's Spot)
Top Articles
Latest Posts
Article information

Author: The Hon. Margery Christiansen

Last Updated: 03/14/2023

Views: 5828

Rating: 5 / 5 (50 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: The Hon. Margery Christiansen

Birthday: 2000-07-07

Address: 5050 Breitenberg Knoll, New Robert, MI 45409

Phone: +2556892639372

Job: Investor Mining Engineer

Hobby: Sketching, Cosplaying, Glassblowing, Genealogy, Crocheting, Archery, Skateboarding

Introduction: My name is The Hon. Margery Christiansen, I am a bright, adorable, precious, inexpensive, gorgeous, comfortable, happy person who loves writing and wants to share my knowledge and understanding with you.