3

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.


David Maze
  • 130,717
  • 29
  • 175
  • 215
Alpesh
  • 606
  • 6
  • 15

2 Answers2

11

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;
David Maze
  • 130,717
  • 29
  • 175
  • 215
1

I do not believe what you're asking to do is possible.

Furthermore, do not use configs maps for storing information like this. It's best practice to use secrets and then mount them to your container as files or ENV variables.

I would abandon whatever you're thinking and re-evaluate what you're trying to accomplish.

Derek Williams
  • 525
  • 6
  • 21
  • As you can see I am not using configmap for anything sensitive, I have a secret file for that. I can mount individual values to ENV variables but needed to concat them into one value. – Alpesh Nov 15 '21 at 18:45
  • You are correct. I misread conflated the configmap and secrets. – Derek Williams Nov 15 '21 at 19:56