【问题标题】:Convert vars from nested yaml structure to a list将 vars 从嵌套的 yaml 结构转换为列表
【发布时间】:2021-08-03 08:09:32
【问题描述】:

我有一个 yaml 配置文件,该文件在各种树分支中具有 watcher 字段和 routes 变量的级别。我想要得到的是一个列表,其中包含来自整个 routes 树的所有不同的 watcher 值。有没有人遇到过任何聪明的方法来解析这样一个 yaml 树?谢谢!

  routes:
  - match:
      watcher: w1
      job: monitoring
    receiver: w1_support
    group_by: ['alertname', 'severity', 'watcher']
    group_wait: 1m
    group_interval: 5m
    repeat_interval: 24h
    routes:
    - match:
        watcher: w1
      receiver: w1_support
      continue: true
    - match:
        watcher: w2
      receiver: w2_support
      continue: true
    - match:
        watcher: w3
      receiver: w3_support
      continue: true
    

最终我想使用目标公式而不是下面的watchers - 比如:

- key: GLOBAL_HDP_WATCHERS
    value: "{{ <<watchers>> | list | unique | join(',') }}"

所需输出:w1,w2,w3

【问题讨论】:

    标签: ansible yaml


    【解决方案1】:

    我不会在所有情况下都推荐以下方法。但是由于我们不知道你的结构可以有多深,并且 ansible 在递归浏览和树遍历方面不是那么好,所以我会直接处理文本数据。

    对于以下示例,我在控制器上创建了一个文件(这与您共享的内容相同,只是为了完整起见。):

    ext.yml

     routes:
     - match:
         watcher: w1
         job: monitoring
       receiver: w1_support
       group_by: ['alertname', 'severity', 'watcher']
       group_wait: 1m
       group_interval: 5m
       repeat_interval: 24h
       routes:
       - match:
           watcher: w1
         receiver: w1_support
         continue: true
       - match:
           watcher: w2
         receiver: w2_support
         continue: true
       - match:
           watcher: w3
         receiver: w3_support
         continue: true
    

    然后是剧本:

    - hosts: localhost
      gather_facts: false
    
      tasks:
          - vars:
              regex: >-
                  ^\s*watcher:\s*(\S*)$
            debug:
              msg: "{{ lookup('file', 'ext.yml').split('\n') | select('match', regex) 
               | map('regex_replace', regex, '\\g<1>') | unique | sort | join(',') }}"
    

    给予:

    PLAY [localhost] **************************************************************************************************************************************************************************************************
    
    TASK [debug] ******************************************************************************************************************************************************************************************************
    ok: [localhost] => {
        "msg": "w1,w2,w3"
    }
    
    PLAY RECAP ********************************************************************************************************************************************************************************************************
    localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多