<p>Is there a way to set the values of some keys in a Knative <code>service.yaml</code> file using environment variables?</p>
<hr />
<p><strong>More detail</strong></p>
<p>I am trying to deploy a Knative service to a Kubernetes cluster using GitLab CI. Some of the variables in my <code>service.yaml</code> file depend on the project and environment of the GitLab CI pipeline. Is there a way I can seamlessly plug those values into my <code>service.yaml</code> file without resorting to hacks like <code>sed -i ...</code>?</p>
<p>For example, given the following script, I want the <code>$(KUBE_NAMESPACE)</code>, <code>$(CI_ENVIRONMENT_SLUG)</code>, and <code>$(CI_PROJECT_PATH_SLUG)</code> values to be replaced by accordingly-named environment variables.</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: design
  namespace: &quot;$(KUBE_NAMESPACE)&quot;
spec:
  template:
    metadata:
      name: design-v1
      annotations:
        app.gitlab.com/env: &quot;$(CI_ENVIRONMENT_SLUG)&quot;
        app.gitlab.com/app: &quot;$(CI_PROJECT_PATH_SLUG)&quot;
    spec:
      containers:
        - name: user-container
          image: ...
      timeoutSeconds: 600
      containerConcurrency: 8
</code></pre>

<p>More than a Knative issue this is more of Kubernetes limitation. Kubernetes allows some expansion but not in annotations or namespace definitions. For example, you can do it in container env definitions:</p>
<pre class="lang-yaml prettyprint-override"><code>containers:
- env:
  - name: PODID
    valueFrom: ...
  - name: LOG_PATH
    value: /var/log/$(PODID)
</code></pre>
<p>If this is a CI/CD system like Gitlab the environment variables should be in a shell environment, so a simple shell expansion will do. For example.</p>
<pre class="lang-sh prettyprint-override"><code>#!/bin/bash

echo -e &quot;
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: design
  namespace: &quot;${KUBE_NAMESPACE}&quot;
spec:
  template:
    metadata:
      name: design-v1
      annotations:
        app.gitlab.com/env: &quot;${CI_ENVIRONMENT_SLUG}&quot;
        app.gitlab.com/app: &quot;${CI_PROJECT_PATH_SLUG}&quot;
    spec:
      containers:
        - name: user-container
          image: ...
      timeoutSeconds: 600
      containerConcurrency: 8
&quot; | kubectl apply -f -
</code></pre>
<p>You can also use <a href="https://www.gnu.org/software/gettext/manual/html_node/envsubst-Invocation.html" rel="nofollow noreferrer">envsubst</a> as a helper like mentioned in the other answer.</p>
