简体   繁体   中英

passing json string in environment variable in Kubernetes deployment yaml

I am looking for something equivalent to SPRING_APPLICATION_JSON env variable of Docker Compose in Kubernetes Deployment yaml.

I am aware of that we can pass individual config as name-value pair. But there must be something through which all env variables can be passed in json or yaml format in Kubernetes.

You can use the following command:

kubectl create cm env --from-file=SPRING_APPLICATION_JSON=./<your-json>.json

You can do that using ConfigMap . For example, create a configmap:

kind: ConfigMap
apiVersion: v1
metadata:
  name: appconfig
data:
  ENV_KEY1: val1
  ENV_KEY2: val2

Then in your deployment container, use

spec:
  containers:
  - image: <image>
    name: <name>
    envFrom:
    - configMapRef:
        name: appconfig

You can do it through config maps, as shown above, or you can read in the environment variable value as a string and unmarshal it. To this, you'd have to make use of | -- a yaml operator which allows you to embed more "complicated" structures.

eg in your K8s deployment.yaml:

 ...
 env:
 - name: FOO
   value: |
   {"foo":"bar"}

then in your code

type v struct {
    Key string `json:"foo"`
}
    
func main() {
    foo := os.Getenv("FOO")
    var t v
    if err := json.Unmarshal([]bytes(foo), &t); err != nil {
        // log error
    }
    
    fmt.Println("Foo %s", t.Foo) // should print out "bar"
}

I'm not sure how well it looks like if you try to do this with yaml, but json objects can definitely be passed this way through the environment variable API in k8s. I'll leave it up to you to decide on the pros and cons of it. :)

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