Bird
Raised Fist0
Terraformcloud~10 mins

Blue-green infrastructure pattern in Terraform - Commands & Configuration

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Switching live applications between two identical environments helps avoid downtime and reduces risk during updates. The blue-green pattern keeps one environment live while preparing the other for changes, then switches traffic smoothly.
When you want to update your app without making users wait or see errors.
When you need a quick way to roll back to the previous version if something breaks.
When you want to test a new version of your app in a real environment before making it live.
When you want to reduce downtime during deployments to nearly zero.
When you want to separate environments for staging and production but switch traffic easily.
Config File - main.tf
main.tf
provider "aws" {
  region = "us-east-1"
}

resource "aws_lb" "app_lb" {
  name               = "app-load-balancer"
  internal           = false
  load_balancer_type = "application"
  security_groups    = ["sg-0123456789abcdef0"]
  subnets            = ["subnet-0123456789abcdef0", "subnet-0fedcba9876543210"]
}

resource "aws_lb_target_group" "blue" {
  name     = "blue-target-group"
  port     = 80
  protocol = "HTTP"
  vpc_id   = "vpc-0123456789abcdef0"
}

resource "aws_lb_target_group" "green" {
  name     = "green-target-group"
  port     = 80
  protocol = "HTTP"
  vpc_id   = "vpc-0123456789abcdef0"
}

resource "aws_lb_listener" "http_listener" {
  load_balancer_arn = aws_lb.app_lb.arn
  port              = 80
  protocol          = "HTTP"

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.blue.arn
  }
}

resource "aws_autoscaling_group" "blue_asg" {
  name                      = "blue-asg"
  max_size                  = 2
  min_size                  = 1
  desired_capacity          = 1
  vpc_zone_identifier       = ["subnet-0123456789abcdef0", "subnet-0fedcba9876543210"]
  launch_configuration      = aws_launch_configuration.blue_lc.name
  target_group_arns         = [aws_lb_target_group.blue.arn]
  health_check_type         = "ELB"
  health_check_grace_period = 300
}

resource "aws_autoscaling_group" "green_asg" {
  name                      = "green-asg"
  max_size                  = 2
  min_size                  = 1
  desired_capacity          = 0
  vpc_zone_identifier       = ["subnet-0123456789abcdef0", "subnet-0fedcba9876543210"]
  launch_configuration      = aws_launch_configuration.green_lc.name
  target_group_arns         = [aws_lb_target_group.green.arn]
  health_check_type         = "ELB"
  health_check_grace_period = 300
}

resource "aws_launch_configuration" "blue_lc" {
  name_prefix   = "blue-lc-"
  image_id      = "ami-0c55b159cbfafe1f0"
  instance_type = "t3.micro"
  security_groups = ["sg-0123456789abcdef0"]
  user_data = <<-EOF
              #!/bin/bash
              echo 'Blue version running' > /var/www/html/index.html
              EOF
}

resource "aws_launch_configuration" "green_lc" {
  name_prefix   = "green-lc-"
  image_id      = "ami-0c55b159cbfafe1f0"
  instance_type = "t3.micro"
  security_groups = ["sg-0123456789abcdef0"]
  user_data = <<-EOF
              #!/bin/bash
              echo 'Green version running' > /var/www/html/index.html
              EOF
}

This Terraform file creates two identical environments named blue and green.

The aws_lb resource creates a load balancer that directs traffic.

The aws_lb_target_group resources define groups of servers for blue and green.

The aws_lb_listener listens on port 80 and initially forwards traffic to the blue target group.

The aws_autoscaling_group resources manage the servers for blue and green environments, with blue active and green inactive at start.

The aws_launch_configuration resources define how to launch servers for each environment, with simple user data to show which version is running.

Commands
This command sets up Terraform in the current folder by downloading necessary plugins and preparing the environment.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/aws... - Installing hashicorp/aws v4.0.0... - Installed hashicorp/aws v4.0.0 (signed by HashiCorp) Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes that are required for your infrastructure.
This command creates the blue and green environments and the load balancer, applying the infrastructure described in the config file.
Terminal
terraform apply -auto-approve
Expected OutputExpected
aws_lb.app_lb: Creating... aws_lb_target_group.blue: Creating... aws_lb_target_group.green: Creating... aws_launch_configuration.blue_lc: Creating... aws_launch_configuration.green_lc: Creating... aws_autoscaling_group.blue_asg: Creating... aws_autoscaling_group.green_asg: Creating... aws_lb_listener.http_listener: Creating... ... Apply complete! Resources: 9 added, 0 changed, 0 destroyed.
-auto-approve - Skip manual approval to apply changes immediately
This command checks the current listener configuration to verify which target group (blue or green) is receiving traffic.
Terminal
aws elbv2 describe-listeners --load-balancer-arn $(terraform output -raw app_lb_arn)
Expected OutputExpected
{ "Listeners": [ { "ListenerArn": "arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/app-load-balancer/50dc6c495c0c9188/6d0ecf831eec9f09", "Port": 80, "Protocol": "HTTP", "DefaultActions": [ { "Type": "forward", "TargetGroupArn": "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/blue-target-group/6d0ecf831eec9f09" } ] } ] }
This command switches the live traffic from the blue environment to the green environment by changing the load balancer's target group.
Terminal
aws elbv2 modify-listener --listener-arn arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/app-load-balancer/50dc6c495c0c9188/6d0ecf831eec9f09 --default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/green-target-group/6d0ecf831eec9f09
Expected OutputExpected
{}
This command scales up the green environment to start serving traffic after the switch.
Terminal
terraform apply -auto-approve -target=aws_autoscaling_group.green_asg -var='desired_capacity=1'
Expected OutputExpected
aws_autoscaling_group.green_asg: Modifying... [id=green-asg] aws_autoscaling_group.green_asg: Modifications complete after 10s [id=green-asg] Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
-target - Apply changes only to the green autoscaling group
Key Concept

If you remember nothing else from this pattern, remember: keep two identical environments and switch traffic between them to update without downtime.

Common Mistakes
Changing the load balancer target group without scaling up the new environment.
Traffic switches to an environment with no active servers, causing downtime.
Always start or scale up the new environment before switching the load balancer.
Applying Terraform changes without initializing the workspace first.
Terraform commands fail because plugins and providers are not set up.
Run 'terraform init' before any other Terraform commands.
Not verifying the load balancer listener after switching target groups.
You might think traffic switched but it still goes to the old environment.
Use AWS CLI or Terraform outputs to confirm the listener points to the correct target group.
Summary
Initialize Terraform to prepare the environment with 'terraform init'.
Apply the infrastructure to create blue and green environments and load balancer with 'terraform apply'.
Check which environment receives traffic by inspecting the load balancer listener.
Switch live traffic by modifying the load balancer listener to point to the other environment.
Scale the new environment to handle traffic after switching.

Practice

(1/5)
1. What is the main purpose of the blue-green infrastructure pattern in Terraform deployments?
easy
A. To reduce infrastructure costs by using a single environment
B. To automate database backups during deployment
C. To increase the number of servers in a single environment
D. To avoid downtime by switching traffic between two identical environments

Solution

  1. Step 1: Understand the blue-green pattern concept

    The blue-green pattern uses two identical environments to ensure zero downtime during updates.
  2. Step 2: Identify the main goal in Terraform deployments

    Terraform manages these environments and switches traffic between them to avoid downtime.
  3. Final Answer:

    To avoid downtime by switching traffic between two identical environments -> Option D
  4. Quick Check:

    Blue-green pattern = avoid downtime [OK]
Hint: Remember: blue-green means two environments for zero downtime [OK]
Common Mistakes:
  • Thinking it reduces costs by using one environment
  • Confusing it with scaling servers in one environment
  • Assuming it automates backups
2. Which Terraform resource is commonly used to switch traffic between blue and green environments in a blue-green deployment?
easy
A. aws_lb_listener_rule
B. aws_instance
C. aws_s3_bucket
D. aws_security_group

Solution

  1. Step 1: Identify Terraform resources related to traffic routing

    Load balancer listener rules control how traffic is routed to target groups.
  2. Step 2: Match resource to blue-green traffic switch

    The aws_lb_listener_rule resource allows switching traffic between blue and green target groups.
  3. Final Answer:

    aws_lb_listener_rule -> Option A
  4. Quick Check:

    Traffic switch uses listener rules [OK]
Hint: Traffic routing uses listener rules, not instances or buckets [OK]
Common Mistakes:
  • Choosing aws_instance which manages servers, not traffic
  • Selecting aws_s3_bucket which is for storage
  • Picking aws_security_group which controls firewall rules
3. Given this Terraform snippet for blue-green deployment traffic switching:
resource "aws_lb_listener_rule" "blue" {
  listener_arn = aws_lb_listener.front_end.arn
  priority     = 10
  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.blue.arn
  }
  condition {
    path_pattern {
      values = ["/blue/*"]
    }
  }
}

resource "aws_lb_listener_rule" "green" {
  listener_arn = aws_lb_listener.front_end.arn
  priority     = 20
  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.green.arn
  }
  condition {
    path_pattern {
      values = ["/green/*"]
    }
  }
}
What happens when a user visits /green/home?
medium
A. Traffic is routed to the green target group
B. Traffic is routed to both blue and green target groups
C. Traffic is blocked by the load balancer
D. Traffic is routed to the blue target group

Solution

  1. Step 1: Analyze path pattern conditions in listener rules

    The green listener rule matches paths starting with /green/* and forwards to the green target group.
  2. Step 2: Match user request path to rules

    The request /green/home matches the green rule condition, so traffic goes to the green target group.
  3. Final Answer:

    Traffic is routed to the green target group -> Option A
  4. Quick Check:

    Path /green/* routes to green group [OK]
Hint: Match URL path to listener rule path pattern [OK]
Common Mistakes:
  • Assuming default routing to blue group
  • Thinking traffic is blocked without default rule
  • Believing traffic splits between groups
4. You wrote this Terraform code to switch traffic in a blue-green setup but the traffic does not switch as expected:
resource "aws_lb_listener_rule" "blue" {
  listener_arn = aws_lb_listener.front_end.arn
  priority     = 10
  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.blue.arn
  }
  condition {
    host_header {
      values = ["blue.example.com"]
    }
  }
}

resource "aws_lb_listener_rule" "green" {
  listener_arn = aws_lb_listener.front_end.arn
  priority     = 10
  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.green.arn
  }
  condition {
    host_header {
      values = ["green.example.com"]
    }
  }
}
What is the likely problem?
medium
A. Target groups are not defined correctly
B. Host header condition is invalid for load balancers
C. Both listener rules have the same priority, causing conflict
D. Listener ARN is missing in one of the rules

Solution

  1. Step 1: Check listener rule priorities

    Both rules have priority 10, which causes a conflict because priorities must be unique.
  2. Step 2: Understand effect of priority conflict

    Load balancer cannot decide which rule to apply, so traffic routing fails or is unpredictable.
  3. Final Answer:

    Both listener rules have the same priority, causing conflict -> Option C
  4. Quick Check:

    Unique priorities required for listener rules [OK]
Hint: Listener rule priorities must be unique numbers [OK]
Common Mistakes:
  • Ignoring priority uniqueness
  • Assuming host_header condition is invalid
  • Overlooking target group correctness
5. You want to implement a blue-green deployment in Terraform with minimal downtime. Which approach best achieves this?
hard
A. Deploy new version to green environment and keep routing traffic to blue until green is manually deleted
B. Deploy new version to green environment, test it, then update load balancer to route all traffic to green
C. Deploy new version directly to blue environment and restart all servers simultaneously
D. Deploy new version to blue environment and use DNS TTL to switch traffic slowly

Solution

  1. Step 1: Understand blue-green deployment goals

    The goal is zero downtime by having two identical environments and switching traffic atomically.
  2. Step 2: Evaluate deployment approaches

    Deploying to green, testing, then switching load balancer traffic ensures smooth transition without downtime.
  3. Step 3: Compare other options

    Direct deploy with restart causes downtime; manual deletion delays switch; DNS TTL causes slow switch and possible downtime.
  4. Final Answer:

    Deploy new version to green environment, test it, then update load balancer to route all traffic to green -> Option B
  5. Quick Check:

    Blue-green = test new env, then switch traffic [OK]
Hint: Test new environment fully before switching traffic [OK]
Common Mistakes:
  • Restarting servers causing downtime
  • Delaying traffic switch by manual deletion
  • Relying on DNS TTL for instant switch