Concatenating Kubernetes secrets for environment variables

Joe Blogs

When deploying a pod in Kubernetes, environment variables can be set a number of ways including using ConfigMaps and Secrets. There are times when an environment variable is needed that is a concatenation of several secret values. You could solve this by creating a new Secret and duplicating the values, however, doing this means you have replication, and the potential of having to remember to update multiple places if the secret changes. This article is going to explain you how this can be achieved by concatenating Secret values to produce a connection string for Azure SQL.

Assuming you have an existing Opaque Secret already created called concatenate-demo-secret, and it has keys for dbowner, password, databasename and the sqlservername, these values can be combined using the below example when creating a Pod:

apiVersion: v1
kind: Pod
metadata:
  name: secret-env-pod
spec:
  containers:
  - name: mycontainer
    image: redis
    env:
      - name: DB_OWNER
        valueFrom:
          secretKeyRef:
            name: concatenate-demo-secret
            key: dbowner
      - name: DB_PASSWORD
        valueFrom:
          secretKeyRef:
            name: concatenate-demo-secret
            key: password
      - name: DB_AZURESQLDB
        valueFrom:
          secretKeyRef:
            name: concatenate-demo-secret
            key: azuresqldb
      - name: DB_AZURESQLSERVER
        valueFrom:
          secretKeyRef:
            name: concatenate-demo-secret
            key: sqlservername
      - name: ConnectionStrings__NameOfConnectionString
        value: Server=tcp:$(DB_AZURESQLSERVER),1433;Initial Catalog=$(DB_AZURESQLDB);Persist Security Info=False;User ID=$(DB_OWNER);Password=$(DB_PASSWORD);MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
  restartPolicy: Never

As you can see from the above, the last environment variable, ConnectionStrings__NameOfConnectionString uses the previously defined variables and concatenates them to define the connection string value.

The above can be tested by deploying the Pod, exec into the container, and then running “echo $ConnectionStrings__NameOfConnectionString“.

The above approach is not 100% ideal as this will need to be repeated for any other Pod definition that needs to use the same connection string, therefore, if there are any other better solutions, please feel free to leave a comment.