3

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.

Inian
  • 80,270
  • 14
  • 142
  • 161
jagatjyoti
  • 699
  • 3
  • 10
  • 29
  • `- myazstg1 myazstg2` is a single word or list of elements – Inian Oct 13 '22 at 05:24
  • What is the expected output for `"az-dev"`? – Inian Oct 13 '22 at 05:26
  • @Inian It is a list of elements. Better to have the output stored in an array. – jagatjyoti Oct 13 '22 at 05:28
  • Your current update, makes it look. like a single value split by a space. Format your YAML to make it look a YAML list of elements and do update the expected output for your input – Inian Oct 13 '22 at 05:29
  • Well I can but there's already lot of previous code using this file, hence can't be changed. It doesn't matter if it's a single value or list, I can do the manipulation of output. – jagatjyoti Oct 13 '22 at 05:33

1 Answers1

3

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.

Inian
  • 80,270
  • 14
  • 142
  • 161
  • I had read this earlier but I want to do this using native yq capabilities. – jagatjyoti Oct 13 '22 at 05:47
  • Not sure what you mean? Is the above solution not sufficient? – Inian Oct 13 '22 at 05:48
  • Not sure why I'm getting error although version is 4.x. ```$ var="az-dev" yq '.tenantlist[strenv(var)].tenants[]' config_kub_env.yaml Error: unknown command ".tenantlist[strenv(var)].tenants[]" for "yq" Run 'yq --help' for usage.``` Version: ```$ yq -V yq (https://github.com/mikefarah/yq/) version 4.16.2 ``` – jagatjyoti Oct 13 '22 at 05:55
  • 1
    Could you upgrade the yq version? to latest? the current one is https://github.com/mikefarah/yq/releases/tag/v4.28.1 The one you have is really old – Inian Oct 13 '22 at 05:57
  • Great, working fine now after updating to latest version. Thanks for the help. – jagatjyoti Oct 13 '22 at 06:26