Kubernetes Provider

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:

  • Automate the creation and management of Kubernetes resources like Pods, Deployments, and Services.
  • Configure cluster-level resources such as Namespaces, Storage Classes, and RBAC rules.
  • Integrate seamlessly with Kubernetes clusters, whether self-managed or on platforms like Google Kubernetes Engine (GKE) or Amazon Elastic Kubernetes Service (EKS).

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?

  • The provider block connects Terraform to your Kubernetes cluster using the configuration in ~/.kube/config.
  • The 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.