Skip to content
DevOps AI ToolKit
Newsletter
All prompts
AI for Terraform Difficulty: Advanced ClaudeChatGPTCursor

Terraform Blue Green Deployment Pattern Prompt

Implement blue/green infrastructure deployments in Terraform with parallel resource sets, create_before_destroy, and weighted DNS or target-group cutover with rollback.

Target user
Infrastructure engineers building zero-downtime release pipelines
Difficulty
Advanced
Tools
Claude, ChatGPT, Cursor

The prompt

You are a senior infrastructure engineer implementing a blue/green deployment pattern in Terraform (assume AWS + ALB, but keep the toggle mechanism generic). Two parallel resource sets ("blue" and "green") coexist; traffic shifts from the old color to the new, with a clean rollback path.

Work through these steps in order:

1. Define an `active_color` variable (`"blue"` | `"green"`) as the single source of truth. Provision BOTH colors' compute in parallel (ASG/launch template or ECS service) using `for_each` over a `toset(["blue","green"])` so each color is an independent, addressable set.

2. Use `create_before_destroy = true` in a `lifecycle` block on immutable resources (launch templates, target groups) so the new version is fully created and healthy before the old is torn down. Explain the dependency ordering this forces.

3. Implement the cutover with weighted routing, NOT resource deletion. Use `aws_lb_listener` with `forward` + weighted `target_group` stickiness, or Route 53 weighted records, so you shift 0/100 -> 10/90 -> 100/0 by changing weights only. Keep the idle color warm for instant rollback.

4. Rollback = flip `active_color` back and set weights; because the old color was never destroyed, rollback is a weight change with no rebuild.

5. Warn about DESTRUCTIVE and traffic-splitting hazards: destroying the live color before draining connections drops in-flight requests; DNS TTL means a weight change does NOT take effect instantly, so clients keep hitting the old color for up to the TTL (split traffic); and a `count`/`for_each` toggle that removes the idle color eliminates your rollback target.

6. Recommend health-gated promotion (ALB target health, deregistration delay / connection draining) and only removing the idle color in a SEPARATE, later apply once the new color is proven.

Input template:
```
Platform: <ECS | ASG+ALB | Route53 weighted | ...>
Cutover mechanism: <ALB target-group weights | Route53 weighted records>
DNS TTL: <seconds>
Health check + drain settings: <path, deregistration_delay>
Current active color: <blue | green>
```

Run this prompt with AI

Test it, get an AI-improved version, or compare models — live in the Prompt Workspace. No copy-paste.

Why this prompt works

Blue/green in Terraform fails when engineers conflate “activate the new color” with “destroy the old color” in a single apply. The safe pattern keeps both colors provisioned, shifts traffic with weights (not resource lifecycle), and uses create_before_destroy so nothing healthy is ever torn down before its replacement is live. This prompt enforces that separation and surfaces the two silent killers: connection draining on teardown and DNS TTL causing split traffic during cutover.

How to use it

Specify your platform, cutover mechanism (ALB weights vs Route 53 weighted records), DNS TTL, and drain settings. Ask the model for a for_each-over-colors module, weighted routing wired to active_color, and a two-phase runbook: apply 1 shifts weights, apply 2 (later) removes the retired color. Rehearse rollback by flipping the weight variable back.

Useful commands

# Shift weights only - no resource destruction on cutover
terraform apply -var 'active_color=green' -var 'green_weight=100' -var 'blue_weight=0'

# Verify BOTH colors still exist in state (rollback target intact)
terraform state list | grep -E 'blue|green'

# Watch ALB target health before promoting
aws elbv2 describe-target-health \
  --target-group-arn "$GREEN_TG_ARN" \
  --query 'TargetHealthDescriptions[].TargetHealth.State'

# Lower Route53 TTL BEFORE cutover to shrink the split-traffic window
aws route53 change-resource-record-sets --hosted-zone-id "$ZONE_ID" \
  --change-batch file://lower-ttl.json

# Only after green is proven: retire blue in a SEPARATE apply
terraform apply -var 'active_color=green' -var 'retire_idle=true'

Patterns

Both colors provisioned in parallel with create_before_destroy:

variable "active_color" {
  type    = string
  default = "blue"
  validation {
    condition     = contains(["blue", "green"], var.active_color)
    error_message = "active_color must be blue or green."
  }
}

locals {
  colors = toset(["blue", "green"])
}

resource "aws_lb_target_group" "color" {
  for_each = local.colors

  name                 = "app-${each.key}"
  port                 = 8080
  protocol             = "HTTP"
  vpc_id               = var.vpc_id
  deregistration_delay = 120   # drain in-flight connections

  health_check {
    path                = "/healthz"
    healthy_threshold   = 3
    unhealthy_threshold = 2
  }

  lifecycle {
    create_before_destroy = true
  }
}

Weighted listener cutover keyed off active_color (idle color stays warm):

locals {
  weights = {
    blue  = var.active_color == "blue" ? 100 : var.blue_weight
    green = var.active_color == "green" ? 100 : var.green_weight
  }
}

resource "aws_lb_listener_rule" "cutover" {
  listener_arn = aws_lb_listener.https.arn
  priority     = 100

  action {
    type = "forward"
    forward {
      dynamic "target_group" {
        for_each = local.colors
        content {
          arn    = aws_lb_target_group.color[target_group.value].arn
          weight = local.weights[target_group.value]
        }
      }
      stickiness {
        enabled  = true
        duration = 300
      }
    }
  }

  condition {
    path_pattern { values = ["/*"] }
  }
}

Related prompts

More Terraform prompts & error guides

Browse every Terraform prompt and troubleshooting guide in one place.

Free download · 368-page PDF

Reading prompts? Get all 500 in one free PDF

500 battle-tested, copy-paste AI prompts engineered by a senior systems engineer — every one with fill-in placeholders and safety/back-out notes. Drop your email and it's yours.

  • 500 prompts: Linux · Kubernetes · Terraform · OpenStack · GitLab · Docker · Monitoring · Incident Response
  • Instant PDF download — yours free, forever
  • Plus one practical AI-workflow email a week (no spam)

Single opt-in · unsubscribe anytime · no spam.