Terraform Advanced — Terragrunt Exercises
Practice Terragrunt patterns.
Exercise 1 — Root Config
Task: Write a root terragrunt.hcl that auto-generates S3 backend config with dynamic keys and an AWS provider for us-west-2.
Answer
remote_state {
backend = "s3"
generate = {
path = "backend.tf"
if_exists = "overwrite_terragrunt"
}
config = {
bucket = "mycompany-tf-state"
key = "${path_relative_to_include()}/terraform.tfstate"
region = "us-west-2"
dynamodb_table = "tf-locks"
encrypt = true
}
}
generate "provider" {
path = "provider.tf"
if_exists = "overwrite_terragrunt"
contents = <<EOF
provider "aws" {
region = "us-west-2"
}
EOF
}
Exercise 2 — Child with Dependency
Task: Write a child terragrunt.hcl for an EKS stack that depends on a VPC stack and passes vpc_id and subnet_ids.
Answer
include "root" {
path = find_in_parent_folders()
}
terraform {
source = "../../../modules/eks"
}
dependency "vpc" {
config_path = "../vpc"
mock_outputs = {
vpc_id = "vpc-mock"
subnet_ids = ["subnet-mock"]
}
}
inputs = {
cluster_name = "prod-eks"
vpc_id = dependency.vpc.outputs.vpc_id
subnet_ids = dependency.vpc.outputs.subnet_ids
}
Exercise 3 — Selective Apply
Task: Write the command to apply only VPC and EKS stacks in the prod environment, with parallelism of 1.
Answer
$ cd environments/prod
$ terragrunt run-all apply \
--terragrunt-include-dir "*/vpc" \
--terragrunt-include-dir "*/eks" \
--terragrunt-parallelism 1
Chapter Summary
- Terragrunt eliminates code duplication across environments
path_relative_to_include()auto-generates unique state keysdependencyblocks reference outputs from other stacks- Mock outputs enable
planbefore dependencies are applied run-allapplies entire environments in dependency order