Simplifying Blue-Green Deployments with Terraform on Kubernetes — Part 1

Introduction

ab1sh3k
2 min readApr 20, 2024

For cloud engineers aiming to enhance deployment strategies using Terraform, understanding the concepts of blue-green deployments, automated rollbacks, and integration with monitoring tools is crucial. This comprehensive guide explores the integration of Terraform with Kubernetes for blue-green deployments, focusing on managing and automating these processes effectively.

Understanding Blue-Green Deployments

Blue-green deployment is a strategy designed to reduce risks by maintaining two identical production environments: one active (blue) and one idle (green). Once the green environment is fully tested and ready, traffic is switched from blue to green, making the transition smooth and practically immediate.

Setting Up Environments with Terraform

The first step in implementing blue-green deployments using Terraform is setting up two identical environments, known as the blue and green environments.

Example Configuration:

# Blue environment
resource "kubernetes_deployment" "blue" {
metadata {
name = "nginx-blue"
}
spec {
replicas = 3
template {
metadata {
labels {
app = "nginx"
version = "blue"
}
}
spec {
containers {
image = "nginx:1.18"
name = "nginx"
}
}
}
}
}

# Green environment
resource "kubernetes_deployment" "green" {
metadata {
name = "nginx-green"
}
spec {
replicas = 3
template {
metadata {
labels {
app = "nginx"
version = "green"
}
}
spec {
containers {
image = "nginx:1.19"
name = "nginx"
}
}
}
}
}

This configuration ensures that both environments are set up with the same number of replicas but can run different versions of the software.

Managing Traffic with Kubernetes Services

Kubernetes services are used to route traffic to the appropriate environment. Initially, all traffic might go to the blue environment, and after testing, it can be switched to green.

Example Configuration:

resource "kubernetes_service" "nginx" {
metadata {
name = "nginx-service"
}
spec {
type = "LoadBalancer"
selector {
app = "nginx"
version = "blue" # Change this to "green" to switch traffic
}
ports {
port = 80
target_port = 80
}
}
}

--

--

No responses yet