Can environment variables passed to containers be composed from environment variables that already exist? Something like:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.14.2
ports:
- containerPort: 80
env:
- name: URL
value: $(HOST):$(PORT)
3
Answers
These manifests are complete files. Not a good way to use variables in it. Though you can.
use the below command to replace and pipe it to kubectl.
Though I would suggest to use Helm.
Read more:
https://kubernetes.io/docs/tasks/inject-data-application/define-environment-variable-container/
Helm with it’s variables seems like a better way of handling that kind use cases.
In the example below you have a deployment snippet with values and variables:
And here is one of the ways of deploying it with some custom variables:
Helm allows you also to use template functions. You can have
default
functions and this will go to default values if they’re not filled. In the example above you can seerequired
which display the message and fails to go further with installing the chart if you won’t specify the value. There is alsoinclude
function that allows you to bring in another template and pass results to other template functions.Within a single Pod spec, this works with exactly the syntax you described, but the environment variables must be defined (earlier) in the same Pod spec. See Define Dependent Environment Variables in the Kubernetes documentation.
Beyond this, a Kubernetes YAML file needs to be totally standalone, and you can’t use environment variables on the system running
kubectl
to affect the file content. Other tooling like Helm fills this need better; see @thomas’s answer for an example.