简体   繁体   中英

How to override Go environment variables with Helm

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM