Kubernetes: Global environment variables for pods

September 30, 2020 - Last updated: February 12, 2021

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

One of the solution is create a ConfigMap and use the envFrom to define all of the ConfigMap's data as container environment variables.

Create a ConfigMap with the variables you want to insert to the pod.

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

Create a pod with the ConfigMap created before.

---
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 environment variables ENVIRONMENT, DATABASE_HOST, and DATABASE_PORT.

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 insert the variables.

Related posts