Ravindra BagaleCourses & study guides मराठी Track your progress

Terraform on AWS: Infrastructure as Code for Beginners

Clicking 40 screens to build a VPC is like cooking without a written recipe — you cannot repeat it for staging. Terraform is the written recipe for AWS: plan shows the shopping list, apply cooks it, state remembers what exists.

What you'll learn in this chapter

  • Why IaC beats click-ops
  • Providers, resources, plan, apply, destroy
  • Remote state on S3 + DynamoDB lock
  • Modules, workspaces, and guardrails
  • Lab, errors, FAQ, interview

1. Everyday example first

Why do we need this?

A Pune SaaS team rebuilt staging by hand every month and drifted from prod. One missed security group rule caused a night outage. Terraform made staging = prod shape, reviewed in Git.

What is it?

Terraform (HashiCorp) is infrastructure as code. You declare AWS resources in HCL. terraform plan shows the diff; apply makes it real; state tracks IDs so later plans know what already exists.

Dev loopWrite .tf filesterraform planReview + PRterraform apply
Never apply unreviewed changes on prod.

2. Core words

WordMeaningPicture
ProviderPlugin talking to AWSTranslator
ResourceOne AWS object you manageOne dish on the menu
StateJSON map of real IDsKitchen inventory book
PlanDry-run diffShopping list before market
ModuleReusable folder of .tfShared recipe card
BackendWhere state is storedShared inventory in S3

3. Remote state (do this early)

Why do we need this?

Local state on a laptop is how two people destroy each other's work.

What is it?

Store state in an S3 bucket with versioning and encrypt it. Use a DynamoDB table for state locking so two applies cannot run together.

terraform {
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 5.0" }
  }
  backend "s3" {
    bucket         = "myorg-tfstate-ap-south-1"
    key            = "app/staging/terraform.tfstate"
    region         = "ap-south-1"
    dynamodb_table = "myorg-tf-locks"
    encrypt        = true
  }
}

provider "aws" { region = "ap-south-1" }

resource "aws_s3_bucket" "logs" {
  bucket = "myorg-staging-logs-example"
}

4. Industries

  • Banks: separate AWS accounts + Terraform modules for VPC baselines.
  • Startups: same module for dev/stage/prod with tfvars.
  • Agencies: client VPCs from a private module registry.
  • Data teams: Glue/S3 lakes described in code for audit.
  • Platform teams: Terraform + CI (plan on PR, apply on merge).

5. Terraform vs CDK vs Console

ToolStrengthWatch-out
ConsoleLearning, emergenciesNot repeatable
CloudFormation/CDKAWS-native deep integrationAWS-only comfort zone
TerraformMulti-cloud, huge module ecosystemState file is crown jewels

Ravindra Bagale's Tip

Treat state like a password file: encrypt, lock, restrict IAM, never commit it.

6. Mini lab: bucket with plan/apply

Do this in ap-south-1 (Mumbai) unless your org forbids it. Set a budget alert first.

How to do it (step by step)

  1. Install Terraform; configure AWS CLI profile for a sandbox account.
  2. Write provider + aws_s3_bucket in main.tf.
  3. terraform init && terraform plan — read every line.
  4. terraform apply — auto-approve only in sandbox.
  5. Change a tag; plan again; see update in-place.

Cleanup (stop billing)

  1. terraform destroy in the sandbox.
  2. Confirm bucket gone in console.

7. Common errors and fixes

Each row is a real mistake students and juniors hit. Read the fix before you panic.

Error / symptomFix
Error acquiring state lockAnother apply running or crashed — check DynamoDB lock item.
Resource already existsImport or rename; do not double-create.
Provider credentialsWrong profile/region/SSO expired.
State driftSomeone clicked console — refresh / untaint carefully.
Force-unlocked casuallyOnly after you proved no other apply is running.
Committed .tfstate to GitRotate secrets; move to S3 backend; purge Git history if needed.
Destructive plan on prodRequire plan artifact review; restrict who can apply.
Module version floatingPin module versions.
count/for_each index shiftUse maps with stable keys, not bare lists, for renames.
AccessDenied on backendIAM needs s3 + dynamodb lock permissions.

8. Troubleshooting checklist

  1. terraform version and AWS_PROFILE echo.
  2. terraform init -reconfigure if backend changed.
  3. Read plan file before apply.
  4. terraform state list to see what Terraform thinks exists.
  5. For one bad object, prefer import over manual delete when unsure.

9. FAQ

Q. Is Terraform free?

Open source Terraform CLI is free; Terraform Cloud is optional paid collaboration.

Q. Can Terraform manage existing clicks?

Yes — terraform import (and newer generate flows).

Q. Terraform or CDK?

Multi-cloud / existing TF modules → Terraform. Heavy AWS+TypeScript teams → CDK.

Q. How to secret-manage?

Use SSM/Secrets Manager data sources; never hardcode.

Q. Workspaces?

Lightweight separation; many teams prefer separate state keys/accounts.

10. Interview Q&A

Q. What does terraform plan do?

Shows the create/update/destroy diff without changing AWS.

Q. Why remote state?

Share IDs safely across people and CI with locking.

Q. State file risk?

May contain sensitive values — protect like secrets.

Q. Module benefit?

Reuse reviewed building blocks (VPC, ECS service).

Q. How do you stop prod accidents?

PR plan, approvals, least-privilege apply role, separate accounts.

Q. Drift detection?

Regular plans in CI; optional refresh policies.

11. Tips in English, Marathi and Hindi

Ravindra Bagale's Tip (EN)

Plan is a document. If you cannot explain a destroy line, do not apply.

Ravindra Bagale's Tip (MR)

Plan = document. Destroy ओळ समजत नसेल तर apply नको.

Tip (HI)

Plan एक दस्तावेज़ है — destroy लाइन समझ न आए तो apply मत करो।

Try at home

  1. Write a main.tf with one S3 bucket and one tag.
  2. Draw S3 backend + DynamoDB lock on paper.
  3. List console clicks you did last week that should be code.

In short

  1. Terraform declares AWS in HCL; plan then apply.
  2. Remote state + lock are mandatory for teams.
  3. Pin versions; never commit state.
  4. Review destroys like production incidents.

Revision, interview and comparison cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Revision card: What is Terraform on AWS?. Clicking the console for every VPC and RDS copy is slow and easy to forget. Terraform is Infrastructure as Code: .tf files describe AWS resources; plan shows change; apply makes it real. Install Terraform → aws credentials → write provider + resources → terraform init/plan/apply. plan shows + aws_instance; apply creates it; state file remembers the id.
Revision card: What is Terraform on AWS? · Download PNG · Open card page
Revision card: Remote state (S3 + lock). Two people apply at once with local state can corrupt or double-create resources. Store state in S3 and lock with DynamoDB (or S3 native lock where enabled) so only one apply runs. Configure backend s3 with bucket, key, region, and dynamodb_table; run init -migrate-state. Second apply waits or errors on lock instead of racing the first.
Revision card: Remote state (S3 + lock) · Download PNG · Open card page
Revision card: Always read plan. Blind apply can destroy a database when a name or force_new flag changes. terraform plan is a dry run: + add, ~ change, - destroy. Review destroy lines before apply. Run plan in CI; require a human check when plan contains destroy on prod modules. A renamed RDS identifier shows -/+: stop and use lifecycle or rename strategy instead of apply.
Revision card: Always read plan · Download PNG · Open card page
Revision card: Modules for reuse. Copy-pasting the same VPC block into five apps drifts and breaks fixes. A module is a folder of .tf with variables and outputs. Root modules call it with different inputs. Write modules/vpc; call it from app-a and app-b with different cidr variables. One security fix inside the module reaches every app on the next plan/apply.
Revision card: Modules for reuse · Download PNG · Open card page
Revision card: Tags and cost allocation. FinOps cannot explain a bill when EC2 and RDS have no owner tags. default_tags on the AWS provider and resource tags mark env, owner, and project for Cost Explorer. Set provider default_tags { Environment = "lab", Owner = "training" }; override per resource when needed. Cost Explorer group-by tag Environment shows lab vs prod spend.
Revision card: Tags and cost allocation · Download PNG · Open card page
Comparison: Terraform vs CloudFormation. Terraform: Multi-cloud HCL, strong modules/state ecosystem. CloudFormation: AWS-native stacks, change sets, drift detection.
Comparison: Terraform vs CloudFormation · Download PNG · Open card page
Comparison: Local state vs Remote state (S3). Local state: terraform.tfstate on one laptop — races and loss risk. Remote state (S3): Shared state in S3 with locking.
Comparison: Local state vs Remote state (S3) · Download PNG · Open card page
Interview card: Why remote state?. Remote state + locking lets teams share one source of truth and avoid apply races. Local state on laptops diverges and causes duplicate or orphan resources. S3 backend with DynamoDB lock is the common AWS pattern.
Interview card: Why remote state? · Download PNG · Open card page
Interview card: How do you avoid accidental destroy?. Read plan; use prevent_destroy lifecycle on databases; separate prod state; require plan review. Never apply a plan you do not understand in prod. Renaming a RDS identifier shows destroy/create — stop and redesign.
Interview card: How do you avoid accidental destroy? · Download PNG · Open card page
Interview card: Where do secrets go in Terraform?. Not in git. Use Secrets Manager/SSM parameters; mark sensitive; restrict state access. State can contain secret values — encrypt and limit who can read the bucket. DB password from aws_secretsmanager_secret_version, not a checked-in tfvars.
Interview card: Where do secrets go in Terraform? · Download PNG · Open card page
Interview card: How do you adopt existing resources?. terraform import (or import blocks) links real AWS ids into state without recreate. Write matching config first; never import blindly into empty resource blocks. Import an existing VPC before managing its routes in code.
Interview card: How do you adopt existing resources? · Download PNG · Open card page

More cards: Ravi Sir's Cards.

Practice Tasks

About this scenario

London Legal LLP is a law business in London. Oliver Hughes looks after its IT and cloud work. They count money in GBP and run their AWS resources in the eu-west-2 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 16

Easy terraform init

Why: Download providers.

What to do: Run terraform init in the project folder.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy terraform plan

Why: Preview changes.

What to do: Run terraform plan.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy terraform validate

Why: Catch syntax errors.

What to do: Validate the Terraform configuration.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy terraform fmt

Why: Keep style consistent.

What to do: Format Terraform files in place.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy List buckets after apply

Why: Verify what Terraform made.

What to do: List S3 buckets in eu-west-2.

How:
  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Who am I (sts)

Why: Confirm which account Terraform uses.

What to do: Show the caller identity for the current AWS credentials.

How:
  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Local state file count after init

Why: terraform.tfstate is the usual local file.

What to do: How many primary local state files named terraform.tfstate does a simple project use?

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Example AZ count for HA

Why: Multi-AZ needs 2+.

What to do: Minimum Availability Zones often recommended for HA?

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium terraform apply auto-approve

Why: Apply without prompt in CI.

What to do: Apply Terraform changes with auto-approve.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium terraform destroy auto-approve

Why: Tear down lab.

What to do: Destroy all managed resources with auto-approve.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium terraform output

Why: Read stack outputs.

What to do: Show Terraform outputs.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium terraform state list

Why: See tracked resources.

What to do: List resources in Terraform state.

How:
  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Default tags JSON

Why: Tag every resource.

What to do: JSON default_tags Project learn Env lab.

How:
  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Medium terraform plan success exit code

Why: Automation checks exit codes.

What to do: Typical success exit code for terraform plan with no error?

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium CI role: list state bucket

Why: CI needs read on state.

What to do: Allow s3:ListBucket on arn:aws:s3:::londonlegal-tfstate.

How:
  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Hard Remote state backend JSON

Why: Teams share state in S3.

What to do: JSON backend s3 with bucket londonlegal-tfstate key app/terraform.tfstate region eu-west-2.

How:
  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.