0
0
Terraformcloud~30 mins

Blue-green infrastructure pattern in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Blue-green infrastructure pattern
📖 Scenario: You are managing a web application deployment on the cloud. To avoid downtime during updates, you want to use the blue-green deployment pattern. This means you have two identical environments: blue and green. Only one environment serves live traffic at a time. When you update, you deploy to the inactive environment, then switch traffic to it.
🎯 Goal: Create a Terraform configuration that defines two identical infrastructure environments named blue and green. Then add a variable to select which environment is active. Finally, configure a load balancer resource that routes traffic to the active environment only.
📋 What You'll Learn
Define two identical infrastructure resources named blue and green.
Add a variable called active_environment with allowed values "blue" and "green".
Use the active_environment variable to select which environment the load balancer routes traffic to.
The Terraform configuration must be valid and deployable.
💡 Why This Matters
🌍 Real World
Blue-green deployment is a common pattern to update applications without downtime by switching traffic between two identical environments.
💼 Career
Cloud engineers and DevOps professionals use this pattern to ensure smooth, reliable application updates in production.
Progress0 / 4 steps
1
Define blue and green infrastructure resources
Create two identical aws_instance resources named blue and green. Use the AMI ID "ami-12345678" and instance type "t2.micro" for both.
Terraform
Need a hint?

Define two aws_instance blocks with names blue and green. Use the same AMI and instance type for both.

2
Add active environment variable
Add a Terraform variable called active_environment with type string and allowed values ["blue", "green"]. Set the default value to "blue".
Terraform
Need a hint?

Use a variable block with type = string, default = "blue", and a validation block to restrict values.

3
Select active instance using the variable
Create a local value called active_instance_id that uses a conditional expression to select aws_instance.blue.id if var.active_environment is "blue", otherwise aws_instance.green.id.
Terraform
Need a hint?

Use a locals block with a conditional expression to pick the active instance ID.

4
Configure load balancer to route to active environment
Create an aws_lb_target_group_attachment resource named active_attachment that attaches the load balancer target group aws_lb_target_group.main.id to the instance ID from local.active_instance_id.
Terraform
Need a hint?

Use aws_lb_target_group_attachment with target_group_arn, target_id, and port set to 80.