Screenshot from the article

Introduction

In modern DevOps practices, Immutable Infrastructure ensures that deployed instances remain unchanged after deployment, reducing configuration drift and improving stability. Blue-Green Deployments allow teams to switch traffic between two identical environments (Blue & Green), minimizing downtime and reducing the risk of failed deployments.

Using Terraform, we can automate the provisioning of immutable infrastructure and manage Blue-Green deployments seamlessly.

What This Guide Covers:

  • The concept of Immutable Infrastructure
  • How Blue-Green Deployments work
  • Terraform implementation for Blue-Green Deployments
  • Best practices and real-world examples
  • FAQs and troubleshooting

1. Understanding Immutable Infrastructure and Blue-Green Deployments

Immutable Infrastructure

Unlike traditional deployments where servers are modified over time, immutable infrastructure ensures that servers are replaced rather than modified, eliminating configuration drift. If an update is needed, a new instance is provisioned with the required changes, and the old one is decommissioned.

Blue-Green Deployment Strategy

  • Blue Environment: The currently running production environment.
  • Green Environment: The new version deployed in parallel.
  • Traffic Switching: After successful validation, traffic is switched to the Green environment.
  • Rollback: If issues arise, switching back to Blue is immediate.

2. Implementing Blue-Green Deployments using Terraform

Prerequisites

  • Terraform installed (>=1.0)
  • AWS CLI configured with appropriate IAM permissions
  • AWS EC2 instances, ALB (Application Load Balancer), and Auto Scaling Group setup

Step-by-Step Implementation

1. Define Variables (variables.tf)

variable "region" {
  default = "us-east-1"
}
variable "ami_id" {
  description = "Amazon Machine Image ID for EC2"
}
variable "instance_type" {
  default = "t2.micro"
}

2. Create an Auto Scaling Group with Two Environments (blue-green.tf)

resource "aws_launch_template" "blue" {
  name          = "blue-environment"
  image_id      = var.ami_id
  instance_type = var.instance_type
}
resource "aws_launch_template" "green" {
  name          = "green-environment"
  image_id      = var.ami_id
  instance_type = var.instance_type
}
resource "aws_autoscaling_group" "blue" {
  desired_capacity     = 2
  max_size            = 3
  min_size            = 2
  launch_template {
    id      = aws_launch_template.blue.id
    version = "$Latest"
  }
}
resource "aws_autoscaling_group" "green" {
  desired_capacity     = 2
  max_size            = 3
  min_size            = 2
  launch_template {
    id      = aws_launch_template.green.id
    version = "$Latest"
  }
}

3. Create an Application Load Balancer (alb.tf)

resource "aws_lb" "blue_green_lb" {
  name               = "blue-green-lb"
  internal           = false
  load_balancer_type = "application"
  security_groups    = [aws_security_group.lb_sg.id]
  subnets            = aws_subnet.public[*].id
}
resource "aws_lb_target_group" "blue" {
  name     = "blue-tg"
  port     = 80
  protocol = "HTTP"
  vpc_id   = aws_vpc.main.id
}
resource "aws_lb_target_group" "green" {
  name     = "green-tg"
  port     = 80
  protocol = "HTTP"
  vpc_id   = aws_vpc.main.id
}

4. Traffic Switching Mechanism (switch_traffic.tf)

resource "aws_lb_listener" "blue" {
  load_balancer_arn = aws_lb.blue_green_lb.arn
  port              = 80
  protocol          = "HTTP"
  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.blue.arn
  }
}
resource "aws_lb_listener" "green" {
  load_balancer_arn = aws_lb.blue_green_lb.arn
  port              = 8080
  protocol          = "HTTP"
  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.green.arn
  }
}

5. Deploy Using Terraform

Run the following Terraform commands:

tf init
tf plan
tf apply -auto-approve

6. Switching Traffic to Green

resource "aws_lb_listener_rule" "switch" {
  listener_arn = aws_lb_listener.blue.arn
  priority     = 100
  conditions {
    field  = "host-header"
    values = ["myapp.example.com"]
  }
  actions {
    type             = "forward"
    target_group_arn = aws_lb_target_group.green.arn
  }
}

Apply the change:

tf apply -auto-approve

3. Best Practices

Use Immutable AMIs: Pre-build the application into an AMI to ensure consistency.✅ Automate with CI/CD: Integrate Terraform with GitHub Actions or Jenkins for seamless deployments.✅ Monitor Deployments: Use AWS CloudWatch to track instance health and application performance.✅ Enable Rollback: Ensure traffic can be easily switched back in case of failures.

4. FAQs & Troubleshooting

❓ How do I roll back to the Blue environment?

✅ Modify the listener rule to point back to the blue target group and reapply Terraform.

tf apply -auto-approve

❓ What if the Green deployment fails?

✅ Ensure logs from CloudWatch and EC2 instances provide insights.✅ Check security groups, IAM permissions, and instance health.

❓ Can I automate traffic switching?

✅ Yes! AWS CodeDeploy or Lambda can dynamically modify the ALB listener rules.

5. Conclusion

Blue-Green Deployments with Terraform ensure zero-downtime deployments while maintaining the benefits of Immutable Infrastructure. By integrating Auto Scaling Groups, ALB, and Terraform, we can automate and streamline deployments, enabling high availability and scalability in cloud environments.

📢 Have questions or feedback? Drop a comment below or connect with me on Twitter/X@spysood!

Originally published on Medium.