DevOps.Academy
CoursesCurriculumInterview prepPricing
◔My learningSign in
DevOps.Academy

Free, hands-on DevOps lessons. Made with care in India.

System status

Learn

All coursesLinux roadmapCurriculumInterview questionsCheat sheetsMy learning

Academy

PricingCertificates

Legal

PrivacyTermsContact

devops.rajeev.pro

TerraformLesson 15 of 17
Your progress · 0%
On this page
  1. Splitting state
  2. Terragrunt
  3. Infracost
↖ Course roadmap
Lesson 15 · Scaling Terraform

Scaling Terraform: split state, Terragrunt, Infracost

When one configuration grows too big: split it into smaller states that share data through outputs, keep many configurations DRY with Terragrunt, and see the cost of every change with Infracost.

25 min read · intermediate · hands-on

By the end of this lesson you'll be able to

0 of 5 complete
Lab status

Verified lab: terraform_remote_state between two projects (local backend). Run on Terraform 1.17.1; the output shown is real.
Code walkthrough: Terragrunt, Infracost, tag lookups and SSM parameters: explained, not run.
Cloud lab: Infracost needs an API key; tag and SSM lookups need AWS.

Every Terraform project starts small. Two years later it can hold 900 resources: the VPC, the databases, forty services, IAM and DNS, all in one state. Plans take minutes, everyone waits on one lock, and a typo in a service can show up as a change to the network. This lesson covers how teams break that up and keep it manageable.

Small states joined by outputs: faster plans, fewer collisions, smaller mistakes.© Diagram: DevOps Academy

Small states joined by outputs: faster plans, fewer collisions, smaller mistakes.© Diagram: DevOps Academy

Splitting state

Split along two lines:

  1. How often it changes. The network changes a few times a year, databases a few times a month, apps daily. Things that change rarely shouldn't be refreshed and locked by every app deploy.
  2. Who owns it. The platform team owns the VPC; each service team owns its service. Separate states mean separate permissions and separate review.

A common layout is by layer: network/, data/, platform/ (cluster, shared IAM), then one folder per service, each per environment. Each has its own backend key.

Sharing values: outputs as the contract

After the split, the app needs the VPC ID and subnet IDs that the network creates. The network exposes them as outputs:

# split/network/main.tf
resource "local_file" "vpc" {
  filename = "${path.module}/vpc.txt"
  content  = "vpc-0a12b34c\n"
}

output "vpc_id" {
  value = trimspace(local_file.vpc.content)
}

output "private_subnets" {
  value = ["10.0.1.0/24", "10.0.2.0/24"]
}

(In the lab, a file stands in for a real VPC.) The app reads the network's state with a terraform_remote_state data source:

# split/app/main.tf
data "terraform_remote_state" "network" {
  backend = "local"
  config = {
    path = "../network/terraform.tfstate"
  }
}

resource "local_file" "app" {
  filename = "${path.module}/app.txt"
  content  = "app in ${data.terraform_remote_state.network.outputs.vpc_id}, subnets ${join(" ", data.terraform_remote_state.network.outputs.private_subnets)}\n"
}
$ terraform apply -auto-approve
data.terraform_remote_state.network: Reading...
data.terraform_remote_state.network: Read complete after 0s
...
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
$ cat app.txt
app in vpc-0a12b34c, subnets 10.0.1.0/24 10.0.2.0/24
terraform apply -auto-approve
  • terraforminfrastructure as code
  • applymake the changes
  • -auto-approveskip the yes prompt
cat app.txt
  • catprint a file

With S3 it's the same idea: backend = "s3" and the bucket, key and region in config. Only outputs are visible to the reader, not the network's resources.

The trade-off: remote state reads the whole snapshot

terraform_remote_state only shows you the outputs, but to read them Terraform downloads the entire state snapshot. So the app's credentials need read access to the whole network state file, including any secrets in it, and every reader is coupled to that state's backend and location. HashiCorp's own documentation recommends considering alternatives for this reason. Treat remote state as one option, not the default:

Way to shareHow the app gets the VPC IDGoodWatch out for
terraform_remote_stateReads the network state's outputsSimple; values always match the network's latest applyNeeds read access to the whole state, secrets included
Lookup by tagdata "aws_vpc" "main" { tags = { Name = "shop-prod" } }No access to anyone's state; reads the real resourceDepends on consistent tags
Published parametersThe network writes aws_ssm_parameter values; the app reads them with the aws_ssm_parameter data sourceExplicit contract, fine-grained IAM per value, usable by non-Terraform toolsOne more resource per shared value

A good default for teams: the owning configuration publishes what others may use (SSM Parameter Store, or tags), and consumers read just that. Use terraform_remote_state inside one team, where everyone already has access to both states.

Terragrunt

Splitting creates repetition: thirty folders, each with the same backend block (only the key differs), the same provider block and similar inputs. Terragrunt, an open-source wrapper from Gruntwork, removes it. Each folder gets a small terragrunt.hcl instead (shown, not run here):

# live/prod/app/terragrunt.hcl
include "root" {
  path = find_in_parent_folders("root.hcl") # shared backend and provider settings
}

terraform {
  source = "git::https://github.com/acme/tf-modules.git//app?ref=v1.3.0"
}

dependency "network" {
  config_path = "../network" # read the network unit's outputs
}

inputs = {
  env        = "prod"
  vpc_id     = dependency.network.outputs.vpc_id
  subnet_ids = dependency.network.outputs.private_subnets
}

What it does for you:

  • Generates backend config from one root file, deriving each state key from the folder path, so keys can't be copy-paste mistakes.
  • Passes outputs between units with dependency blocks, and knows the order to apply them in.
  • Runs a command across many units at once (plan everything under live/prod), respecting dependencies.

It's another tool to learn and run, so it pays off when you have many small configurations across several environments and accounts. For a handful of folders, plain Terraform with modules is enough.

Infracost

A plan tells you what will change, not what it will cost. Infracost reads a plan and shows the monthly cost difference using cloud price lists, and can comment it on the pull request. It needs a free API key to fetch prices, so it wasn't run for this course:

$ infracost breakdown --path .                    # cost of the whole configuration
$ infracost diff --path . --compare-to base.json  # change versus the main branch
infracost breakdown --path .
  • .this folder

A pull request that switches t3.micro to m6i.2xlarge across ten instances then arrives with its monthly price increase next to the plan, before anyone approves it. Its CI integrations (GitHub Actions, GitLab CI and others) post the comment automatically. Costs for usage-based services (data transfer, Lambda invocations) are estimates unless you give Infracost a usage file.

In production

Plan the split before the state gets big: by layer (network, data, platform, apps), by environment, and by account. Treat outputs as an API between teams: add freely, remove or rename only with warning. Add a cost check to pull requests early; it's cheap and changes how people choose instance sizes.

⌘
Mini mission

Split a network from an app

Create split/network with a resource and two outputs (vpc_id and private_subnets), apply it, then create split/app that reads those outputs through terraform_remote_state and writes them into a file. Change the network's vpc_id, apply the network, and show the app's next plan picks up the change.

Input: Two empty folders, split/network and split/appOutput: split/network and split/app
Reveal one safe solution
$ (cd split/network && terraform init && terraform apply -auto-approve)
$ (cd split/app && terraform init && terraform apply -auto-approve && cat app.txt)
$ # change the VPC id in split/network/main.tf, apply there, then:
$ (cd split/app && terraform plan)

The app's plan should replace app.txt with the new ID. In the lab, app.txt read app in vpc-0a12b34c, subnets 10.0.1.0/24 10.0.2.0/24.

Try it yourself

0 of 5 steps done

Run each task in your own account or terminal, then tick it off.

Knowledge check

Quick check

Question 1 of 3

Which is a sign a state should be split?

Go deeper

Official reading for this lesson

  • DocsThe terraform_remote_state data sourceHashiCorp ↗
  • DocsTerragrunt documentationGruntwork ↗
  • DocsInfracost documentationInfracost ↗
  • GuideRecommended practices for structuring workspacesHashiCorp ↗

Or get every quiz answer right and it completes itself.

Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.

← PreviousTesting Terraform codeNext lesson →Terraform security: secrets, scanning and policy