How to Use ConfigMaps and Secrets with Go Apps in Kubernetes

Inject ConfigMaps and Secrets into Go apps via environment variables or mounted files in Kubernetes deployments.

You inject ConfigMaps as environment variables or mounted files, and Secrets as environment variables or mounted files, then read them in your Go app using os.Getenv or os.ReadFile.

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  LOG_LEVEL: "info"
---
apiVersion: v1
kind: Secret
metadata:
  name: app-secret
type: Opaque
stringData:
  DB_PASSWORD: "supersecret"
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: go-app
spec:
  template:
    spec:
      containers:
      - name: go-app
        image: my-go-app:latest
        env:
        - name: LOG_LEVEL
          valueFrom:
            configMapKeyRef:
              name: app-config
              key: LOG_LEVEL
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: app-secret
              key: DB_PASSWORD
        volumeMounts:
        - name: config-volume
          mountPath: /etc/config
        - name: secret-volume
          mountPath: /etc/secrets
      volumes:
      - name: config-volume
        configMap:
          name: app-config
      - name: secret-volume
        secret:
          secretName: app-secret

In your Go code, access them like this:

package main

import (
	"fmt"
	"os"
)

func main() {
	logLevel := os.Getenv("LOG_LEVEL")
	dbPassword, _ := os.ReadFile("/etc/secrets/DB_PASSWORD")
	fmt.Printf("Log Level: %s, DB Password: %s\n", logLevel, dbPassword)
}