Search code examples
yamlyq

Convert yaml config file to environment variables


Given yaml config file that looks like this:

key1:
   key11:value1
   key12:value2
key2:
   key21:value3

How can I convert it in a bash script (preferable with yq) to env vars prefixed with a string? Desired output for env:

TF_VAR_key11=value1
TF_VAR_key12=value2
TF_VAR_key21=value3

Solution

  • Assuming the missing spaces in the input's subelements between key and value are intentional, so we are just dealing with an array of string values containing :, and separated by whitespace.

    yq '.[] | split(" ") | .[] | split(":") | "TF_VAR_" + .[0] + "=" + .[1]' file.yaml
    

    Which implementation of yq are you using? This works for mikefarah/yq. To be used with kislyuk/yq, add the -r option.