Home > Software engineering >  convert yaml to environment variable by selecting a KEY
convert yaml to environment variable by selecting a KEY

Time:09-28

I have a config file:

name: test
configmap:
  foo1: bar1
  foo2: bar2
secrets:
  secrets1: value1

whatever comes under configmap should be converted to ENV Variables. Like in above example, only 2 values will be converted to ENV variables:

export foo1=bar1
export foo2=bar2

I followed this https://unix.stackexchange.com/questions/539009/export-environment-variables-parsed-from-yaml-text-file but could not get it working.

CodePudding user response:

You can use a tool like to create an output like:

key1=value1 key2=value2

Passing that to export will create the env vars.


export $(yq e '.configmap | to_entries | map(.key   "="   .value) | join(" ")' input)

Local shell example, were your input is stored in a file called input:

$ echo $foo1 $foo2

$
$ export $(yq e '.configmap | to_entries | map(.key   "="   .value) | join(" ")' input)
$
$ echo $foo1 $foo2
bar1 bar2
$

CodePudding user response:

Using awk:

While I would recommend using a proper YAML parser as in the answer by @OstoneO, you could use awk to accomplish this task:

$ unset foo1; unset foo2 
$ export $(awk -F": " '/configmap:/{f=1} {if(f && NF==2) {printf "export %s=%s ", $1, $2}} /secrets:/{f=0}' test.yaml); 
$ echo $foo1 $foo2
bar1 bar2
  • Related