DEV Community

Cover image for 3.Replace Existing EC2 Instance via Terraform
Thu Kha Kyawe
Thu Kha Kyawe

Posted on

3.Replace Existing EC2 Instance via Terraform

Lab Information

To test resilience and recreation behavior in Terraform, the DevOps team needs to demonstrate the use of the -replace option to forcefully recreate an EC2 instance without changing its configuration. Please complete the following tasks:

Use the Terraform CLI -replace option to destroy and recreate the EC2 instance nautilus-ec2, even though the configuration remains unchanged.

Ensure that the instance is recreated successfully.
Enter fullscreen mode Exit fullscreen mode

Lab Solutions

Step 1: Verify the EC2 resource exists in state

Run:

terraform state list
terraform output
Enter fullscreen mode Exit fullscreen mode

⚠️ Important:
The resource address must be exactly:

aws_instance.nautilus-ec2

🔄 Step 2: Force recreation using -replace (KEY STEP)

Run this command:

terraform apply -replace="aws_instance.web_server"

type - yes

🔍 What Terraform Will Show

Terraform will clearly indicate destroy → create, even though nothing changed:

This confirms:

Old instance will be destroyed

New instance will be created

⏳ Step 3: Wait for Completion

Terraform will:

Destroy the existing EC2

Recreate the EC2 with the same configuration

Update the state file

You should see:

Apply complete! Resources: 1 added, 0 changed, 1 destroyed.


Resources & Next Steps
📦 Full Code Repository: KodeKloud Learning Labs
📖 More Deep Dives: Whispering Cloud Insights - Read other technical articles
💬 Join Discussion: DEV Community - Share your thoughts and questions
💼 Let's Connect: LinkedIn - I'd love to connect with you

Credits
• All labs are from: KodeKloud
• I sincerely appreciate your provision of these valuable resources.

Top comments (0)