Search code examples
kuberneteskubernetes-helmconfigmapkubernetes-secrets

Concating values from configMap and secret


I have a configMap file:

apiVersion: v1
kind: ConfigMap
metadata:
  labels:
    owner: testdb
  name: testdb-configmap 
data:
  host: postgres
  port: "5432" 

and a secret file:

aapiVersion: v1
kind: Secret
type: Opaque
metadata:
  labels:
    owner: testdb
  name: testdb-secret
  namespace: test
data:
  user: dGVzdA==
  pwd: dGVzdA==

and I want to build an environment variable CONNECTION_STRING as below:

env:
 - name: CONNECTION_STRING
   value: "Host=<host-from-configmap>;Username=<user-from-secret>;Password=<password-from-secret>;Port=<port-from-configmap>;Pooling=False;"

I want to know if this is possible and if yes, then how? I have also looked at using .tpl (named templates) but couldn't figure out a way.


NOTE

Since I don't have access to the image which requires CONNECTION_STRING I have to build it this way. These configmap and secret files are also going to remain like this.



Solution

  • Kubernetes can set environment variables based on other environment variables. This is a core Kubernetes Pod capability, and doesn't depend on anything from Helm.

    Your value uses four components, two from the ConfigMap and two from the Secret. You need to declare each of these as separate environment variables, and then declare a main environment variable that concatenates them together.

    env:
      - name: TESTDB_HOST
        valueFrom:
          configMapKeyRef:
            name: testdb-configmap # {{ include "chart.name" . }}
            key: host
      - name: TESTDB_PORT
        valueFrom:
          configMapKeyRef:
            name: testdb-configmap
            key: port
      - name: TESTDB_USER
        valueFrom:
          secretKeyRef:
            name: testdb-secret
            key: user
      - name: TESTDB_PASSWORD
        valueFrom:
          secretKeyRef:
            name: testdb-secret
            key: password
      - name: CONNECTION_STRING
        value: Host=$(TESTDB_HOST);Username=$(TESTDB_USER);Password=$(TESTDB_PASSWORD);PORT=$(TESTDB_PORT);Pooling=False;