Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tony-sol/d770290e2f439feea05a86ca2d9cd318 to your computer and use it in GitHub Desktop.
Save tony-sol/d770290e2f439feea05a86ca2d9cd318 to your computer and use it in GitHub Desktop.
How to convert yaml config file to envs for go app with cobra config parser

#tools/yq

Install yq for handy work with yaml

Convert yaml to env

 yml2env() {
	 yq --unwrapScalar=false --output-format=props "${1:-.} | (.. | select((tag == \"\!\!map\" or tag == \"\!\!seq\") and length == 0)) = \"\" | ... comments=\"\"" | awk '{gsub(/\./,"_",$1)} {$1=toupper($1);print}' | sed 's/ = /=/g'
}

Usage

cat my.yaml
rpc:
  proxy:
    network: "unix"
    unix:
      dir: "/var/run/engine"
      group: "${USER}"

cat my.yaml | yml2env
RPC_PROXY_NETWORK="unix"
RPC_PROXY_UNIX_DIR="/var/run/engine"
RPC_PROXY_UNIX_GROUP="${USER}"

cat my.yaml | yml2env '.rpc.proxy.unix'
DIR=/var/run/engine
GROUP=${USER}

Limitations:

  • due to yq output format is properties, so it cannot merge lists into a string but append index, like 0, 1, .., N in a last level with single value under these index
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment