Terragrunt for Beginners

Terragrunt Functions

read terragrunt config

In this lesson, we’ll dive into Terragrunt’s built-in function read_terragrunt_config, which reads a Terragrunt HCL file and returns its contents as a map. This enables you to:

  • Dynamically consume inputs, outputs, blocks, and attributes from another configuration.
  • Adapt resources for different environments or setups.
  • Promote modularity, reusability, and DRY infrastructure code.

When you invoke:

read_terragrunt_config("<path/to/file.hcl>")

Terragrunt will:

  1. Parse the specified HCL file.
  2. Serialize its contents into a map.
  3. Expose all blocks and attributes under that map for referencing in your configuration.

Key Benefits

  • Dynamic Configuration: Tailor resources per environment.
  • Modularity: Reuse shared inputs and outputs.
  • Maintainability: Avoid duplication across modules.

Best Practices

PracticeRecommendation
Centralize common inputsStore project-level variables in a root common.hcl.
Use locals for mappingAssign descriptive local names to imported values.
Keep shared configs leanInclude only widely used variables to reduce complexity.
Verify relative pathsEnsure the path passed to the function is correct.

The image outlines best practices for "read_terragrunt_config," highlighting the need for resources to adapt dynamically and access input/output configurations.

Tip

Use clear naming conventions in your common.hcl to avoid confusion when referencing nested attributes.


Example: Sharing Common Variables

Create a root-level common.hcl with project-wide variables:

# common.hcl
inputs = {
  project     = "KodeKloud"
  environment = "dev"
}

In the vpc/ directory, import these inputs using read_terragrunt_config:

# vpc/terragrunt.hcl
terraform {
  source = "tfr://terraform-aws-modules/vpc/aws//?version=5.8.1"
}

locals {
  common_vars = read_terragrunt_config("../common.hcl")
}

inputs = {
  name = "${local.common_vars.inputs.project}-${local.common_vars.inputs.environment}-VPC"
}

What happens under the hood:

  1. Terragrunt reads ../common.hcl.
  2. local.common_vars.inputs contains:
    • project: "KodeKloud"
    • environment: "dev"
  3. The VPC module’s name input resolves to:
KodeKloud-dev-VPC

Warning

Verify the relative path to common.hcl, or Terragrunt will error out with a file-not-found.


Initializing Terragrunt

Run the following in the vpc/ directory:

$ terragrunt init

Expected output:

- Finding hashicorp/aws versions matching ">= 5.30.0"...
- Installing hashicorp/aws v5.52.0...
- Installed hashicorp/aws v5.52.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl ...
Terraform has been successfully initialized!

Next Steps

After initialization, run terragrunt plan to preview changes based on your dynamic inputs.


Watch Video

Watch video content

Previous
Terragrunt Function Overview