【问题标题】:YQ 4.7.0 - How to traverse each array elements and update valueYQ 4.7.0 - 如何遍历每个数组元素并更新值
【发布时间】:2021-08-09 17:09:49
【问题描述】:

我有一个 yaml:

global:
  resolve_timeout: 5m
receivers:
- name: alerts-null
- name: default
  local_configs:
  - api_url: https://abx.com
    channel: '#abx'
    send_resolved: true      
    username: abc-123
- name: devops-alerts
  local_configs:
  - api_url: https://abx.com
    channel: '#abx'
    send_resolved: true      
    username: abc-123

yaml 可以在数组中有多个“name:”元素,我想循环所有“name”元素并将键“username:”的值更改为“xyz-321”。生成的 YAML 应如下所示:

global:
  resolve_timeout: 5m
receivers:
- name: alerts-null
- name: default
  local_configs:
  - api_url: https://abx.com
    channel: '#abx'
    send_resolved: true      
    username: xyz-321
- name: devops-alerts
  local_configs:
  - api_url: https://abx.com
    channel: '#abx'
    send_resolved: true      
    username: xyz-321

我尝试使用以下 yq 命令,但它没有更改所需键的值:

yq eval '(.receivers[] | select(.name.local_configs.username)) = "xyz-321"' source.yaml > manipulated.yaml

感谢任何指针。

【问题讨论】:

  • 为什么internal_config: 是空的?您的输入甚至不是有效的 YAML。考虑先在yamllint.com中验证它

标签: yaml yq


【解决方案1】:

如果您将索引更改为如下所示:

global:
  resolve_timeout: 5m
receivers:
- name: alerts-null
  internal_config:
    username: abc-123
- name: default
  internal_config:
    username: abc-123

然后流动将起作用:

yq e '(.receivers[].internal_config.username) |= "new_username"' myFile.yaml

【讨论】:

    猜你喜欢
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2017-04-19
    相关资源
    最近更新 更多