Chapter 10 of 12
Course Progress0 of 12 completed (0%)

AWS & Modern Cloud Architecture · Chapter 10 · ~25 min · Advanced

Infrastructure as Code (IaC) with Terraform & CloudFormation

Eliminate manual console "ClickOps" forever: declare cloud topologies in version-controlled code, master Terraform state management with distributed locking, detect out-of-band drift, and build immutable multi-tier architectures.

  • Understand declarative Infrastructure as Code: version control, repeatability, and zero manual console drift
  • Master the Terraform workflow: init, plan, apply, and state file dependency graphs
  • Compare Terraform HCL vs AWS CloudFormation and AWS Cloud Development Kit (CDK)
  • Detect and reconcile out-of-band state drift and lock state safely with S3 & DynamoDB

Infrastructure as Code (IaC) with Terraform & CloudFormation: learn it visually

Automate cloud provisioning with Infrastructure as Code: declarative HCL syntax, Terraform state drift detection, dependency DAG plan graphs, and immutable architecture deployment.

Infrastructure as Code (IaC) with Terraform & CloudFormationAutomate cloud provisioning with Infrastructure as Code: declarative HCL syntax, Terraform state drift detection, dependency DAG plan graphs, and immutable architecture deployment.UNDERSTANDDeclare resourcesFOLLOW THE FLOWPlan the changesAPPLY ITProvision cloudInfrastructure as Code (IaC) with Terraform & CloudFormationAutomate cloud provisioning with Infrastructure as Code: declarative HCL syntax, Terraform state drift detection, dependency DAG plan graphs, and immutable architecture deployment.UNDERSTANDDeclare resourcesFOLLOW THE FLOWPlan the changesAPPLY ITProvision cloud

1Why Infrastructure as Code Matters

In the early days of cloud computing, engineers logged into the AWS Management Console and clicked buttons to create resources. This manual approach—affectionately called "ClickOps"—is catastrophic for production environments:

  • Snowflake Environments: No two environments (dev, staging, prod) are ever truly identical; subtle configuration drift causes bugs that only manifest in production.
  • Zero Audit Trail: There is no record of who modified a firewall rule or resized a database at 2:00 AM.
  • Catastrophic Recovery Time: If an entire AWS Region suffers a failure, manually recreating hundreds of servers, subnets, route tables, and policies takes days.
Idempotency

Repeatable Execution

Running an IaC pipeline ten times produces the exact same end-state as running it once.

Git Review

Pull Request Audits

Every infrastructure alteration goes through code review, linting, and automated security scanning before apply.

Immutable Upgrades

Zero Patch Drift

Instead of mutating running servers, IaC spins up fresh instances with new AMIs and terminates the old fleet.

Concept Check

What is the core distinction between 'declarative' and 'imperative' infrastructure provisioning?

2Architectural Mental Models: ClickOps vs. Remote State

Managing production infrastructure as software requires shifting your mental model from interactive GUIs to version-controlled state reconciliation:

Wrong idea: Clicking through the AWS Console is faster and perfectly fine for production

Engineer A clicks console → Unrecorded security hole → Disaster → Impossible to recreateFlaw: Zero audit trail · snowflake environments · human memory fails during outages

Believing that manually clicking buttons in the AWS Web Console to launch databases and configure VPC subnets saves time without consequences.

Real system: Declare entire topologies in code; review in Git PRs and deploy via CI/CD

Git Commit → Automated Pull Request Review → Terraform CI/CD Deployment100% reproducible environments · instant disaster recreation across regions

Define every VPC, subnet, IAM policy, and RDS cluster in declarative code (Terraform HCL or CloudFormation). Code is peer-reviewed, tested, and tracked in Git history.

3The Terraform Engine: Init, Plan, Apply & State

HashiCorp Terraform is the industry-standard, cloud-agnostic declarative IaC engine. It uses the HashiCorp Configuration Language (HCL) to declare resources.

The Four Pillars of the Terraform Lifecycle:

  1. terraform init: Downloads provider plugins (such as the AWS provider) and initializes the remote backend.
  2. terraform plan: Refreshes state against real AWS APIs and displays an execution diff showing resources to add (+), modify (~), or destroy (-).
  3. terraform apply: Prompts for confirmation and executes the necessary API calls against AWS to reach the desired state.
  4. terraform destroy: Tears down all managed resources in reverse dependency order.
# Standard Remote State Backend Configuration (backend.tf)
terraform {
  required_version = ">= 1.7.0"

  backend "s3" {
    bucket         = "production-terraform-state-us-east-1"
    key            = "core-infra/terraform.tfstate"
    region         = "us-east-1"
    encrypt        = true
    dynamodb_table = "terraform-state-locks" # Prevents concurrent applies!
  }
}
Concept Check

Why is an Amazon DynamoDB table configured alongside Amazon S3 in a Terraform remote backend?

4CloudFormation vs. Terraform vs. AWS CDK

AWS architectures can be deployed using three distinct IaC methodologies:

AWS CloudFormation

AWS Native Stacks

JSON/YAML templates managed natively by AWS. State is stored entirely inside AWS CloudFormation stacks with automated rollback on failure.

Terraform (HCL)

Multi-Cloud Standard

Cross-provider support (AWS, GitHub, Datadog, Snowflake). Explicit plan previews, modularity, and rich ecosystem registry.

AWS CDK

Real Programming Languages

Author infrastructure using TypeScript, Python, or Go. Compiles into standard CloudFormation templates with high-level L2/L3 constructs.

Concept Check

What is 'configuration drift', and how does declarative IaC resolve it?

5Hands-On: Simulate Out-of-Band Console Drift & DAG Graph

Trigger an unauthorized out-of-band edit in the simulated AWS console. Watch how Terraform detects the drift, inspect the execution plan diff, and execute terraform apply to restore compliance:

Terraform Plan & Out-of-Band State Drift Visualizer

Simulate a rogue engineer making out-of-band manual edits in the AWS Web Console. Then observe how Terraform detects the drift and restores compliance.

1. Desired HCL Code (main.tf)
Git HEAD
# aws_instance.webinstance_type = "t3.medium"
# aws_security_group.webingress_ssh = DISABLED
2. State File (terraform.tfstate)
S3 Bucket
Recorded Instance Type:"t3.medium"
Recorded Ingress SSH:Not authorized
3. Live AWS API (Reality)
IN COMPLIANCE
Actual EC2 Instance:t3.medium
Actual Firewall SSH:BLOCKED

6Bug Hunt: Fix the Broken CloudFormation Infrastructure YAML

A junior cloud engineer committed this CloudFormation YAML template to provision a VPC and Subnet. However, the template fails validation due to three resource type and reference bugs:

  • ProductionVpc has an invalid resource type: "AWS::EC2::VPC_INVALID".
  • PublicSubnet attempts to link to a non-existent VPC reference: !Ref NonExistentVpc.

Fix the template so that it compiles and passes CloudFormation validation:

CloudFormation YAML · VPC & Subnet Bug Hunt
YAML

🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.

Need a hint?
  • Change AWS::EC2::VPC_INVALID to standard AWS::EC2::VPC.
  • Change !Ref NonExistentVpc to !Ref ProductionVpc.

7Chapter Knowledge Challenge

Validate your Infrastructure as Code and state reconciliation mastery:

Concept Check 1 of 2
1

A team of 15 engineers is adopting Terraform for production AWS deployments. What is the most critical security rule regarding `terraform.tfstate`?

Concept Check 2 of 2
2

In Terraform, what does the Directed Acyclic Graph (DAG) determine?

8Recap & Architecture Best Practices

  • Declarative IaC: Eliminates snowflake environments and ClickOps human errors through peer-reviewed Git workflows.
  • Terraform State: Must be stored remotely in encrypted S3 buckets with DynamoDB state locking to prevent concurrent apply collisions.
  • Drift Remediation: terraform plan and apply automatically detect unauthorized manual console edits and restore code compliance.
  • AWS CDK & CloudFormation: Choose native CloudFormation for pure AWS stacks, or AWS CDK to leverage TypeScript/Python software engineering practices.

Ready for Chapter 11? Mark this chapter as complete to proceed to Observability & CloudWatch:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us