⬡ Hub
Skip to content

Terraform Real-Time Examples and Solutions

Scenario 1: Managing Multiple Environments (Dev/Prod)

Problem: You need to deploy the same infrastructure to Development and Production, but with different sizes (e.g., t2.micro for Dev, m5.large for Prod).

Solution: Use Terraform Workspaces or Directory Structure with .tfvars. * Approach: Create dev.tfvars and prod.tfvars. * dev.tfvars: instance_type = "t2.micro" * prod.tfvars: instance_type = "m5.large" * Execution: * Dev: terraform apply -var-file="dev.tfvars" * Prod: terraform apply -var-file="prod.tfvars"

Scenario 2: Refactoring Infrastructure (Moving Resources)

Problem: You want to rename a resource in your Terraform code (e.g., aws_instance.web to aws_instance.app_server) or move it into a module, but you don't want Terraform to destroy and recreate the real infrastructure.

Solution: Use the moved block (Terraform 1.1+). * Code: hcl moved { from = aws_instance.web to = aws_instance.app_server } * Result: When you run terraform plan, Terraform recognizes this as a rename operation rather than a destroy/create, preserving the existing resource.

Scenario 3: Importing Existing Infrastructure

Problem: Someone manually created an S3 bucket in the AWS Console, and now you need to manage it with Terraform.

Solution: Use terraform import. 1. Write Code: Create the resource "aws_s3_bucket" "my_bucket" {} block in your .tf file. 2. Import: Run terraform import aws_s3_bucket.my_bucket <bucket-name>. 3. Plan: Run terraform plan. Terraform will show the difference between your code and the real state. Update your code to match the real state until the plan shows "No changes".