Terraform Advanced — Zero-Downtime Deployments

1 minute read

Deploy infrastructure changes without service interruption.


create_before_destroy

resource "aws_launch_template" "app" {
  name_prefix   = "app-"
  image_id      = var.ami_id
  instance_type = var.instance_type

  lifecycle {
    create_before_destroy = true
  }
}

resource "aws_autoscaling_group" "app" {
  launch_template {
    id      = aws_launch_template.app.id
    version = aws_launch_template.app.latest_version
  }

  instance_refresh {
    strategy = "Rolling"
    preferences {
      min_healthy_percentage = 90
    }
  }
}

Blue/Green with ALB

# Blue target group (current)
resource "aws_lb_target_group" "blue" {
  name     = "app-blue"
  port     = 8080
  protocol = "HTTP"
  vpc_id   = var.vpc_id
}

# Green target group (new version)
resource "aws_lb_target_group" "green" {
  name     = "app-green"
  port     = 8080
  protocol = "HTTP"
  vpc_id   = var.vpc_id
}

# Switch traffic by changing the listener
resource "aws_lb_listener_rule" "app" {
  listener_arn = var.listener_arn
  action {
    type             = "forward"
    target_group_arn = var.active_color == "blue" ? aws_lb_target_group.blue.arn : aws_lb_target_group.green.arn
  }
  condition {
    path_pattern { values = ["/app/*"] }
  }
}

ECS Rolling Deployment

resource "aws_ecs_service" "app" {
  name            = "app"
  cluster         = aws_ecs_cluster.main.id
  task_definition = aws_ecs_task_definition.app.arn
  desired_count   = 3

  deployment_minimum_healthy_percent = 100
  deployment_maximum_percent         = 200
  # New tasks start before old ones stop
}

💡 Production Tip: Always test deployment strategies in staging first. Zero-downtime deployments have subtle failure modes.


What’s Next?

Track costs and detect drift.

← Account-Per-Environment Cost Tagging & Drift →

Updated: