K8S deployments with shared environment variables
You can create a ConfigMap with all the common kye:value
pairs of env variables.
Then you can reuse the configmap to declare all the values of configMap
as environment in Deployment
.
Here is an example taken from kubernetes official docs.
Create a ConfigMap containing multiple key-value pairs.
apiVersion: v1kind: ConfigMapmetadata: name: special-config namespace: defaultdata: SPECIAL_LEVEL: very SPECIAL_TYPE: charm
Use envFrom to define all of the ConfigMap’s data as Pod environment variables. The key from the ConfigMap becomes the environment variable name in the Pod.
apiVersion: v1kind: Podmetadata: name: test-podspec: containers: - name: test-container image: k8s.gcr.io/busybox command: [ "/bin/sh", "-c", "env" ] envFrom: - configMapRef: name: special-config # All the key-value pair will be taken as environment key-value pair env: - name: uncommon value: "uncommon value" restartPolicy: Never
You can specify uncommon env variables in env
field.
Now, to verify if the environment variables are actually available, see the logs.
$ kubectl logs -f test-pod KUBERNETES_PORT=tcp://10.96.0.1:443SPECIAL_LEVEL=veryuncommon=uncommon valueSPECIAL_TYPE=charm...
Here, it is visible that all the provided environments are available.
you can add a secret first then use newly created secret into your countless deployment files to share same environment variable with value:
kubectl create secret generic jwt-secret --from-literal=JWT_KEY=my_awesome_jwt_secret_code
apiVersion: apps/v1kind: Deploymentmetadata: name: auth-deplspec: replicas: 1 selector: matchLabels: app: auth template: metadata: labels: app: auth spec: containers: - name: auth image: lord/auth resources: requests: memory: "128Mi" cpu: "250m" limits: memory: "256Mi" cpu: "500m" env: - name: JWT_KEY valueFrom: secretKeyRef: name: jwt-secret key: JWT_KEY
process.env.JWT_KEY
apiVersion: apps/v1kind: Deploymentmetadata: name: tickets-deplspec: replicas: 1 selector: matchLabels: app: tickets template: metadata: labels: app: tickets spec: containers: - name: tickets image: lord/tickets resources: requests: memory: "128Mi" cpu: "250m" limits: memory: "256Mi" cpu: "500m" env: - name: JWT_KEY valueFrom: secretKeyRef: name: jwt-secret key: JWT_KEY
process.env.JWT_KEY