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

AWS Cloud

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.

In this chapter

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

1. Everyday example first

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.

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

Suppose you need one storage bucket in a test account and a similar one for production. A Terraform configuration describes the desired resources. The AWS provider translates resource operations into AWS API calls. A state file records which actual resource corresponds to each address in that configuration. After a lab bucket is made, state can remember that aws_s3_bucket.logs refers to it. Read terraform plan to see the changes calculated from the current environment and desired code before you allow apply to make those changes.

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)

Imagine two classmates share responsibility for the same test resources. The state tells Terraform what it already manages. A lock helps make sure only one run is changing that state at a time. The remote bucket also makes it possible to keep previous versions. A later run should use the same backend configuration for the same environment, and a different state key for a separate environment. Compare the key in your lab notes with the one Terraform is using before you plan the wrong stack.

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

Store state in an S3 bucket with versioning and encrypt it. Set use_lockfile = true with a supported Terraform version so two writers cannot update the same state concurrently. DynamoDB-based locking is deprecated.

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"
    use_lockfile   = true
    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

Before applying the lab, read the plan symbols. A resource marked for addition should have the one lab bucket name you picked. If a plan shows a deletion or a different account, stop and inspect the configuration and credentials. After the apply, run a fresh plan against the same untouched lab. Expect no changes once the saved configuration and real resource agree. Check that the destroy plan names the lab bucket only, and keep the separate state backend intact.

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

  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 lockCheck whether another run holds the lock and coordinate with its owner before clearing a stale lock.
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 backendCheck permissions for the state bucket and object, and for its .tflock object when locking is enabled.

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 an S3 backend with its state object and lockfile 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
Remote state and locking. Keep state in a separately managed, versioned S3 bucket. Restrict access to that state. Terraform state can contain secrets. For a supported Terraform version, set use_lockfile = true in the S3 backend. DynamoDB-based locking is deprecated. The backend needs permission for its state object and the .tflock object. Coordinate with the owner before clearing a stale lock.
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
Why use remote state?. Keep state in a separately managed, versioned S3 bucket. Restrict access to that state. Terraform state can contain secrets. For a supported Terraform version, set use_lockfile = true in the S3 backend. DynamoDB-based locking is deprecated. The backend needs permission for its state object and the .tflock object. Coordinate with the owner before clearing a stale lock.
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.

Practise this chapter

Interview questions and answers

Why use both versioning and locking for shared Terraform state?

Versioning can give you an older state copy after a problematic change. Locking coordinates writers so two operations do not update the same state together. They solve different problems. Check the backend key and permissions before taking action on either the state file or its lock.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. What does Terraform state map?

Answer and explanation

C. Addresses in configuration to actual managed resources

Terraform uses state to know what existing infrastructure corresponds to its descriptions.

2. Which Terraform operation shows expected resource changes before making them?

Answer and explanation

B. plan

The plan proposes actions for inspection. An apply carries out changes and destroy removes managed resources as planned.

3. Which extra action is needed on the S3 state lock file to let Terraform release it?

Answer and explanation

A. Permission to delete the lock object

Terraform must remove the lock object when finished. State-object and lock-object permissions can be scoped separately.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

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

Download providers.

Run terraform init in the project folder.

  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

Preview changes.

Run terraform plan.

  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

Catch syntax errors.

Validate the Terraform configuration.

  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

Keep style consistent.

Format Terraform files in place.

  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

Verify what Terraform made.

List S3 buckets in eu-west-2.

  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)

Confirm which account Terraform uses.

Show the caller identity for the current AWS credentials.

  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

terraform.tfstate is the usual local file.

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

  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

Multi-AZ needs 2+.

Minimum Availability Zones often recommended for HA?

  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

Apply without prompt in CI.

Apply Terraform changes with auto-approve.

  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

Tear down lab.

Destroy all managed resources with auto-approve.

  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

Read stack outputs.

Show Terraform outputs.

  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

See tracked resources.

List resources in Terraform state.

  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

Tag every resource.

JSON default_tags Project learn Env lab.

  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

Automation checks exit codes.

Typical success exit code for terraform plan with no error?

  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

CI needs read on state.

Allow s3:ListBucket on arn:aws:s3:::londonlegal-tfstate.

  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

Teams share state in S3.

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

  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.