【问题标题】:Update array value in yq on base of criteria根据条件更新 yq 中的数组值
【发布时间】:2021-10-25 20:40:32
【问题描述】:

我有如下示例 yaml

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

我想添加job_name等于'snmp-moxa'的IP地址,我尝试了以下但没有工作

验证它到达正确的路径

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

以下是两次更新值的尝试

#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

生成的 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

【问题讨论】:

    标签: yaml yq


    【解决方案1】:

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

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

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

    【讨论】:

    • 非常感谢,此类提示的文档缺失!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多