How to add environment variables in Kubernetes config file? How to add environment variables in Kubernetes config file? kubernetes kubernetes

How to add environment variables in Kubernetes config file?


Thanks Markus for the hint link.

I am writing the answer in Go as the original link showed how to do it from command line. The steps are as follows:

  • Replace the fields to be modified in the file with something of the form ${X}. In my case e.g. I replaced my-token with ${my-token} and so on.
  • Here you can set X as an environment variable so that your code can access it during runtime. e.g. by doing export X="abcd" in command line.
  • Say the file name is config.
  • Execute the following code:
package mainimport (    "os"    "os/exec")func main() {    mytoken := os.Getenv("mytoken")    part := fmt.Sprintf("s/${mytoken}/%s/g", mytoken)    command := exec.Command("sed", "-i", "", "-e", part, "config")    command.Run()}

This will do the required replacement during runtime.