The Kubernetes Provider allows you to manage Kubernetes resources directly from Terraform. From deploying applications and services to configuring namespaces and storage classes, this provider simplifies infrastructure as code for containerized environments.
Key Features:
Example Use Case: Creating a Namespace
Namespaces in Kubernetes are used to isolate resources within a cluster. Here’s how to create one using the Kubernetes Provider:
provider "kubernetes" {
config_path = "~/.kube/config"
}
resource "kubernetes_namespace" "example" {
metadata {
name = "example-namespace"
labels = {
environment = "development"
team = "backend"
}
}
}
What’s Happening Here?
provider
block connects Terraform to your Kubernetes cluster using the configuration in ~/.kube/config
.kubernetes_namespace
resource creates a namespace named example-namespace
with metadata labels for environment and team.Advanced Tip:
Use the provider to deploy a complete application, including a Deployment and Service:
resource "kubernetes_deployment" "nginx" {
metadata {
name = "nginx"
namespace = kubernetes_namespace.example.metadata[0].name
}
spec {
replicas = 2
selector {
match_labels = {
app = "nginx"
}
}
template {
metadata {
labels = {
app = "nginx"
}
}
spec {
container {
name = "nginx"
image = "nginx:latest"
}
}
}
}
}
resource "kubernetes_service" "nginx" {
metadata {
name = "nginx-service"
namespace = kubernetes_namespace.example.metadata[0].name
}
spec {
selector = {
app = "nginx"
}
port {
port = 80
target_port = 80
}
type = "LoadBalancer"
}
}
This configuration deploys an NGINX application as a Deployment with two replicas and exposes it using a LoadBalancer Service.