Terraform Basics Refresher

Quick Terraform refresher: what Terraform is, core concepts, dependency management, execution model, files, and best‑practice workflow for multi‑env IaC.

1. What Terraform Is

Terraform is an Infrastructure as Code (IaC) tool by HashiCorp for defining, provisioning, and managing cloud infrastructure declaratively via HCL (HashiCorp Configuration Language).

Terraform manages infrastructure lifecycle — create, update, destroy — by comparing your desired configuration to the actual state.


2. Core Concepts

a. Providers

Plugins that enable Terraform to interact with cloud or service APIs.

provider "aws" {
  region = "eu-central-1"
}

b. Resources

Define infrastructure components (e.g., EC2, S3, etc.).

resource "aws_instance" "app_server" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t3.micro"
}

c. Data Sources

Read-only access to existing data or resources.

data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["099720109477"]
}

d. Variables

Enable parameterization and flexibility.

variable "instance_type" {
  type    = string
  default = "t3.micro"
}

Use as var.instance_type.

e. Outputs

Expose values after provisioning.

output "instance_ip" {
  value = aws_instance.app_server.public_ip
}

f. State

Tracks deployed infrastructure and relationships. Enables Terraform to detect drift and manage updates efficiently. Stored locally or remotely (terraform.tfstate).

g. Modules

Reusable configuration units — each folder with .tf files is a module.

module "network" {
  source     = "./modules/vpc"
  cidr_block = "10.0.0.0/16"
}

h. Backends

Define where state is stored (local, S3, GCS, Terraform Cloud, etc.).

terraform {
  backend "s3" {
    bucket = "my-terraform-state"
    key    = "envs/prod/terraform.tfstate"
    region = "eu-central-1"
  }
}


3. Terraform Workflow

StepCommandPurpose
1️⃣terraform initInitialize project, download providers/modules
2️⃣terraform validateValidate syntax and configuration
3️⃣terraform planPreview intended changes
4️⃣terraform applyApply desired changes
5️⃣terraform destroyRemove all resources
6️⃣terraform fmtFormat code
7️⃣terraform showDisplay current state

4. Dependency Management

Terraform builds a dependency graph automatically based on references. You can also specify explicit dependencies:

resource "aws_instance" "app" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"
  depends_on    = [aws_vpc.main]
}


5. Execution Model

  1. Read Configuration – Parse .tf files.
  2. Refresh State – Sync with real infrastructure.
  3. Plan & Apply – Execute changes to match desired state.

6. Common Files and Structure

main.tf          # resources
variables.tf     # variable definitions
outputs.tf       # outputs
provider.tf      # providers and backend
terraform.tfvars # variable values


References