Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String operation on env variables on Kubernetes

Tags:

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?

like image 411
ab_tech_sp Avatar asked Nov 30 '16 13:11

ab_tech_sp


People also ask

Are env variables strings?

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.

Are all env variables strings?

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.

How do I use env files in Kubernetes?

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.

How does Kubernetes define environment variables?

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.


1 Answers

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.

like image 193
Tomáš Poch Avatar answered Oct 22 '22 09:10

Tomáš Poch