Kubernetes: Global environment variables for pods

September 30, 2020 - Last updated: September 30, 2020

I was trying to inject a few global environment variables to every container running, so one of the options was Pod Presets but I realize this feature was removed (check this pull request) probably in Kubernetes 1.20.x will disappear.

The alternative is to create a ConfigMap and use the envFrom to define all of the ConfigMap's data as container environment variables. The key from the ConfigMap becomes the environment variable name in the Pod.

Create a ConfigMap with the variables you want to inject.

---
apiVersion: v1
kind: ConfigMap
metadata:
  name: global
  namespace: tools
data:
  ENVIRONMENT: "dev"
  DATABASE_HOST: "postgresql.dev.local"
  DATABASE_PORT: "5432"

Create a pod and insert the ConfigMap's data as environment variables.

---
apiVersion: v1
kind: Pod
metadata:
  name: webserver
  namespace: tools
spec:
  containers:
    - name: nginx
      image: nginx
      envFrom:
      - configMapRef:
          name: global

The new pod now has defined the variables ENVIRONMENT, DATABASE_HOST, and DATABASE_PORT as environment variables.

Limitations

  • The ConfigMap is per namespaces, you need to duplicate the ConfigMap per namespace.
  • You need to define envFrom on each deployment or pod you want to inject the variables.

Related posts