Overview and What You Will Learn
Terraform is a tool that creates and manages infrastructure from configuration files written in HCL. You describe the end state you want, Terraform compares it with what exists, and it calls the cloud provider's APIs to close the gap. In this lab, you will install Terraform, authenticate to AWS, write a multi-file configuration with a provider, variables, resources and outputs, and run init, plan, apply and destroy.
- Installing and pinning a Terraform version
- Authenticating to AWS without putting credentials in code
- Structuring a configuration across
versions.tf,provider.tf,variables.tf,main.tfandoutputs.tf - Reading plan output and its change symbols
- Making a change and watching Terraform apply only the difference
- Destroying everything to avoid charges
Why This Matters in Production
At a company like Razorpay, an engineer who needs infrastructure opens a pull request containing Terraform. A reviewer reads the terraform plan output posted on the PR, approves it, and the pipeline applies it. Every change then has an author, a reviewer and a commit, and dev, staging and prod are built from the same code with different variable values. Without this workflow, environments drift apart and nobody can say who changed what.
Core Principles
Terraform follows a fixed loop: write, init, plan, apply. plan is a read-only preview, and apply makes it real and records the result in state.
download providers] I --> P[terraform plan
safe preview] P --> A[terraform apply
create resources] A --> S[(State file
records reality)] classDef step fill:#326CE5,color:#FFFFFF classDef plan fill:#F97316,color:#FFFFFF classDef store fill:#475569,color:#FFFFFF class W,I,A step class P plan class S store
Terraform itself does not know how to talk to AWS. A provider plugin does that, and Terraform builds a dependency graph from references between resources, so you never state the creation order.
builds dependency graph] T --> PR[AWS provider plugin] PR --> API[(AWS APIs over HTTPS)] API --> RES([EC2, S3, security groups]) classDef cfg fill:#DBEAFE,color:#1E293B classDef core fill:#326CE5,color:#FFFFFF classDef cloud fill:#10B981,color:#FFFFFF class C cfg class T,PR core class API,RES cloud
Detailed Step-by-Step Practical Lab
This lab needs an AWS account, permissions to create EC2 and S3 resources, a default VPC in the region, and a terminal on macOS, Linux or WSL.
Step 1 - Install and Pin Terraform
Use tfenv so each project can pin its own version, the same way nvm works for Node.js:
brew install tfenv # Linuxgit clone https://github.com/tfutils/tfenv.git ~/.tfenvecho 'export PATH="$HOME/.tfenv/bin:$PATH"' >> ~/.bashrcsource ~/.bashrc tfenv install 1.9.8tfenv use 1.9.8terraform versionCreate the project directory and pin the version for your team:
mkdir terraform-first-lab && cd terraform-first-labecho "1.9.8" > .terraform-versionStep 2 - Authenticate to AWS
Never put credentials in .tf files, because they end up in Git history. Prefer short-lived credentials from IAM Identity Center or an assumed role, and use a named profile:
aws configure sso --profile mumbai-devexport AWS_PROFILE=mumbai-devexport AWS_REGION=ap-south-1 aws sts get-caller-identityThe last command must print your account and role before you run Terraform. If you must use access keys for a throwaway lab, export them as environment variables and delete them afterwards.
Step 3 - Add a .gitignore Before Anything Else
State files contain resource attributes in plaintext, so keep them out of Git from the first commit:
cat > .gitignore << 'EOF'# State files contain sensitive values*.tfstate*.tfstate.* # Provider binaries, regenerated by terraform init.terraform/ # Variable files that may contain secrets*.auto.tfvars crash.logcrash.*.logEOFStep 4 - Declare the Terraform and Provider Requirements
# versions.tfterraform { required_version = ">= 1.6.0" required_providers { aws = { source = "hashicorp/aws" # registry.terraform.io/hashicorp/aws version = "~> 5.0" # any 5.x release, never 6.0 or later } }}# provider.tfprovider "aws" { region = var.aws_region # applied to every resource this provider creates default_tags { tags = { ManagedBy = "terraform" Environment = var.environment } }}Step 5 - Declare Input Variables
# variables.tfvariable "aws_region" { description = "AWS region to deploy into" type = string default = "ap-south-1"} variable "environment" { description = "Deployment environment, used in names and tags" type = string default = "dev" validation { condition = contains(["dev", "staging", "prod"], var.environment) error_message = "Environment must be dev, staging, or prod." }} variable "project" { description = "Project name, used as a prefix in resource names" type = string default = "payments-api"} variable "instance_type" { description = "EC2 instance type for the web server" type = string default = "t3.micro"}Step 6 - Write the Resources
# main.tflocals { name_prefix = "${var.project}-${var.environment}"} # Data sources READ existing information and create nothingdata "aws_ami" "amazon_linux" { most_recent = true owners = ["amazon"] filter { name = "name" values = ["al2023-ami-2023.*-x86_64"] }} data "aws_caller_identity" "current" {} resource "aws_s3_bucket" "app_assets" { # bucket names are global, so the account ID suffix avoids collisions bucket = "${local.name_prefix}-assets-${data.aws_caller_identity.current.account_id}"} resource "aws_s3_bucket_public_access_block" "app_assets" { bucket = aws_s3_bucket.app_assets.id # this reference creates the dependency block_public_acls = true block_public_policy = true ignore_public_acls = true restrict_public_buckets = true} resource "aws_s3_bucket_versioning" "app_assets" { bucket = aws_s3_bucket.app_assets.id versioning_configuration { status = "Enabled" }} resource "aws_s3_bucket_server_side_encryption_configuration" "app_assets" { bucket = aws_s3_bucket.app_assets.id rule { apply_server_side_encryption_by_default { sse_algorithm = "AES256" } }} resource "aws_security_group" "web" { name = "${local.name_prefix}-web-sg" description = "Web server security group" ingress { description = "HTTPS from internet" from_port = 443 to_port = 443 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } ingress { description = "HTTP from internet" from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } egress { description = "All outbound traffic" from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] }} resource "aws_instance" "web" { ami = data.aws_ami.amazon_linux.id instance_type = var.instance_type vpc_security_group_ids = [aws_security_group.web.id] user_data = <<-EOF #!/bin/bash dnf install -y nginx systemctl enable --now nginx echo "<h1>${var.project} - ${var.environment}</h1>" > /usr/share/nginx/html/index.html EOF # require IMDSv2 to block credential theft through SSRF metadata_options { http_endpoint = "enabled" http_tokens = "required" http_put_response_hop_limit = 1 } tags = { Name = "${local.name_prefix}-web-server" }}# outputs.tfoutput "s3_bucket_name" { description = "Name of the assets bucket" value = aws_s3_bucket.app_assets.id} output "instance_id" { description = "EC2 instance ID" value = aws_instance.web.id} output "instance_public_ip" { description = "Public IP of the web server" value = aws_instance.web.public_ip}Step 7 - Initialise, Validate and Format
terraform initterraform validateterraform fmtinit downloads the AWS provider and writes .terraform.lock.hcl, which records the exact provider version and checksums. Commit that file, but never the .terraform/ directory.
Remember
terraform validatechecks syntax without calling any API, andterraform fmt -checkexits non-zero when files need formatting, which makes it useful in CI.
Step 8 - Plan, Then Read Every Line
plan changes nothing. Read it as a code review of your infrastructure:
terraform plan -out=tfplanThe end of the output should read Plan: 6 to add, 0 to change, 0 to destroy. The symbols mean:
+ resource will be created~ resource will be updated in place-/+ resource will be destroyed and recreated (check why)- resource will be destroyed<= data source will be readSaving the plan with -out guarantees that what you reviewed is exactly what gets applied.
Step 9 - Apply
terraform apply tfplanterraform outputcurl http://$(terraform output -raw instance_public_ip)/Terraform creates the S3 bucket and the security group in parallel because neither depends on the other, then creates the instance once the security group exists. Allow a minute for nginx to start before the curl succeeds.
Step 10 - Inspect What Terraform Tracks
terraform state listterraform state show aws_instance.webThe list includes the two data sources and the six resources. State is how Terraform knows what it already created.
Step 11 - Change One Value and Apply Only the Difference
Edit the instance_type default in variables.tf from t3.micro to t3.small, then plan:
terraform plan# ~ aws_instance.web will be updated in-place# ~ instance_type = "t3.micro" -> "t3.small"# Plan: 0 to add, 1 to change, 0 to destroy. terraform applyTerraform changed only the instance type. The resource is modified in place, not recreated, although AWS stops and starts the instance during the change, so expect a short interruption.
Step 12 - Destroy Everything
terraform plan -destroyterraform destroySecurityAlways run
terraform destroyafter a lab. A forgotten instance keeps billing, so also set an AWS budget alert as a safety net.
Production Best Practices & Common Pitfalls
Common MistakeRunning
terraform applywithout reading the plan, especially-/+lines. A replacement destroys and recreates the resource, which means downtime or data loss for stateful resources like databases.
TipUse
default_tagsin the provider block so shared tags apply to every resource automatically, instead of repeating atagsblock everywhere.
- Pin provider versions with
~>.~> 5.0allows any 5.x release but blocks 6.0, so an upgrade never lands by surprise. - Commit the lock file.
.terraform.lock.hclkeeps every engineer and pipeline on the same provider binary. - Move state off your laptop before a second engineer joins. Use a remote backend with locking. Recent Terraform versions support native S3 locking, so check the backend documentation for the current recommended setup.
- Use a naming prefix from a local value.
"${var.project}-${var.environment}"keeps resource names consistent across environments. - Use a data source for AMI IDs. It always returns a current image, and the same code works in every region.
- Reserve
-auto-approvefor pipelines. Manual runs should always show the plan and ask for confirmation.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
terraform init |
Download providers and set up the backend |
terraform init -upgrade |
Upgrade providers within the allowed constraint |
terraform validate |
Check syntax and consistency with no API calls |
terraform fmt -check |
Check formatting, useful in CI |
terraform plan -out=tfplan |
Preview changes and save the plan |
terraform apply tfplan |
Apply exactly the saved plan |
terraform destroy |
Destroy all managed resources |
terraform output -raw NAME |
Print one output without quotes |
| Error | Cause | Fix |
|---|---|---|
No configuration files |
Wrong directory | cd to the folder with the .tf files |
Inconsistent dependency lock file |
Provider changed since init | Run terraform init |
No valid credential sources found |
AWS credentials missing | Set AWS_PROFILE and log in |
BucketAlreadyExists |
Bucket names are global | Keep the account ID suffix |
Error: Cycle |
Resources reference each other | Remove the circular reference |
Unexpected -/+ in plan |
A change forces replacement | Read the forces replacement note |