Terraform Configuration for Kubernetes Deployment
Terraform Configuration Overview
Required Providers
terraform {
required_providers {
kubernetes = {
source = "hashicorp/kubernetes"
version = "~> 2.0"
}
}
}
- Purpose: Specifies the required provider,
kubernetes
, from HashiCorp, ensuring version compatibility (~> 2.0
).
Kubernetes Provider Configuration
provider "kubernetes" {
config_path = "~/.kube/config"
}
- Purpose: Configures access to the Kubernetes cluster using the
~/.kube/config
file, enabling Terraform to interact with the cluster.
Local Variables
locals {
applications = jsondecode(file("${path.module}/apps.json")).applications
}
- Purpose: Loads application configurations dynamically from an
apps.json
file, enabling modular and reusable application definitions.
- Key: The
applications
variable decodes the JSON file containing application details such as name, image, replicas, and port.
Resource Definitions
Kubernetes Deployment Resource
resource "kubernetes_deployment_v1" "apps" {
for_each = { for app in local.applications : app.name => app }
metadata {
name = "${each.value.name}-deployment"
labels = {
app = each.value.name
}
}
spec {
replicas = each.value.replicas
selector {
match_labels = {
app = each.value.name
}
}
template {
metadata {
labels = {
app = each.value.name
}
}
spec {
container {
image = each.value.image
name = each.value.name
args = ["-listen=:${each.value.port}", "-text=\\"I am ${each.value.name}\\""]
port {
container_port = each.value.port
}
}
}
}
}
}
- Purpose: Creates deployments dynamically for each application defined in the
apps.json
file.
- Key Features:
- Uses
for_each
to iterate through applications.
- Sets container image, replicas, and ports dynamically based on application configurations.
- Labels each deployment for efficient management.
Kubernetes Service Resource
resource "kubernetes_service_v1" "apps" {
for_each = { for app in local.applications : app.name => app }
metadata {
name = "${each.value.name}-service"
}
spec {
selector = {
app = each.value.name
}
port {
port = each.value.port
target_port = each.value.port
}
type = "ClusterIP"
}
}
- Purpose: Creates a
ClusterIP
service for each application.