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:
- code redundancy -Multiple copies of the same code for each environment.
- 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
- How do I install Terragrunt?
- Write your first Terragrunt implementation using the ec2-instance module.
- Execution: Terragrunt plans, Terragrunt applies and Terragrunt destroys
- Verify the EC2 instance on AWS manually using the AWS console and using the Terragrunt output
- Delete AWS resources with - Terragrunt Destroy
- File handling and local values
- Input handling and variable precedence
- 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
- 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)
- rename- Change the name of the downloaded binary toBoden.
- make executable- Change the permission of the binary to make it executable.
1chmod u+x terragrunt
- Move the binary to
/usr/local/bin
(Linux y Mac)
1mv terragrunt /usr/local/bin/terragrunt
Here is my screenshot of/usr/local/bin
directory after installation -
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.
- windows-For windows you can trustchocolate milkPackaging Manager -
1choco installs terragrunt
- MacOSFor Mac, you can install it usingSelf made-
1Prepare to install Terragrunt
- Linux-For Linux you can use homebrew like Mac or use manual installation. ForArch-LinuxUsers can use the following installation command:
1Pacman-S Terraground
- 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
(*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:
- Terragrunt never recommends code duplication.
- 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?
- Terraform-AWSModule (Note: If you work with Google Cloud, seeGoogle module)
- You will need it
terragrunt.hcl
to write Terragrunt configuration - 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
- Project structure -Here is the screenshot of my project structure:
- 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.hcl
where 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-
- 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"
- Provider Details-The next shot we need to add inside
terragrunt.hcl
and theprovider settings. The provider configuration generally consists of three important elements:
- Profile
- Region
- Credentials: In my current setup I am using
shared_credentials_file
Vogelcredentialsbut you can useaccess key
misecret key
rather
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 -
The provider can be optional and can be avoided if theprueba.tfthe configuration already exists in itENTwoPROOFSurroundings.
Old provider settings overwrite any existing local provider settings
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}
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 country
command, you must change to the directory in which theterragrunt.hcl
is available.
1he enters the country
And it should produce output -
3.2 Mass levels
The next command you can run isthe foundations
which 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:
3.3 Using Terragrunt
If all the Terragrunt settings are correct and there are no errors associated with them, you can simply runApply Terragrunt
command that creates oneEC2 instance
1Apply Terragrunt
Here is the output of the Terragrunt apply command:
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.
As you can see in the screenshot above, we have an EC2 instance running. you can clickinstancesLink for more details about the running instance.
Here are a few things to check:
- Sign- NO
terragrunt.hcl
We specify the values of the labels asTutorial on Terragrunt: EC2and the same tag name that we can see in the AWS EC2 dashboard. - 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 Terragrunt
to 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:
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 Terragrunt
Domain.
Go to the terminal and just run the following command:
1Destroy Terragrunt
After the execution ofDestroy Terragrunt
Command successful, then you should see the following output in your terminal:
You have now successfully deleted your EC2 instanceDestroy Terragrunt
Domain.
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.yaml
that 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. Yaml
for DEV and TEST
Here is the screenshot of my project structure:
After creating the values files, we need to define some common variablesDEV, TESTEas well as setting some environment-specific variables for each environment.
- 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"
- How to add common-environment.yaml?-In the previous step we defined a common variable
instance type
but 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 type
insidestartSection 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-
- the block must start with
start
Example -
1start = {2 ami = "ami-00c90dbdc12232b58"3 instance type = "t2.micro"4}
- You need to create an input block on it.
terragrunt.hcl
- as soon as you run
Apply Terragrunt
command Any values you set in the input block are passed to your module as environment variables. - TF_VAR_XXX- If you have already hired
Variablen.tf
Within 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:
- Terragrunt will try to load the variables from the beginningEnvironment Variables
- Look for the same variables interraform.tfvars
- He will also look inside.terraform.tfvars.json
- Everything defined in it.auto.tfvars/.auto.tfvars.jsonthey are processed in the order of their file names
- 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:
- We installed Terragrunt along with Terraform and also reviewed the Terragrunt installation
- Set up a small EC2 instance using the Terragrunt EC2 instance module
- In addition to the EC2 instance, we also saw how you can design your project structure for different environments (dev, test, staging, production).
- We also configure the specific environment
terragrunt.hcl
forENTwlike thisPROOFSurroundings - 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
- In the blog post, we also discuss how you can outsource
shared environment.yaml
so 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:
- Configuring the S3 bucket and remote state file with Terragrunt
- Create your own module on Github for Terragrunt
- 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-
- How to use Terragrunt?