TerraformIntermediate

Terraform Basics: A Comprehensive Guide to Infrastructure as Code

Admin KC
8 min read

TL;DR

Learn the fundamentals of Terraform for infrastructure automation. This guide covers core concepts, basic commands, and best practices for managing cloud infrastructure as code.

Terraform Basics: A Comprehensive Guide to Infrastructure as Code

Executive Summary

Terraform is HashiCorp's infrastructure as code tool: you describe the infrastructure you want in declarative configuration files, and Terraform works out how to create, update, or delete resources to match. This guide covers the building blocks — providers, resources, variables, outputs, data sources, and state — and the core workflow of init, plan, and apply. It also covers the habits that matter from day one: pinning versions, keeping state remote, and structuring a project cleanly. After reading it, you should be able to write a small configuration, run it safely, and know which practices to adopt before the codebase grows.

Why This Matters

The alternative to infrastructure as code is clicking through consoles and running one-off scripts. That works until you need a second environment, a second engineer, or an answer to the question "why does production look like this?" Manual infrastructure cannot be reviewed before it exists, cannot be reproduced after it breaks, and drifts silently as people make fixes under pressure. Terraform's model — a declared desired state, a previewable plan, and a recorded state file — is what makes infrastructure reviewable, repeatable, and recoverable. Learning the basics properly matters because the common beginner mistakes, such as local state and unpinned providers, are exactly the ones that become painful to unwind later.

Core Concepts

Write .tf configuration Plan diff vs state Apply API calls to cloud State source of truth Declarative, not imperative You describe the destination; Terraform computes the route and records it in state. Dashed loop: the next plan compares config against state and reports drift.

Declarative Configuration and Providers

You declare resources; Terraform computes the changes. A provider is the plug-in that teaches Terraform to talk to a platform — AWS, Azure, Google Cloud, Kubernetes, and many others. Providers are declared with a source and a version constraint, and configured per environment:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-west-2"
}

Credentials are deliberately not part of this block in real projects. Providers pick up credentials from their platform's standard chain — environment variables, shared config files, or the identity of the machine or CI role running Terraform. Hard-coding access keys in configuration is a leak waiting for a commit.

Resources

A resource block declares one piece of infrastructure. The first label is the type, the second is your local name for it, and the body sets its arguments:

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  tags = {
    Name = "example-instance"
  }
}

Resources reference each other by address — aws_instance.example.id — and those references are how Terraform builds its dependency graph and orders creation and destruction correctly. Explicit depends_on exists for dependencies Terraform cannot infer, and should be the exception, not the pattern.

Variables, Locals, and Outputs

Variables parameterise a configuration, outputs expose values from it, and locals name expressions you reuse:

# variables.tf
variable "instance_type" {
  description = "EC2 instance type"
  type        = string
  default     = "t2.micro"
}

# outputs.tf
output "instance_ip" {
  description = "Public IP of the instance"
  value       = aws_instance.example.public_ip
}

Give every variable a type and a description. Use validation blocks for values with a fixed set of acceptable answers, and mark secrets sensitive = true so they stay out of CLI output — while remembering they still land in the state file.

Data Sources

Data sources read information that already exists outside the configuration — an AMI published by Canonical, a VPC managed elsewhere, a DNS zone:

data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["099720109477"] # Canonical
}

Prefer a data source over a hard-coded ID whenever the value is owned by someone else; the ID will change, and the lookup will not.

State

Terraform records what it manages in a state file. State maps configuration to real resource IDs, stores the attributes providers return, and lets Terraform compute a precise diff instead of guessing. Two rules follow from this. First, state belongs in a remote backend with locking as soon as anyone shares the configuration:

# Backend configuration for state management
terraform {
  backend "s3" {
    bucket = "terraform-state-bucket"
    key    = "terraform.tfstate"
    region = "us-west-2"
  }
}

Second, state contains sensitive values in plain text, so access to it is access to your infrastructure's secrets. Never commit it to source control.

The Core Workflow

Four commands cover daily work:

terraform init

Downloads providers and modules, configures the backend, and writes a lock file recording the exact provider versions selected. Commit the lock file; it is what makes runs reproducible across machines.

terraform plan

Shows precisely what will be created, changed, or destroyed, without changing anything. Read plans. Surprises belong here, not in apply output.

terraform apply

Executes the plan after confirmation and updates state. In team settings, apply a previously saved plan file so the change you reviewed is the change that runs.

terraform destroy

Removes everything the configuration manages. Useful for ephemeral environments, dangerous everywhere else; treat it accordingly.

Two supporting commands earn their place quickly: terraform fmt normalises formatting (run it in CI with -check), and terraform validate catches syntax and reference errors before a plan ever runs.

Project Layout and Version Pinning

A conventional layout keeps declarations findable as the project grows:

project/
├── main.tf         # Main configuration
├── variables.tf    # Variable declarations
├── outputs.tf      # Output declarations
├── terraform.tfvars # Variable values
└── providers.tf    # Provider configuration

Pin both the Terraform version and provider versions. Unpinned providers upgrade silently and change behaviour under you; constraints plus the lock file make upgrades deliberate, reviewable events:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0.0"  # Use version constraints
    }
  }
  required_version = ">= 1.0.0"
}

Decision Framework

SituationRecommendation
First configuration, learningLocal state, one provider, a handful of resources; run plan before every apply
Second person or CI joinsMove state to a remote backend with locking before anything else changes
Same pattern needed twiceExtract a module rather than copying resource blocks
Value owned outside this configurationData source, not a hard-coded ID or a variable someone must look up
Secret valuesVariables marked sensitive, supplied via environment or a secret store; never committed tfvars
Repeating an environmentSeparate root configurations per environment, not one config with conditional everything

Implementation Checklist

  • [ ] Terraform and provider versions are constrained, and .terraform.lock.hcl is committed
  • [ ] State is in a remote backend with locking and encryption before the configuration is shared
  • [ ] No credentials appear in configuration files; the provider credential chain is used
  • [ ] Every variable has a type and description; secrets are marked sensitive
  • [ ] terraform fmt -check and terraform validate pass in CI
  • [ ] Plans are reviewed before apply, and applies run from saved plan files in team settings
  • [ ] Resources carry consistent tags, including environment and owner
  • [ ] State files and tfvars containing secrets are excluded from source control
  • Trade-offs

    Terraform's declarative model is its strength and its constraint. You describe outcomes, which makes changes predictable, but expressing genuinely procedural logic — ordered multi-step processes, complex conditionals — fights the language. The state file is a single point of operational truth that must be stored, locked, backed up, and access-controlled; teams that ignore that discover it during an incident. Provider quality also varies: the major cloud providers are mature, while smaller providers can lag the APIs they wrap, and every provider upgrade is a change to test rather than a formality. Finally, Terraform manages the resources it creates well and the things that happen inside them — packages, files, application config — poorly; that boundary shapes the next section.

    When Not to Use

  • Configuring software inside machines: use Ansible, Chef, or Puppet for package installation and file-level configuration. Terraform's provisioners exist as a last resort; HashiCorp's own documentation steers you away from them.
  • Kubernetes application workloads: use Kubernetes manifests, Helm, or GitOps tooling for Deployments and Services. Terraform is reasonable for the cluster itself and cloud resources around it.
  • One-off, never-repeated tasks: a short script or the cloud CLI is cheaper than a configuration you must store state for forever.
  • Teams standardised on a general-purpose language: Pulumi or the AWS CDK express infrastructure in TypeScript, Python, or Go and may fit better than HCL.
  • Conclusion

    Terraform's basics are few: providers supply resources, variables and outputs form the interface, state records reality, and init, plan, and apply drive the workflow. The craft is in the surrounding habits — pinned versions, remote locked state, reviewed plans, no credentials in code. Build those habits on your first small configuration and they will still be serving you when the estate is large.

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.