Skip to content

Terraform basics and the core workflow

Terraform is HashiCorp’s infrastructure as code (IaC) tool. You describe the infrastructure you want in configuration files, and Terraform works out which API calls turn the current infrastructure into that description. This page covers what Terraform is, the blocks a configuration is made of, and the everyday loop of init, plan and apply. State and modules have their own page: Terraform state and modules.

All complete samples on this page were run with Terraform 1.17.2 on Linux, using only the built-in terraform_data resource so they need no cloud account. Save the files in an empty folder and run the commands shown from that folder. Output is trimmed to the relevant lines.

Topic What it answers
What Terraform is What problem infrastructure as code solves and how Terraform approaches it.
Configuration building blocks Providers, resources, variables, locals, outputs and data sources.
Init and the dependency lock file What terraform init downloads and why .terraform.lock.hcl is committed.
Plan and apply How to review a change before it happens and apply exactly what was reviewed.
Variables and environments How one configuration serves dev, staging and production.
Formatting validation and CI The checks to run on every merge request.

Terraform manages infrastructure through declarative configuration written in HCL (HashiCorp Configuration Language). Instead of clicking through a cloud portal or running a sequence of CLI commands, you write down the end state: “two web servers, one database, this DNS record”. Terraform compares that description with what it last recorded in its state file and with what the provider reports, then proposes the create, update and delete operations needed to close the gap.

That model gives you three practical benefits. Infrastructure changes go through the same review as application code, because they are text files in Git. Environments become repeatable, because staging and production are built from the same configuration with different inputs. And the plan step shows the blast radius of a change before anything is touched.

Terraform talks to platforms through providers: plugins for AWS, Azure, Google Cloud, Kubernetes, GitHub, DNS services and thousands of others, published on the Terraform Registry. The core binary knows nothing about any cloud; it knows how to build a dependency graph, diff it against state, and call providers in the right order.

Licensing matters when you choose a tool: Terraform 1.6.0 and later are released under the Business Source License (BUSL 1.1) rather than an open source license; the license file shipped with Terraform 1.17 names IBM as the licensor. OpenTofu is a community fork of the last open source release and is largely compatible at the language level. HCP Terraform (formerly Terraform Cloud) is HashiCorp’s hosted service for remote runs, state storage and policy.

Pitfalls:

  • Treating Terraform as a script runner. If you need imperative steps (configure an OS, deploy an app build), use a configuration tool such as Ansible or a pipeline step. Terraform is for the resources themselves.
  • Mixing manual changes with Terraform. A setting changed in the portal is “drift”: the next plan will try to revert it. Decide which tool owns each resource.

Terraform reads every .tf file in the working directory as one configuration; file names are only for humans. The blocks you meet first are:

  • terraform sets the required Terraform version, required providers and the backend for state.
  • provider configures a provider instance (region, credentials source, default tags).
  • resource declares an object Terraform creates and manages, such as a virtual network or a storage bucket.
  • data reads an existing object Terraform does not manage, such as the latest image ID or an existing DNS zone.
  • variable declares an input. It can have a type, a default, a description and validation rules.
  • locals names an intermediate expression so you do not repeat it.
  • output exposes a value after apply, to the CLI, to a parent module or to another configuration.

Resources reference each other by address (aws_subnet.app.id). Those references are how Terraform learns the dependency order, so you rarely need depends_on.

The OrdersPortal sample below uses a validated variable, a locals block, a counted resource and an output. terraform_data is a built-in resource that stores a value in state; it stands in for a real cloud resource.

main.tf
terraform {
required_version = ">= 1.9"
}
variable "environment" {
type = string
description = "Deployment environment for OrdersPortal."
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "environment must be dev, staging or prod."
}
}
variable "instance_count" {
type = number
default = 2
}
locals {
name_prefix = "ordersportal-${var.environment}"
tags = {
app = "ordersportal"
environment = var.environment
}
}
resource "terraform_data" "web" {
count = var.instance_count
input = {
name = "${local.name_prefix}-web-${count.index + 1}"
tags = local.tags
}
}
output "web_names" {
value = [for w in terraform_data.web : w.output.name]
}

A real configuration would add a required_providers entry and a provider block, for example the hashicorp/aws provider with a region, and replace terraform_data with resources such as aws_instance.

Pitfalls:

  • Using count for things that have identity. Removing the first item of a counted list renumbers the rest and Terraform destroys and recreates them. Use for_each with stable keys when items can be added or removed independently.
  • Hard-coding credentials in provider blocks. Providers read credentials from environment variables, CLI profiles or workload identity; keep secrets out of .tf files.

terraform init prepares a working directory. It configures the backend that stores state, downloads the providers named in required_providers (and any remote modules) into .terraform/, and writes or checks .terraform.lock.hcl. Run it once after cloning, and again whenever you add a provider or module or change the backend.

Terminal window
terraform init
Initializing the backend...
Initializing provider plugins...
- terraform.io/builtin/terraform is built in to Terraform
Terraform has been successfully initialized!

The lock file records the exact provider versions and their checksums that were selected. Commit it. Without it, two engineers running init a week apart can get different provider versions from the same ~> 6.0 constraint, and a CI run can behave differently from a laptop. Upgrade providers deliberately with terraform init -upgrade and review the lock file change in the merge request.

Do not commit .terraform/; it is a local cache.

Pitfalls:

  • Lock file generated on one platform only. The lock file stores checksums per platform. If developers use macOS and CI uses Linux, run terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 so both are recorded.
  • Wide version constraints with no lock file. That combination is how a provider major release breaks a pipeline overnight.

The plan step is what makes Terraform safe to operate. terraform plan refreshes what it knows about real objects, compares them with the configuration, and prints the actions it would take: + create, ~ update in place, -/+ replace, - destroy. Nothing changes during a plan.

Validation rules run during planning, so bad input fails early:

Terminal window
terraform plan -var environment=qa
Error: Invalid value for variable
on main.tf line 5:
5: variable "environment" {
│ var.environment is "qa"
environment must be dev, staging or prod.

For anything shared, save the plan to a file and apply that file. Applying a saved plan performs exactly the reviewed actions; if the state changed in the meantime, Terraform refuses the stale plan instead of improvising.

Terminal window
terraform plan -var environment=staging -out=staging.tfplan
terraform apply staging.tfplan
Plan: 2 to add, 0 to change, 0 to destroy.
Saved the plan to: staging.tfplan
...
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
Outputs:
web_names = [
"ordersportal-staging-web-1",
"ordersportal-staging-web-2",
]

Run the same plan again and Terraform reports No changes. Your infrastructure matches the configuration. That idempotence is the property to protect: a plan that always shows changes usually means a provider default or a computed value is fighting your configuration.

terraform destroy is a plan with every resource marked for deletion; it also asks for confirmation. Use it for short-lived environments, and protect long-lived resources with lifecycle { prevent_destroy = true }.

Pitfalls:

  • Reading only the summary line. “1 to change” can be a harmless tag or a replaced database. Look for -/+ and the # forces replacement marker.
  • Saved plans contain secrets. A plan file includes the values Terraform will write, so store it as a short-lived, access-controlled CI artifact.

Input variables are how one configuration serves several environments. Terraform assigns them from, in increasing order of precedence: environment variables named TF_VAR_<name>, a terraform.tfvars file, a terraform.tfvars.json file, *.auto.tfvars files in lexical order, and then -var-file and -var options in the order they appear on the command line. Variables with no default and no value are prompted for interactively, which you should disable in automation with -input=false.

A common layout keeps one .tfvars file per environment next to the configuration:

staging.tfvars
environment = "staging"
instance_count = 2
Terminal window
terraform plan -var-file=staging.tfvars -out=staging.tfplan
Plan: 2 to add, 0 to change, 0 to destroy.
Saved the plan to: staging.tfplan

Mark secret inputs with sensitive = true so Terraform redacts them in plan and apply output, and pass them through TF_VAR_ environment variables from your CI secret store rather than committing them in a .tfvars file. Redaction is about display only; the state page explains why the value is still stored.

Each environment must also use its own state. That usually means a separate backend key per environment (for example ordersportal/staging/terraform.tfstate), set with a partial backend configuration at init time, or separate root folders per environment that call shared modules.

Pitfalls:

  • One state for all environments. A staging plan that can see production resources can also destroy them.
  • Defaults that are only right for one environment. Give environment-specific variables no default, so a missing value fails the plan instead of silently creating a production-sized resource in dev.

A small set of commands catches most problems before a human reviews the plan:

  • terraform fmt -check -recursive fails if any file is not in canonical format. Run terraform fmt -recursive locally to fix it.
  • terraform validate checks syntax, references and types without contacting providers’ APIs (it needs init first, which can run with -backend=false).
  • terraform plan -input=false -out=tfplan produces the plan the reviewer approves.
  • terraform test runs .tftest.hcl test files, useful for modules.

A typical merge request pipeline runs fmt, validate and plan, posts the plan as a comment or artifact, and runs apply of that saved plan only after approval on the main branch. The same flow works in GitLab CI/CD, GitHub Actions or TeamCity; HCP Terraform provides it as a hosted service.

Terminal window
terraform fmt -check -recursive
terraform init -input=false
terraform validate
terraform plan -input=false -var-file=staging.tfvars -out=tfplan
Success! The configuration is valid.
Plan: 2 to add, 0 to change, 0 to destroy.

Pitfalls:

  • Applying from laptops. It bypasses review, uses personal credentials and makes the audit trail incomplete. Apply from the pipeline with a dedicated identity.
  • Running plan and apply in different jobs without the saved plan. The apply job would re-plan against whatever changed since review.
You want to Use
Review a change before it happens terraform plan -out=... and review the saved plan
Apply exactly what was approved terraform apply <planfile>
Catch style and reference errors fast terraform fmt -check and terraform validate
Serve several environments Per-environment .tfvars and per-environment state
Reuse the same infrastructure shape Modules

What does terraform plan compare? The configuration, the last recorded state, and the current real objects as reported by providers during refresh. The plan is the set of actions that makes real infrastructure match the configuration.

Why commit .terraform.lock.hcl but not .terraform/? The lock file pins the selected provider versions and checksums so every run uses the same providers. .terraform/ is a local download cache that init rebuilds.

What is the difference between count and for_each? count creates instances addressed by index, so removing an item in the middle shifts the others and causes replacements. for_each addresses instances by map key or set element, so items keep their identity when others are added or removed.

Why apply a saved plan instead of running terraform apply directly? A saved plan applies exactly the reviewed actions, and Terraform rejects it if state changed since it was created. A bare apply re-plans and might do something different from what was reviewed.

Senior scenario: a teammate’s plan for a small tag change shows a database being replaced. What do you do? Stop and read the plan for the attribute marked # forces replacement; it is often an immutable argument changed by a provider upgrade, a renamed resource, or a refactor without a moved block. Check the lock file diff and recent refactors. Fix the cause (pin the provider, add a moved block, revert the argument) until the plan is an in-place update, and add prevent_destroy to stateful resources so a future mistake fails the plan instead of deleting data.