Search code examples
yamlyq

Update array value in yq on base of criteria


I have sample yaml like below

scrape_configs:
- job_name: 'snmp-moxa'
  static_configs:
  - targets:
- job_name: prometheus
  static_configs:
  - targets:
    - localhost:9090

I want to add IP address where job_name is equal to 'snmp-moxa', I tried following but none working

To verify it reaches at correct path

# yq eval '.scrape_configs[] | select(.job_name == "snmp-moxa") | .static_configs' prom.yaml
- targets:

Following are two tries to update values

#yq eval -i '.scrape_configs[] | select(.job_name == "snmp-moxa") | .static_configs.targets |= . + ["10.11.158.177"]' prom.yaml
Error: Cannot index array with 'targets' (strconv.ParseInt: parsing "targets": invalid syntax)


# yq eval -i '.scrape_configs[] | select(.job_name == "snmp-moxa") | .static_configs.targets |= . + [10.11.158.177]' prom.yaml
Error: expected end of expression but found '|', please check expression syntax

Resulting yaml should be like

scrape_configs:
- job_name: 'snmp-moxa'
  static_configs:
  - targets: 10.11.158.177  
or
  - targets: 
    - 10.11.158.177 
- job_name: prometheus
  static_configs:
  - targets:
    - localhost:9090

Solution

  • Your idea is almost right, but the static_configs record is an array type and not a scalar type. So you need to access the sub-fields inside it, with the [] notation, i.e.

    You probably need the targets as an array so use the += to append the array content (tested on yq version 4.13.5)

    yq e '(.scrape_configs[] | select(.job_name == "snmp-moxa").static_configs[].targets) += [ "10.11.158.177" ]' yaml