String operation on env variables on Kubernetes

11/30/2016

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?

-- ab_tech_sp
kubernetes

2 Answers

12/1/2016

You can't do this directly.

You should run a startup script using the Pod ENV variables you have accessible to set any additional variable that you need, and launch your service after that in the startup script.

-- MrE
Source: StackOverflow

6/19/2017

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.

-- tom.poch
Source: StackOverflow