Part 17: Infrastructure as Code - Terraform & OpenTofu
In modern cloud environments, manual resource provisioning—clicking through the AWS Console or running ad-hoc shell scripts—is an anti-pattern. Infrastructure as Code (IaC) treats physical infrastructure configuration with the same rigor as application code, enabling versioning, testing, and automated peer reviews.
Terraform (and its open-source, Linux Foundation-governed fork, OpenTofu) is the undisputed industry standard for declarative multi-cloud orchestration. Master IaC to position yourself as an elite platform engineer. This guide provides a deep architectural breakdown and a complete blueprint of exactly 30 curated resources.
The IaC Architecture & State Lifecycle
Unlike imperative tools (like Ansible or shell scripts) that require you to declare the exact steps to create resources, Terraform and OpenTofu are declarative. You define the target end-state of your infrastructure, and the engine automatically figures out the correct dependency graph and execution plan to reach that target.
[ Your Declarative HCL Code ]
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Terraform Core Engine Graph │
│ 1. Check Dependency Trees & Execution Order │
│ 2. Diff Target Code vs. Live Cloud Status │
│ 3. Reconcile Target State via State Database (state.tfstate)│
└─────────────────────────────────────────────────────────────┘
│
┌────────────────────────┴────────────────────────┐
▼ ▼
[ Local/Remote State File ] [ Cloud APIs (AWS/GCP) ]
* state.tfstate * Spawns physical assets
* Strictly tracks resource mapping * Reconciles configuration
- The State File (
.tfstate):- Acts as the single source of truth, mapping declarative resource declarations to real-world cloud resources.
- Crucial Rule: Because it stores sensitive parameters in plain text (including auto-generated passwords, API credentials, and TLS certificates), NEVER commit state files to version control (Git).
- State Locking:
- In a team environment, multiple engineers applying changes concurrently can corrupt the state file.
- Backends like AWS S3 coupled with DynamoDB enable remote state management and state locking, preventing parallel execution collisions.
- Infrastructure Drift:
- Occurs when resources are modified directly in the cloud console outside of Terraform.
- Running
terraform plancompares the code with both the state file and the live cloud, automatically generating a reconciliation plan to eliminate the drift.
1. Declarative HCL Syntax & State File Lifecycle Management
Master HashiCorp Configuration Language (HCL) syntax and state lifecycles with these 5 resources.
Subtopic Resources
| Resource Name & Metadata | Access Category | Status & Skip Conditions |
|---|---|---|
| Terraform Up & Running by Yevgeniy Brikman (O'Reilly) The definitive guide to IaC architecture and CLI syntax. | Book | Required |
| HashiCorp Certified: Terraform Associate by Zeal Vora (Udemy) Highly-rated video course covering complete syntax and exam prep. | Video Course | Required |
| Terraform Language Documentation: Syntax & Settings (HashiCorp) Official technical manuals for HCL syntax, blocks, and arguments. | Documentation | Required |
| Terraform Lifecycle Explained by TechWorld with Nana (YouTube) Visual breakdown of init, plan, apply, and destroy workflows. | Video Stream | Required |
| HashiCorp Learn: Get Started with Terraform CLI Interactive browser-based playground to run CLI tasks without local setup. | Interactive Sandbox | Required |
Resource Identification & Access
- Terraform Up & Running
- Direct URL:
https://www.oreilly.com/library/view/terraform-up-and/9781098116521/ - Search Identification: Search O'Reilly for
"Terraform Up and Running Yevgeniy Brikman"
- Direct URL:
- HashiCorp Certified: Terraform Associate
- Direct URL:
https://www.udemy.com/course/terraform-certified/ - Search Identification: Search Udemy for
"Terraform Associate Zeal Vora"
- Direct URL:
- Terraform Language Documentation
- Direct URL:
https://developer.hashicorp.com/terraform/language - Search Identification: Search HashiCorp Developer for
"Terraform language HCL syntax"
- Direct URL:
- Terraform Lifecycle Explained
- Direct URL:
https://www.youtube.com/watch?v=l5k1h_M89sk - Search Identification: Search YouTube for
"TechWorld with Nana Terraform Lifecycle"
- Direct URL:
- HashiCorp Learn: Get Started
- Direct URL:
https://developer.hashicorp.com/terraform/tutorials/aws-get-started - Search Identification: Search HashiCorp Developer for
"Get Started with Terraform tutorial"
- Direct URL:
2. Multi-Environment Workspaces & Variable Scopes
Isolate environments dynamically with these 5 curated resources.
Subtopic Resources
| Resource Name & Metadata | Access Category | Status & Skip Conditions |
|---|---|---|
| Terraform in Action by Scott Winkler (Manning) Deep guide on multi-environment setups and custom orchestrations. | Book | Required |
| Mastering Terraform - From Beginner to Advanced (Udemy) Comprehensive video training on variable scopes and local variables. | Video Course | Required |
| Terraform Workspaces: CLI & Cloud (HashiCorp Docs) Official guide on dynamic state isolation across multiple environments. | Documentation | Required |
| Managing Multi-Environment Infrastructure by DevOps Directive Excellent video tutorial detailing staging vs. production parameters. | Video Stream | Required |
| Multi-Environment Variables Isolation Playground (StackBlitz) Interactive configuration sandbox mapping variable hierarchies. | Interactive Sandbox | Alternative (Skip if "Mastering Terraform" by TJ Addington is completed) |
Resource Identification & Access
- Terraform in Action
- Direct URL:
https://www.manning.com/books/terraform-in-action - Search Identification: Search Manning for
"Terraform in Action Scott Winkler"
- Direct URL:
- Mastering Terraform
- Direct URL:
https://www.udemy.com/course/mastering-terraform/ - Search Identification: Search Udemy for
"Mastering Terraform TJ Addington"
- Direct URL:
- Terraform Workspaces: CLI & Cloud
- Direct URL:
https://developer.hashicorp.com/terraform/cli/workspaces - Search Identification: Search HashiCorp Developer for
"CLI Workspaces dynamic state"
- Direct URL:
- Managing Multi-Environment Infrastructure
- Direct URL:
https://www.youtube.com/watch?v=0k5G9_Z8aB4 - Search Identification: Search YouTube for
"DevOps Directive Terraform Multi Environment"
- Direct URL:
- Multi-Environment Variables Isolation Playground
- Direct URL:
https://stackblitz.com/edit/terraform-workspace-variables-sandbox - Search Identification: Search StackBlitz for
"Terraform workspace variables config"
- Direct URL:
3. Writing DRY Reusable Terraform Modules
Encapsulate resources securely by mastering modules with these 5 resources.
Subtopic Resources
| Resource Name & Metadata | Access Category | Status & Skip Conditions |
|---|---|---|
| Terraform Cookbook by Mikael Krief (Packt) Recipe-based guide full of real-world modules and structural patterns. | Book | Required |
| More than Certified in Terraform by Derek Morgan (Udemy) Advanced video series covering complex module blocks and outputs. | Video Course | Required |
| Terraform Modules: Creation & Reusability (HashiCorp) Official documentation on designing nested sub-modules and dynamic blocks. | Documentation | Required |
| How to Write Clean, DRY, Reusable Modules by Anton Babenko Architectural video detailing structural patterns and variables. | Video Stream | Required |
| Interactive Module Architecture Playground (StackBlitz) Interactive sandbox showing file hierarchies and inputs/outputs. | Interactive Sandbox | Required |
Resource Identification & Access
- Terraform Cookbook
- Direct URL:
https://www.packtpub.com/product/terraform-cookbook/9781800207554 - Search Identification: Search Packt for
"Terraform Cookbook Mikael Krief"
- Direct URL:
- More than Certified in Terraform
- Direct URL:
https://www.udemy.com/course/more-than-certified-in-terraform/ - Search Identification: Search Udemy for
"More than Certified in Terraform Derek Morgan"
- Direct URL:
- Terraform Modules: Creation & Reusability
- Direct URL:
https://developer.hashicorp.com/terraform/language/modules - Search Identification: Search HashiCorp Developer for
"Language Modules dynamic blocks"
- Direct URL:
- How to Write Clean, DRY, Reusable Modules
- Direct URL:
https://www.youtube.com/watch?v=gT9x3d6P1kE - Search Identification: Search YouTube for
"Anton Babenko clean reusable Terraform modules"
- Direct URL:
- Interactive Module Architecture Playground
- Direct URL:
https://stackblitz.com/edit/terraform-module-design-playground - Search Identification: Search StackBlitz for
"Terraform nested module directory structures"
- Direct URL:
4. Remote State Locking with AWS S3 & DynamoDB
Secure state synchronization and block concurrency issues with these 5 resources.
Subtopic Resources
| Resource Name & Metadata | Access Category | Status & Skip Conditions |
|---|---|---|
| Terraform in Depth by Robert Hafner (Manning) Deep-dive book on state-locking, security bounds, and recovery. | Book | Required |
| DevOps Bootcamp: Terraform, Ansible, & K8s (Udemy) Hands-on backend provisioning video track in an enterprise context. | Video Course | Required |
| Terraform Backend Types: S3 with Locking (HashiCorp) Official settings schema detailing S3 remote sync and DynamoDB locks. | Documentation | Required |
| Why You Need Remote State and How Locking Works (YouTube) Clear visual video by Ned in the Cloud explaining DynamoDB keys. | Video Stream | Required |
| AWS S3 Backend DynamoDB State Locker Config Simulator Interactive sandbox template demonstrating locking parameters. | Interactive Sandbox | Alternative (Skip if "Terraform in Depth" by Robert Hafner is completed) |
Resource Identification & Access
- Terraform in Depth
- Direct URL:
https://www.manning.com/books/terraform-in-depth - Search Identification: Search Manning for
"Terraform in Depth Robert Hafner"
- Direct URL:
- DevOps Bootcamp: Terraform, Ansible, & K8s
- Direct URL:
https://www.udemy.com/course/devops-bootcamp/ - Search Identification: Search Udemy for
"ZTM DevOps Bootcamp Terraform"
- Direct URL:
- Terraform Backend Types: S3 with Locking
- Direct URL:
https://developer.hashicorp.com/terraform/language/settings/backends/s3 - Search Identification: Search HashiCorp Developer for
"S3 Backend DynamoDB locking"
- Direct URL:
- Why You Need Remote State and How Locking Works
- Direct URL:
https://www.youtube.com/watch?v=FjC311v9B5Q - Search Identification: Search YouTube for
"Ned in the Cloud Terraform remote state locking"
- Direct URL:
- AWS S3 Backend DynamoDB State Locker Config Simulator
- Direct URL:
https://stackblitz.com/edit/aws-s3-backend-dynamodb-locking - Search Identification: Search StackBlitz for
"AWS S3 Backend DynamoDB State Locking"
- Direct URL:
5. Infrastructure Drift & OpenTofu Drift Detection Handlers
Master drift reconciliation and the OpenTofu open-source toolchain with these 5 resources.
Subtopic Resources
| Resource Name & Metadata | Access Category | Status & Skip Conditions |
|---|---|---|
| Infrastructure as Code by Kief Morris (O'Reilly) Industry-standard guide to continuous delivery and drift containment. | Book | Required |
| OpenTofu Deep Dive (Linux Foundation Training) Official comprehensive video track covering open-source IaC migration. | Video Course | Required |
| OpenTofu: Drift Detection & Reconciliation (OpenTofu) Documentation on planning reconciliation runs and fixing manual console drift. | Documentation | Required |
| OpenTofu: The Open-Source Fork Explained (YouTube) Video detailing why OpenTofu split from HashiCorp and its future. | Video Stream | Required |
| OpenTofu CLI Local Drift Reconciliation Playground Browser sandbox verifying drift runs via Mock OpenTofu commands. | Interactive Sandbox | Required |
Resource Identification & Access
- Infrastructure as Code
- Direct URL:
https://www.oreilly.com/library/view/infrastructure-as-code/9781098114671/ - Search Identification: Search O'Reilly for
"Infrastructure as Code Kief Morris"
- Direct URL:
- OpenTofu Deep Dive
- Direct URL:
https://training.linuxfoundation.org/training/opentofu-deep-dive/ - Search Identification: Search Linux Foundation for
"OpenTofu Deep Dive training"
- Direct URL:
- OpenTofu: Drift Detection & Reconciliation
- Direct URL:
https://opentofu.org/docs/ - Search Identification: Search OpenTofu Docs for
"Drift detection state reconcile"
- Direct URL:
- OpenTofu: The Open-Source Fork Explained
- Direct URL:
https://www.youtube.com/watch?v=uD9lKszV3iI - Search Identification: Search YouTube for
"Kelsey Hightower OpenTofu fork explain"
- Direct URL:
- OpenTofu CLI Local Drift Reconciliation Playground
- Direct URL:
https://stackblitz.com/edit/opentofu-drift-reconciliation-sandbox - Search Identification: Search StackBlitz for
"OpenTofu CLI local drift emulation"
- Direct URL:
6. State File Inspection, Import Operations & Refactoring
Refactor and import live assets safely into clean code with these 5 resources.
Subtopic Resources
| Resource Name & Metadata | Access Category | Status & Skip Conditions |
|---|---|---|
| Advanced Terraform: State Management & Refactoring (Udemy) Specialized video course on complex state moves and import blocks. | Video Course | Required |
| Infrastructure as Code: Up and Running (Packt Publishing) Hands-on book focusing on brownfield migrations and import refactoring. | Book | Required |
| Terraform State Management Command Reference (HashiCorp) Official command manual for state mv, rm, show, and moved blocks. | Documentation | Required |
| How to Safely Refactor Terraform with Moved Blocks (YouTube) Visual walkthrough of moved blocks replacing risky state overrides. | Video Stream | Required |
| Refactoring State Moves & Imports Sandbox (StackBlitz) Interactive sandbox practicing safe imports without affecting live clouds. | Interactive Sandbox | Required |
Resource Identification & Access
- Advanced Terraform: State Management & Refactoring
- Direct URL:
https://www.udemy.com/course/advanced-terraform/ - Search Identification: Search Udemy for
"Advanced Terraform State Refactoring"
- Direct URL:
- Infrastructure as Code: Up and Running
- Direct URL:
https://www.packtpub.com/product/infrastructure-as-code-up-and-running/9781804616222 - Search Identification: Search Packt for
"Infrastructure as Code Up and Running"
- Direct URL:
- Terraform State Management Command Reference
- Direct URL:
https://developer.hashicorp.com/terraform/cli/commands/state - Search Identification: Search HashiCorp Developer for
"CLI commands state moved block"
- Direct URL:
- How to Safely Refactor Terraform with Moved Blocks
- Direct URL:
https://www.youtube.com/watch?v=F_fP45zQ9kM - Search Identification: Search YouTube for
"Ned Bellavance Terraform moved blocks"
- Direct URL:
- Refactoring State Moves & Imports Sandbox
- Direct URL:
https://stackblitz.com/edit/terraform-state-refactoring-sandbox - Search Identification: Search StackBlitz for
"Terraform state import moved block playground"
- Direct URL:
Portfolio Project Lab: Multi-Environment AWS Network Infrastructure
Objective
Create a modular, secure, and DRY multi-environment AWS VPC configuration featuring isolated dynamic subnets, S3-backed state locking, and variable overrides per environment.
1. Reusable Modular Network Design
Create the following file hierarchy:
infrastructure/
├── main.tf
├── variables.tf
├── outputs.tf
└── modules/
└── vpc/
├── main.tf
├── variables.tf
└── outputs.tf
Save this as modules/vpc/variables.tf:
variable "vpc_cidr" {
type = string
description = "The primary IPv4 CIDR block for the custom VPC"
}
variable "public_subnet_cidrs" {
type = list(string)
description = "List of CIDRs to provision for public traffic subnets"
}
variable "private_subnet_cidrs" {
type = list(string)
description = "List of CIDRs to provision for isolated private subnets"
}
variable "environment" {
type = string
description = "Execution stage tracking (e.g. dev, prod)"
}
Save this as modules/vpc/main.tf:
# Provision the Virtual Private Cloud (VPC)
resource "aws_vpc" "this" {
cidr_block = var.vpc_cidr
enable_dns_support = true
enable_dns_hostnames = true
tags = {
Name = "${var.environment}-vpc"
Environment = var.environment
}
}
# Query active availability zones within the current AWS region
data "aws_availability_zones" "available" {
state = "available"
}
# Dynamically provision public subnets based on the input CIDR list
resource "aws_subnet" "public" {
count = length(var.public_subnet_cidrs)
vpc_id = aws_vpc.this.id
cidr_block = var.public_subnet_cidrs[count.index]
availability_zone = data.aws_availability_zones.available.names[count.index]
map_public_ip_on_launch = true
tags = {
Name = "${var.environment}-public-subnet-${count.index + 1}"
Environment = var.environment
}
}
# Provision isolated private subnets matching input parameters
resource "aws_subnet" "private" {
count = length(var.private_subnet_cidrs)
vpc_id = aws_vpc.this.id
cidr_block = var.private_subnet_cidrs[count.index]
availability_zone = data.aws_availability_zones.available.names[count.index]
tags = {
Name = "${var.environment}-private-subnet-${count.index + 1}"
Environment = var.environment
}
}
Save this as modules/vpc/outputs.tf:
output "vpc_id" {
value = aws_vpc.this.id
description = "The unique identifier of the provisioned VPC"
}
output "public_subnet_ids" {
value = aws_subnet.public[*].id
description = "List of public subnet resource IDs"
}
output "private_subnet_ids" {
value = aws_subnet.private[*].id
description = "List of private subnet resource IDs"
}
2. Parent Environment Integration & Remote State Configuration
Save this file as main.tf in your root infrastructure/ directory:
terraform {
required_version = ">= 1.5.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
# Enterprise S3 backend with DynamoDB locking
backend "s3" {
bucket = "blog-orizin-tfstate-bucket"
key = "environments/global-vpc/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "blog-orizin-tf-lock-table"
encrypt = true
}
}
provider "aws" {
region = var.aws_region
}
# Dynamic invocation of the custom network module
module "network" {
source = "./modules/vpc"
vpc_cidr = var.vpc_cidr
public_subnet_cidrs = var.public_subnet_cidrs
private_subnet_cidrs = var.private_subnet_cidrs
environment = var.environment
}
Save this as variables.tf in your root infrastructure/ directory:
variable "aws_region" {
type = string
default = "us-east-1"
}
variable "vpc_cidr" {
type = string
default = "10.0.0.0/16"
}
variable "public_subnet_cidrs" {
type = list(string)
default = ["10.0.1.0/24", "10.0.2.0/24"]
}
variable "private_subnet_cidrs" {
type = list(string)
default = ["10.0.10.0/24", "10.0.11.0/24"]
}
variable "environment" {
type = string
default = "dev"
}
Save this as outputs.tf in your root infrastructure/ directory:
output "network_vpc_id" {
value = module.network.vpc_id
}
output "network_public_subnets" {
value = module.network.public_subnet_ids
}
3. Execution Commands
Deploy your infrastructure using isolated workspaces:
# Initialize remote backend configurations
terraform init
# Provision and isolate the "staging" workspace
terraform workspace new staging
terraform workspace select staging
terraform plan -var="environment=staging" -var="vpc_cidr=10.1.0.0/16"
terraform apply -auto-approve -var="environment=staging" -var="vpc_cidr=10.1.0.0/16"
# Provision and isolate the "production" workspace
terraform workspace new production
terraform workspace select production
terraform plan -var="environment=production" -var="vpc_cidr=10.2.0.0/16"
Common Infrastructure as Code Interview Questions
1. Why are Terraform state files considered critical and how should they be secured in production?
- Answer: The state file (
.tfstate) maps declarative HCL resources directly to live physical parameters in your cloud provider, tracks changes, and stores dependency trees. It is highly critical because it contains sensitive parameters (passwords, tokens, configuration credentials) in plain text. Secure it by:- Storing it in an encrypted remote S3 bucket with restricted IAM permissions.
- Implementing DynamoDB state locking to prevent concurrency collisions.
- Strictly adding
.tfstateand.tfstate.backupfiles to your.gitignoreto prevent leaking them to repository logs.
2. Explain the difference between terraform plan and terraform apply.
- Answer:
terraform planis a read-only execution check that parses your codebase, queries live resources via cloud provider APIs, and compares the differences against the current state file to construct an execution chart. It does not modify live assets.terraform applyreads that execution chart and executes the API requests to provision, modify, or destroy real physical assets to reach the declared configuration target.
3. How does OpenTofu differ from Terraform, and why was it created?
- Answer: OpenTofu was created as an open-source, community-governed alternative under the Linux Foundation following HashiCorp’s transition of Terraform from the open Mozilla Public License (MPL v2) to a restrictive Business Source License (BSL). OpenTofu is completely open-source, backward-compatible with legacy HCL modules, and focuses on adding innovative community-led enhancements like client-side encryption options for state files.
Next Steps
Now that you have learned to automate and isolate cloud environments using Terraform, we will proceed to monitor and diagnose these systems under active traffic.
Comments
Comments are powered by giscus. Set
PUBLIC_GISCUS_REPO_IDandPUBLIC_GISCUS_CATEGORY_IDin your environment to enable them.