Home > Software engineering >  How to override Go environment variables with Helm
How to override Go environment variables with Helm

Time:09-09

How do I override environment variables in a .env file for Go with Helm?

With C# I do the following:

In appsettings.json:

{
    "Animals":{
        "Pig": "Squeek"
    },
}

In values.yaml:

animals:
  pig: "Oink"

In configmap.yaml:

apiVersion: v1
kind: ConfigMap
metadata:
  name: animal-configmap
pig: {{ .Values.animals.pig }}

And finally in deployment.yaml:

spec:
  ...
  template:
    ...
    spec:
      ...
      containers:
          ...
          env:
            - name: Animals__Pig
              valueFrom:
                configMapKeyRef:
                  name: animal-configmap  
                  key: pig

Not the double __. How would one go about updating an environment value for Go?

Here is the Go .env file example:

PIG=SQUEEK

CodePudding user response:

If your Go code is retrieving an ordinary environment variable

pig := os.Getenv("PIG")

then the Kubernetes manifest should use that name as the environment variable name:

env:
  - name: PIG
    valueFrom: {...}

The double-underscore doesn't have any special meaning in Unix environment variables or the Kubernetes manifest, in your initial example it looks like the way the C# framework separates components when it maps environment variables to application properties. If you're using environment variables directly you don't need to do anything special.

CodePudding user response:

You can use the "github.com/joho/godotenv" package to read .env files. Since you don't want to mix up existing environment variables with those from the .env file, you can create a map and set the vars to it.

If you have a .env file like this:

HELLO=word

You can read it like this:

package main

import (
    "fmt"
    "log"

    "github.com/joho/godotenv"
)

func main() {
    var envs map[string]string
    envs, err := godotenv.Read(".env")

    if err != nil {
        panic("Error loading .env file")
    }

    name := envs["HELLO"]

    fmt.Println(name)
}

If you set a var env, you can still access the value defined on the file:

$ HELLO=ping go run main.go

world

Then you access the file vars from the envs var.

  • Related