I have a question regarding Kubernetes YAML string operations.
I need to set an env variable based on the hostname of the container that is deployed and append a port number to this variable.
env:
- name: MY_POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
How do I create another env variable that uses MY_POD_NAME and makes it look like this uri://$MY_POD_NAME:9099/
This has to be defined as an env variable. Are there string operations allowed in Kubernetes YAML files?
The value of an environment variable is a string of characters. For a C-language program, an array of strings called the environment shall be made available when a process begins.
The one notable difference with the process. env object, is that every key and value will always be a string. This is because environment variables themselves can only ever be strings.
There are two ways to define environment variables with Kubernetes: by setting them directly in a configuration file, from an external configuration file, using variables, or a secrets file. This tutorial shows both options, and uses the Humanitec getting started application used in previous tutorials.
To set environment variables, include the env or envFrom field in the configuration file. Note: The environment variables set using the env or envFrom field override any environment variables specified in the container image. Note: Environment variables may reference each other, however ordering is important.
You can do something like
- name: MY_POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: MY_POD_URI
value: "uri://$(MY_POD_NAME):9099/"
We are using that since K8s 1.4
$()
is processed by k8s itself, does not work everywhere, but works for env variables.
If your container contains bash, you can also leverage bash variable expansion
"command": ["/bin/bash"],
"args": [ "-c",
"MY_POD_URI_BASH=uri://${MY_POD_NAME}:9099/ originalEntryPoint.sh
],
${}
is not touched by k8s, but evaluated later in container by bash. If you have a chance, prefer the first option with $()
note: order matters in declaration. In example above, if MY_POD_NAME
is defined later in env array, the expansion will not work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With