根据条件更新 yq 中的数组值

Imr*_*han 1 yaml yq

我有如下示例 yaml

scrape_configs:
- job_name: 'snmp-moxa'
  static_configs:
  - targets:
- job_name: prometheus
  static_configs:
  - targets:
    - localhost:9090
Run Code Online (Sandbox Code Playgroud)

我想添加 IP 地址,其中 job_name 等于“snmp-moxa”,我尝试了以下操作,但没有成功

验证它到达正确的路径

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

以下是更新值的两次尝试

#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
Run Code Online (Sandbox Code Playgroud)

结果 yaml 应该是这样的

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
Run Code Online (Sandbox Code Playgroud)

Ini*_*ian 5

你的想法几乎是正确的,但是static_configs记录是数组类型而不是标量类型。因此,您需要使用符号访问其中的子字段[],即

您可能需要作为targets数组,因此使用+=来附加数组内容(在 yq 版本 4.13.5 上测试)

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