Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically fetch values using env variable from yaml file using yq

Tags:

yaml

yq

I'm trying to get the values of tenants in below yaml file using yq. The intent is to dynamically fetch the value depending on env variable.

Let's assume there's an env variable var="az-dev", then tenants of az-dev should be retrieved.

I have given some tries as mentioned below but no luck.

YAML file

tenantlist:
  az-dev:
    tenants:
      - myazdev
  az-stage:
    tenants:
      - myazstg1 myazstg2
  aw-dev:
    tenants:
      - myawdev1 myawdev2
  aw-stage:
    tenants:
      - myawstg1 myawstg2

Tries:

var="az-dev" yq e '.tenantlist | select(. == env(var))' file.txt 

var=az-dev; yq '.tenantlist |= strenv(var) has("az-dev")' file.txt

Any help would be appreciated. TIA.

like image 603
jagatjyoti Avatar asked Apr 21 '26 11:04

jagatjyoti


1 Answers

With mikefarah/yq, you can simply index the required key name by [..] and get the corresponding tenants list

var="az-dev"  yq '.tenantlist[strenv(var)].tenants[]' yaml

Or just pick the keys of interest from the map (available since v4.22.1)

var="az-dev"  yq '.tenantlist | pick([strenv(var)]) | .[].tenants[]' yaml

Note: Since 4.18.1, yq's eval/e command is the default command and no longer needs to be specified.

like image 182
Inian Avatar answered Apr 24 '26 11:04

Inian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!