<p>My k8s namespace contains a <code>Secret</code> which is created at deployment time (by <code>svcat</code>), so the values are not known in advance.</p>

<pre><code>apiVersion: v1
kind: Secret
type: Opaque
metadata:
  name: my-database-credentials
data:
  hostname: ...
  port: ...
  database: ...
  username: ...
  password: ...
</code></pre>

<p>A <code>Deployment</code> needs to inject these values in a slightly different format:</p>

<pre><code>...

containers:
  env:
  - name: DATABASE_URL
    valueFrom:
      secretKeyRef:
        name: my-database-credentials
        key: jdbc:postgresql:&lt;hostname&gt;:&lt;port&gt;/&lt;database&gt; // ??

  - name: DATABASE_USERNAME
    valueFrom:
      secretKeyRef:
        name: my-database-credentials
        key: username

  - name: DATABASE_PASSWORD
    valueFrom:
      secretKeyRef:
        name: my-database-credentials
        key: password
</code></pre>

<p>The <code>DATABASE_URL</code> needs to be composed out of the <code>hostname</code>, <code>port</code>, 'database` from the previously defined secret.</p>

<p>Is there any way to do this composition? </p>

metacubed
<p>Kubernetes allows you to use previously defined environment variables as part of subsequent environment variables elsewhere in the configuration. From the <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.21/#envvar-v1-core" rel="noreferrer">Kubernetes API reference docs</a>:</p>
<blockquote>
<p>Variable references $(VAR_NAME) are expanded using the previous defined environment variables in the container and any service environment variables.</p>
</blockquote>
<p>This <code>$(...)</code> syntax defines <a href="https://kubernetes.io/docs/tasks/inject-data-application/define-interdependent-environment-variables/" rel="noreferrer">interdependent environment variables</a> for the container.</p>
<p>So, you can first extract the required secret values into environment variables, and then compose the <code>DATABASE_URL</code> with those variables.</p>
<pre class="lang-yaml prettyprint-override"><code>...

containers:
  env:
  - name: DB_URL_HOSTNAME               // part 1
    valueFrom:
      secretKeyRef:
        name: my-database-credentials
        key: hostname

  - name: DB_URL_PORT                   // part 2
    valueFrom:
      secretKeyRef:
        name: my-database-credentials
        key: port

  - name: DB_URL_DBNAME                 // part 3
    valueFrom:
      secretKeyRef:
        name: my-database-credentials
        key: database

  - name: DATABASE_URL                  // combine
    value: jdbc:postgresql:$(DB_URL_HOSTNAME):$(DB_URL_PORT)/$(DB_URL_DBNAME)

...
</code></pre>
