Kubernetes
Go Programming
ConfigMap
API Integration
DevOps

K8S Read config map via go API

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Reading a ConfigMap from Go means using the Kubernetes client-go library to talk to the API server and fetch the object from a namespace. The overall flow is straightforward: build a client configuration, create a typed clientset, and call the ConfigMaps API for the namespace you care about.

Create the Kubernetes Client

In an external tool or local script, the most common setup is to read kubeconfig from disk.

go
1package main
2
3import (
4    "context"
5    "fmt"
6    "path/filepath"
7
8    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
9    "k8s.io/client-go/kubernetes"
10    "k8s.io/client-go/tools/clientcmd"
11    "k8s.io/client-go/util/homedir"
12)
13
14func main() {
15    kubeconfig := filepath.Join(homedir.HomeDir(), ".kube", "config")
16    config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
17    if err != nil {
18        panic(err)
19    }
20
21    clientset, err := kubernetes.NewForConfig(config)
22    if err != nil {
23        panic(err)
24    }
25
26    cm, err := clientset.CoreV1().ConfigMaps("default").Get(
27        context.Background(),
28        "app-config",
29        metav1.GetOptions{},
30    )
31    if err != nil {
32        panic(err)
33    }
34
35    fmt.Println(cm.Data)
36}

This reads the ConfigMap named app-config from the default namespace and prints its key-value data.

Read a Specific Key

Most applications do not need the whole object. They need one configuration entry.

go
1value, ok := cm.Data["DATABASE_HOST"]
2if !ok {
3    panic("DATABASE_HOST not found in ConfigMap")
4}
5fmt.Println(value)

ConfigMap.Data stores string keys and string values. If you use binary content, check BinaryData instead.

In-Cluster Code Uses a Different Config Source

If the Go program runs inside Kubernetes as a Pod, use in-cluster configuration instead of a kubeconfig file.

go
1config, err := rest.InClusterConfig()
2if err != nil {
3    panic(err)
4}
5
6clientset, err := kubernetes.NewForConfig(config)
7if err != nil {
8    panic(err)
9}

You need this extra import:

go
import "k8s.io/client-go/rest"

This works when the Pod has the right service account credentials and RBAC permissions.

Handle Errors Carefully

A failed Get call can mean different things:

  • The ConfigMap does not exist
  • The namespace is wrong
  • The caller lacks get permission
  • The client cannot authenticate to the API server

In real code, inspect the error instead of panicking immediately.

go
if err != nil {
    return fmt.Errorf("read configmap: %w", err)
}

If you want more control, use Kubernetes error helpers such as apierrors.IsNotFound(err).

RBAC Still Applies

Reading a ConfigMap through the API requires permission. A Pod running inside the cluster does not automatically get read access to every namespace.

A minimal role might look like this:

yaml
1apiVersion: rbac.authorization.k8s.io/v1
2kind: Role
3metadata:
4  name: configmap-reader
5  namespace: default
6rules:
7  - apiGroups: [""]
8    resources: ["configmaps"]
9    verbs: ["get"]

Then bind that role to the service account used by the Pod.

When API Access Is the Right Choice

Kubernetes also lets Pods consume ConfigMaps as mounted files or environment variables. Reading via the API is useful when:

  • You are writing an operator or controller
  • You need to read arbitrary namespaces programmatically
  • You want to watch for updates and react dynamically

If a normal application only needs static config at startup, mounting the ConfigMap into the Pod may be simpler than calling the API directly.

Common Pitfalls

A common mistake is forgetting the namespace. ConfigMaps are namespaced objects, so looking in the wrong namespace makes a valid ConfigMap appear missing.

Another mistake is using BuildConfigFromFlags inside a Pod. In-cluster code should usually call rest.InClusterConfig() instead.

A third mistake is debugging the client code before checking RBAC. The code can be correct while the service account simply lacks permission to read ConfigMaps.

Summary

  • Use client-go to build a config, create a clientset, and call CoreV1().ConfigMaps(namespace).Get(...).
  • Use kubeconfig for external tools and InClusterConfig for Pods running inside the cluster.
  • Read values from ConfigMap.Data or BinaryData depending on the content.
  • Make sure the caller has RBAC permission to get the ConfigMap.
  • Consider mounted files or environment variables if API access is unnecessary.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.