Go for Infrastructure Engineers›Part 3 · Cheat sheet & self-check

Part 3 — Go and Kubernetes · wrap-up

Cheat sheet & self-check

Every command from this section on one page.

07 · client-go: talking to Kubernetes

Set-up

go get k8s.io/client-go@v0.34.0 k8s.io/apimachinery@v0.34.0client-go and apimachinery, versions matching your clusters' minor
clientcmd.BuildConfigFromFlags("", kubeconfigPath)Config from a kubeconfig file
rest.InClusterConfig()Config inside a pod (ServiceAccount token)
kubernetes.NewForConfig(cfg)The typed clientset

Calls

cs.CoreV1().Nodes().List(ctx, metav1.ListOptions{})List nodes
cs.CoreV1().Pods("").List(ctx, metav1.ListOptions{FieldSelector: "status.phase=Pending"})Pending pods in all namespaces
cs.CoreV1().Nodes().Patch(ctx, name, types.MergePatchType, data, metav1.PatchOptions{})Patch a node (labels, annotations)
apierrors.IsNotFound(err)Was it a 404?

08 · A small controller with Kubebuilder

Kubebuilder

kubebuilder init --domain platform.example.com --repo github.com/me/team-operatorScaffold a project
kubebuilder create api --group platform --version v1alpha1 --kind TeamNamespaceA CRD type and its controller
make manifests generateRegenerate CRD YAML, RBAC and deep-copy code after editing types
make install runInstall the CRD into the current cluster and run the controller locally
make testUnit and envtest-based tests
make docker-build deploy IMG=registry.example.com/team-operator:0.1.0Build and deploy into the cluster

09 · Testing, linting and shipping

Quality

go test ./... -race -coverAll tests, race detector, coverage
go test -run TestParse/empty -v ./internal/auditOne sub-test, verbose
golangci-lint runMany linters at once (errcheck, staticcheck, govet…)
govulncheck ./...Known vulnerabilities in code paths you actually call

Ship

CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o kaudit .Small static binary
docker build -t registry.example.com/kaudit:0.1.0 .Multi-stage build into a distroless image
goreleaser release --cleanMulti-platform binaries, checksums and release notes from a tag