Terraform

 

1️⃣ Variables

Purpose:
Inputs to your Terraform configuration.

variable "region" { type = string default = "us-east-1" }

👉 Used by providers, resources, and modules
👉 Loaded first


2️⃣ Providers

Purpose:
Tell Terraform which cloud / service API to talk to and how to authenticate.

provider "aws" { region = var.region }

👉 Depend on variables
👉 Initialize during terraform init


3️⃣ Resources

Purpose:
Actual infrastructure objects (EC2, S3, Kafka topic, DB, etc.).

resource "aws_s3_bucket" "data_bucket" { bucket = "my-bucket" }

👉 Depend on providers
👉 Can depend on variables and other resources


4️⃣ Data Sources

Purpose:
Read-only existing infrastructure.

data "aws_vpc" "default" { default = true }

👉 Do not create anything
👉 Used by resources and modules


5️⃣ Modules

Purpose:
Reusable logical groups of Terraform code (like functions).

module "network" { source = "./modules/network" vpc_id = data.aws_vpc.default.id }

👉 Can contain:

  • variables

  • providers

  • resources

  • data sources

  • outputs

👉 Modules depend on inputs passed to them


Relationship (Big Picture)

Variables ↓ Providers ↓ Data Sources ──→ Resources ↓ ↓ Modules

Or more practically:

  • Variables feed everything

  • Providers enable API communication

  • Data sources read existing state

  • Resources create/update infrastructure

  • Modules organize and reuse all of the above


Execution Flow (What Terraform Does Internally)

1️⃣ terraform init

  • Downloads providers

  • Initializes backend

  • Loads modules


2️⃣ terraform plan

Terraform builds a dependency graph:

  1. Loads variables

  2. Configures providers

  3. Reads data sources

  4. Calculates resource dependencies

  5. Shows what will change

👉 Execution order is determined by dependencies, not file order


3️⃣ terraform apply

Terraform executes in this order automatically:

  1. Providers are initialized

  2. Data sources are read

  3. Resources are created/updated/destroyed

  4. Module outputs are calculated

  5. State file is updated


Example Execution Order

variable "vpc_id" {} data "aws_vpc" "existing" { id = var.vpc_id } resource "aws_subnet" "subnet" { vpc_id = data.aws_vpc.existing.id }

Execution:

  1. Read variable vpc_id

  2. Read existing VPC (data source)

  3. Create subnet (resource)


Key Rules to Remember

✅ Terraform does NOT execute top to bottom
✅ It executes based on dependency graph
✅ Use references (resource.id) to control order
✅ Use depends_on only when absolutely necessary


One-Line Summary

Variables provide input → Providers enable APIs → Data sources read → Resources create → Modules organize everything

Comments

Popular posts from this blog

Design Patterns

Hibernate (Java) -- by jps sasadara

AWS Networking & IAM