# 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.

Course: [Terraform](https://devops.rajeev.pro/courses/terraform), lesson 15. About 25 minutes, intermediate. Source: https://devops.rajeev.pro/courses/terraform/15-scaling-terraform

## What you will learn

- Recognise the signs that a state has grown too big
- Split a configuration by layer and owner, and share values with outputs
- Read another state's outputs with terraform_remote_state, and know the alternatives
- Explain what Terragrunt adds and when it's worth it
- Show the monthly cost change of a plan with Infracost

> **Lab status.** **Verified lab:** terraform_remote_state between two projects (local backend). Run on Terraform 1.17.1; the output shown is real. <br />**Code walkthrough:** Terragrunt, Infracost, tag lookups and SSM parameters: explained, not run. <br />**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.

> **Figure.** Before: one state, everything.tfstate, holding the VPC, subnets, NAT, RDS, Redis, 40 app services, IAM and DNS: 900 resources, plans take minutes, it locks everyone and the blast radius is everything. After: three states, network.tfstate with outputs vpc_id and subnets, data.tfstate with RDS and Redis, and app.tfstate, which reads the network outputs with a terraform_remote_state data source. Tools on the right: Terragrunt, a wrapper for shared backend and inputs across many small configs, and Infracost, which posts the monthly cost change of a plan on the pull request.
>
> Small states joined by outputs: faster plans, fewer collisions, smaller mistakes.

## 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:

```hcl
# 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:

```hcl
# 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"
}
```

```text
$ 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
```

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 share             | How the app gets the VPC ID                                                                                | Good                                                                         | Watch out for                                          |
| ------------------------ | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------ |
| `terraform_remote_state` | Reads the network state's outputs                                                                          | Simple; values always match the network's latest apply                       | Needs read access to the whole state, secrets included |
| Lookup by tag            | `data "aws_vpc" "main" { tags = { Name = "shop-prod" } }`                                                  | No access to anyone's state; reads the real resource                         | Depends on consistent tags                             |
| Published parameters     | The network writes `aws_ssm_parameter` values; the app reads them with the `aws_ssm_parameter` data source | Explicit contract, fine-grained IAM per value, usable by non-Terraform tools | One 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):

```hcl
# 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:

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

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.

## 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.

- You need: Two empty folders, split/network and split/app
- You'll have: split/network and split/app

```sh
$ (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

- Count the resources in a project with `terraform state list | wc -l` and time `terraform plan`.
- Create a network project with outputs and an app project that reads them with terraform_remote_state.
- Change an output in the network project, apply, and re-plan the app project.
- Read the Terragrunt quick start and sketch a terragrunt.hcl for one environment.
- Do the mini mission and keep both project folders.

## Quiz

1. Which is a sign a state should be split?
   - It has 20 resources
   - **Plans take minutes, every team waits on the same lock, and a small change can touch unrelated systems** (answer)
   - It uses two providers
   Why: Big states are slow to refresh, block people on one lock, and make every apply risky. Split by layer and owner.

2. How does the app configuration get the network's VPC ID after a split?
   - By copying the ID into a variable by hand
   - **From the network state's outputs, through a terraform_remote_state data source, or by looking the VPC up by tag with a data source** (answer)
   - By sharing one state file
   Why: Outputs are the contract between states. Lookups by tag avoid giving the app read access to the whole network state.

3. What does Terragrunt mainly add?
   - A new cloud provider
   - **A thin wrapper that removes repetition across many small configurations, such as backend settings, inputs and dependencies between them** (answer)
   - A replacement for state
   Why: Terragrunt generates backend and provider config, passes outputs between units, and runs commands across many folders.

## Resources

- [The terraform_remote_state data source](https://developer.hashicorp.com/terraform/language/state/remote-state-data) (HashiCorp)
- [Terragrunt documentation](https://terragrunt.gruntwork.io/docs/) (Gruntwork)
- [Infracost documentation](https://www.infracost.io/docs/) (Infracost)
- [Recommended practices for structuring workspaces](https://developer.hashicorp.com/terraform/cloud-docs/recommended-practices) (HashiCorp)
