Terraform Plans Changes by Comparing Code with Its State File

In progress

Terraform is a declarative Infrastructure as Code tool: you describe resources in HCL (.tf files) and it creates, changes or deletes real infrastructure to match. It knows what it manages through a state file that maps each resource in the code to an object at the provider. terraform plan compares code, state and reality, and shows the difference before anything changes.

The Core Workflow

terraform fmt       # format the code
terraform init      # download providers and modules, set up the state backend
terraform plan      # show what would be created, changed or destroyed
terraform apply     # make the changes after confirmation
provider "aws" {
  region = "us-east-1"
}

resource "aws_vpc" "main" {
  cidr_block           = "10.0.0.0/16"
  enable_dns_support   = true
  enable_dns_hostnames = true
  tags = { Name = "main-vpc" }
}

What State Buys You

  • Idempotency: applying unchanged code does nothing, because state already matches.
  • Dependencies: Terraform orders creation from references between resources and creates independent ones in parallel.
  • Modules: repeated patterns become a module called several times instead of copied code.
  • Provider-agnostic: the same workflow drives clouds and on-premises platforms through providers.

References

Review cards

Flashcard Why is the state file important in Terraform?

The state file is crucial because it keeps track of the current state of the infrastructure, allowing Terraform to understand what resources exist and their current state, which is necessary for planning and applying changes.

Flashcard Why read the 'destroy' lines of a terraform plan carefully?

Some attribute changes can't be made in place and force replacement: Terraform destroys and recreates the resource, which is how a database gets recreated empty.