Terraform Cost Optimization for AWS - Reduce Your Cloud Bill
Practical Terraform patterns to reduce AWS costs: right-sizing, spot instances, scheduling, and reserved capacity. Step-by-step guide with code examples and ...
Guides
How to achieve zero-downtime deployments with Terraform using blue-green, rolling updates, and create_before_destroy. Step-by-step guide with code examples a...
Infrastructure changes shouldn't cause outages. Here are battle-tested patterns for zero-downtime deployments with Terraform.
The simplest approach — create the new resource before destroying the old one:
resource "aws_instance" "web" {
ami = var.ami_id
instance_type = var.instance_type
lifecycle {
create_before_destroy = true
}
}Maintain two environments, switch traffic between them:
variable "active_color" {
default = "blue" # Change to "green" to switch
}
resource "aws_lb_target_group" "blue" {
name = "app-blue"
port = 80
protocol = "HTTP"
vpc_id = aws_vpc.main.id
}
resource "aws_lb_target_group" "green" {
name = "app-green"
port = 80
protocol = "HTTP"
vpc_id = aws_vpc.main.id
}
resource "aws_lb_listener_rule" "app" {
listener_arn = aws_lb_listener.front.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 = ["/*"] }
}
}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" {
desired_capacity = 3
max_size = 6
min_size = 3
launch_template {
id = aws_launch_template.app.id
version = "$Latest"
}
instance_refresh {
strategy = "Rolling"
preferences {
min_healthy_percentage = 66
instance_warmup = 300
}
}
}resource "aws_route53_record" "app" {
zone_id = var.zone_id
name = "app.example.com"
type = "A"
weighted_routing_policy {
weight = var.active_color == "blue" ? 100 : 0
}
set_identifier = "blue"
alias {
name = aws_lb.blue.dns_name
zone_id = aws_lb.blue.zone_id
}
}create_before_destroy for stateless resourcesprevent_destroy on databases — data loss isn't zero-downtimePractical Terraform patterns to reduce AWS costs: right-sizing, spot instances, scheduling, and reserved capacity. Step-by-step guide with code examples and ...
Complete guide to testing Terraform configurations with terraform test, Terratest, and validation rules. Step-by-step guide with code examples and best pract...
Complete guide to Terraform data sources: querying existing infrastructure, filtering, and common patterns. Step-by-step guide with code examples and best pr...
Best practices for managing secrets, passwords, and sensitive data in Terraform configurations. Step-by-step guide with code examples and best practices for ...