Lesson 1 of 8 · 11 min · Getting started

Infrastructure as Code and the Terraform workflow

Covers: Terraform 1.17; local, random providers. Updated 13 Nov 2026. Part of the DevOps Engineer roadmap.

What you will learn

  • What infrastructure as code (IaC) is and why teams use it
  • Declarative versus imperative, and how Terraform differs from scripts
  • The core workflow: init, fmt, validate, plan, apply, destroy
  • How to read a plan
  • The files Terraform creates and which belong in Git

In simple words

You can build servers and networks by clicking in a web console, but clicks can't be reviewed, repeated or undone easily. Infrastructure as code means writing down what you want in a file. Terraform reads that file, shows you what it is going to change, and makes the cloud match it.

Words to know

  • Infrastructure as code (IaC): describing servers and networks in files instead of creating them by hand.
  • Declarative: you describe the result you want, not the steps to get there.
  • Plan: Terraform's preview of what it will add, change or delete.
  • Apply: carrying out the plan.

From clicking to code

Creating servers, networks and databases through a web console is quick the first time and a disaster the tenth: nobody remembers what was clicked, environments drift apart, and rebuilding after a failure takes days. Infrastructure as Code treats infrastructure like software:

  • described in text files kept in Git (history, review, rollback, audit),
  • reproducible: the same code creates the same environment again and again (dev, staging, production, a disaster-recovery copy),
  • reviewed through pull requests before it touches production,
  • automated in pipelines, with fewer manual mistakes,
  • self-documenting: the code is the inventory.

Declarative, not imperative

A script says how: "create a network, then create a server in it, then...". Re-running it creates duplicates or errors. A declarative tool says what: "there should be one network, with this range, and two servers". Terraform (HashiCorp; the open-source fork OpenTofu is compatible) reads your desired state, compares it with what it knows exists, and works out the minimum set of changes (create, update, delete, replace) to get there. Run it twice and the second run changes nothing: idempotent by design.

Terraform is cloud-agnostic: it talks to AWS, Azure, Google Cloud, Kubernetes, GitHub, Cloudflare, Datadog, databases and thousands more through providers. The language is HCL (HashiCorp Configuration Language), readable and mostly declarative. Other tools: CloudFormation (AWS only), Pulumi (real programming languages), Crossplane (Kubernetes-native), Bicep (Azure). Ansible (the next tool in many stacks) is more about configuring what runs inside servers than creating cloud resources. The ideas transfer between all of them.

A first configuration

main.tf:

terraform {
  required_version = ">= 1.6"
  required_providers {
    local  = { source = "hashicorp/local",  version = "~> 2.5" }
    random = { source = "hashicorp/random", version = "~> 3.6" }
  }
}

variable "environment" {
  type        = string
  description = "Deployment environment"
  default     = "dev"
}

resource "random_pet" "name" {
  length = 2
}

resource "local_file" "greeting" {
  filename = "${path.module}/out/${var.environment}-${random_pet.name.id}.txt"
  content  = "Hello from ${var.environment}\n"
}

output "file_path" {
  value = local_file.greeting.filename
}

(We use harmless local providers so you can practise without a cloud account; the workflow is identical for AWS.) Blocks: terraform (settings), variable (input), resource (a thing to manage, TYPE "LOCAL_NAME"), output (a value to show or export).

The workflow

terraform init

Downloads the providers and modules the configuration needs and prepares the working directory.

Initializing the backend...
Initializing provider plugins...
- Installing hashicorp/random v3.9.1...
- Installed hashicorp/random v3.9.1 (signed by HashiCorp)
- Installing hashicorp/local v2.9.1...
Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above.
Terraform has been successfully initialized!

It creates a .terraform/ directory (providers; do not commit) and .terraform.lock.hcl (the exact provider versions and checksums; do commit, so everyone, including CI, uses identical providers). Run init again whenever you add a provider, module or change the backend.

terraform fmt and validate

fmt rewrites files into the canonical style (terraform fmt -check -diff in CI fails when files are not formatted: it flagged our hand-aligned = signs and showed the diff). validate checks syntax and internal consistency without contacting any cloud: Success! The configuration is valid.

terraform plan

Shows what would change, without changing anything. Terraform refreshes its knowledge of existing objects, compares it with your configuration, and prints the actions:

Terraform will perform the following actions:

  # local_file.greeting will be created
  + resource "local_file" "greeting" {
      + content              = <<-EOT
            Hello from dev
        EOT
      + filename             = (known after apply)
      ...
    }

  # random_pet.name will be created
  + resource "random_pet" "name" {
      + id        = (known after apply)
      + length    = 2
      + separator = "-"
    }

Plan: 2 to add, 0 to change, 0 to destroy.

Reading the symbols:

Symbol Meaning
+ create
- destroy
~ update in place
-/+ replace (destroy and create): look for # forces replacement on the attribute that cannot change in place
<= read a data source
(known after apply) value only available after creation (ids, addresses)

The plan is the review artefact. Read it every time, especially the destroy and replace lines and the totals. Save it for exact reproduction: terraform plan -out=tfplan, then terraform apply tfplan applies precisely that plan (and refuses if the state changed meanwhile), which is what CI/CD pipelines do between the review and the apply stages.

terraform apply

Executes the plan, in dependency order, in parallel where possible (default 10 at a time):

local_file.greeting: Creating...
local_file.greeting: Creation complete after 0s [id=9fbfe7ab...]
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

Outputs:
file_path = "./out/dev-immortal-caribou.txt"

Without a saved plan, apply makes a fresh plan and asks you to type yes (-auto-approve skips it: only for automation that already reviewed a plan). If you run plan again now:

No changes. Your infrastructure matches the configuration.

That is idempotency in action. Change an input and only the difference is applied. Changing environment from dev to prod in our config produced:

# local_file.greeting must be replaced
  ~ filename = "./out/dev-immortal-caribou.txt" -> "./out/prod-immortal-caribou.txt" # forces replacement
Plan: 1 to add, 0 to change, 1 to destroy.

The random_pet was untouched (same name), the file resource was replaced because a file's path cannot be changed in place. Always notice replacements of databases, disks and anything with data: a replacement destroys the old one.

terraform destroy

Plans and executes the removal of everything the state manages (terraform plan -destroy to preview). Powerful: protect critical resources (prevent_destroy, deletion protection flags, separate state/permissions for production).

Files and what to commit

File or folder Commit? Purpose
*.tf yes the configuration
.terraform.lock.hcl yes pinned provider versions
*.tfvars yes if no secrets variable values per environment (dev.tfvars)
.terraform/ no downloaded providers and modules
terraform.tfstate, *.tfstate.backup no local state: may contain secrets; use a remote backend
tfplan no binary saved plan, may contain secrets

Add them to .gitignore. A typical project layout:

infra/
  main.tf           # resources
  variables.tf      # inputs
  outputs.tf        # outputs
  providers.tf      # provider and backend settings
  versions.tf       # required_version, required_providers
  terraform.tfvars  # values (or per-environment files)

The file names are conventions; Terraform loads every .tf file in the directory as one configuration.

Using Terraform with a real cloud

Authentication is not in the code: the AWS provider reads credentials from the standard sources (environment variables, ~/.aws, an IAM role, or OIDC in CI), as in the CI/CD course. Never hard-code keys in .tf files. Start with a sandbox account, run plan often, and destroy test resources to avoid bills.

Common mistakes

  • Committing state files or .terraform/.
  • Skipping the plan review and approving blindly.
  • Editing resources in the console after Terraform created them (drift; later lesson).
  • Not committing the lock file, so CI gets different provider versions.
  • No version constraints on providers and Terraform.
  • Running apply from laptops against production with different versions and no record.
  • Treating destroy and replacements lightly.

Try it yourself

  1. Install Terraform (or use the hashicorp/terraform container) and run the configuration above with init, fmt, validate, plan, apply.
  2. Run plan again and read the "no changes" message. Change content and read the update plan.
  3. Change the filename pattern and find the # forces replacement line.
  4. Run plan -out=tfplan, change a variable, then try apply tfplan and see how the saved plan behaves.

Check yourself

What does it mean that Terraform is declarative?

You describe the desired end state; Terraform works out which actions (create, update, delete) are needed to reach it from the current state, and repeated runs converge without changing anything further.

What is the difference between plan and apply?

plan computes and shows the changes without making them; apply performs them. Saving a plan lets you apply exactly what was reviewed.

Which Terraform files should be committed to Git and which not?

Commit .tf files, the .terraform.lock.hcl lock file and non-secret .tfvars. Do not commit .terraform/, state files or saved plans.

What does -/+ in a plan mean?

The resource will be replaced: destroyed and created again, usually because a changed attribute cannot be updated in place.

Interview questions

Why use Terraform instead of the cloud console or CLI scripts?

Reproducibility, review and audit through Git, consistent environments, dependency handling, drift detection and the ability to preview changes. Scripts are imperative and don't track what exists.

What is the purpose of the lock file?

It records exact provider versions and checksums chosen by init, so every machine and CI run uses the same providers, avoiding surprise upgrades.

How do you make sure a reviewed plan is what gets applied?

Save the plan with -out in the review stage and apply that file in the apply stage; the apply fails if the state changed since.

Summary

  • IaC makes infrastructure reproducible, reviewable and automatable; Terraform is declarative and idempotent.
  • Workflow: init → fmt / validate → plan (review!) → apply; plan -out pins the reviewed plan.
  • Read + - ~ -/+, "known after apply" and "forces replacement" carefully.
  • Commit .tf and the lock file; never state files or secrets.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Infrastructure as Code with Terraform for DevOps Engineer and scores every answer, with what to fix.