0
0
Terraformcloud~30 mins

Zero-downtime deployment pattern in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Zero-downtime deployment pattern
📖 Scenario: You are managing a web application hosted on a cloud provider. To avoid downtime during updates, you want to deploy a new version of your application alongside the old one, then switch traffic to the new version only after it is ready.
🎯 Goal: Build a Terraform configuration that creates two identical instances of a web server behind a load balancer. The load balancer should route traffic only to the active instance. You will configure the infrastructure to allow switching traffic from the old instance to the new instance without downtime.
📋 What You'll Learn
Create two compute instances with the same configuration but different names
Create a load balancer with a target group
Attach only one instance to the load balancer target group at a time
Add a variable to select which instance is active
Use the variable to control which instance receives traffic
💡 Why This Matters
🌍 Real World
Zero-downtime deployment is critical for web applications that must remain available during updates. This pattern is used in production environments to avoid service interruptions.
💼 Career
Cloud engineers and DevOps professionals use zero-downtime deployment patterns to ensure high availability and reliability of applications during updates.
Progress0 / 4 steps
1
Create two compute instances
Create two AWS EC2 instances named app_instance_old and app_instance_new with the AMI ID ami-0c55b159cbfafe1f0 and instance type t2.micro.
Terraform
Need a hint?

Use two aws_instance resources with the specified AMI and instance type. Name them exactly app_instance_old and app_instance_new.

2
Create a load balancer and target group
Add an AWS Application Load Balancer resource named app_lb and a target group named app_tg with port 80 and protocol HTTP.
Terraform
Need a hint?

Use aws_lb for the load balancer and aws_lb_target_group for the target group. Use port 80 and HTTP protocol.

Note: Replace subnet and VPC IDs with your actual values.

3
Add a variable to select the active instance
Create a Terraform variable named active_instance of type string with default value "old" to select which instance receives traffic.
Terraform
Need a hint?

Define a variable block named active_instance with type string and default value "old".

4
Attach only the active instance to the target group
Create an aws_lb_target_group_attachment resource named active_attachment that attaches the instance selected by var.active_instance to the target group aws_lb_target_group.app_tg. Use a conditional expression to select aws_instance.app_instance_old.id if var.active_instance is "old", else aws_instance.app_instance_new.id.
Terraform
Need a hint?

Use a conditional expression for target_id to select the instance ID based on var.active_instance.