CoursesTerratestIntermediate

Testing Kubernetes & Helm

Deploy and probe workloads.

Advanced12 min · lesson 6 of 12

Terratest tests Kubernetes and Helm as well as Terraform, using the k8s and helm modules. The flow mirrors the Terraform one: deploy (apply manifests or install a chart), wait for readiness, assert (the service responds, the right resources exist), and clean up. This lets you prove a Helm chart actually brings up a working, healthy application — not just that it renders — which is exactly the gap the Helm course flagged.

k8s_test.go
import (
"github.com/gruntwork-io/terratest/modules/helm"
"github.com/gruntwork-io/terratest/modules/k8s"
)
func TestChart(t *testing.T) {
kubeOpts := k8s.NewKubectlOptions("", "", "test-ns")
helmOpts := &helm.Options{ KubectlOptions: kubeOpts, SetValues: map[string]string{"replicaCount":"2"} }
defer helm.Delete(t, helmOpts, "payments", true)
helm.Install(t, helmOpts, "../charts/payments", "payments")
k8s.WaitUntilServiceAvailable(t, kubeOpts, "payments", 30, 5*time.Second)
// then hit the service and assert it works
}

Ephemeral clusters

Where do these tests run? Against a throwaway cluster — a kind or k3d cluster spun up in CI (cheap, fast, no cloud bill), or a dedicated test namespace in a sandbox cluster. kind is popular for Terratest Kubernetes suites because it is a full cluster in a container that CI can create and destroy per run, keeping tests isolated and inexpensive. The helm/k8s modules do not care whether the cluster is kind or a real cloud one.

terminal
$ kind create cluster --name terratest # ephemeral cluster for the suite
$ go test -v -timeout 20m ./k8s/...
$ kind delete cluster --name terratest # tear it down after
Namespace and clean up, or tests collide
Kubernetes tests running against a shared cluster will step on each other if they share a namespace — a leftover release from a failed run breaks the next. Give each test its own namespace (unique per run), defer the Helm delete/namespace cleanup, and prefer an ephemeral kind cluster per run when possible so isolation is total and there is nothing to leak.