如何在ansible中提取stdout.lines的输出

How to extract the output from stdout.lines in ansible

---
- name: Mikrotik info
  hosts: mikrotik
  connection: network_cli
  remote_user: root
  gather_facts: false
  tasks:
  - name: show info
    routeros_command:
     commands: /system routerboard print
    register: rb_info

  - name: Debug info
    debug:
      msg: "{{ rb_info.stdout_lines }}"

输出:

 routerboard: yes
             model: 751G-2HnD
     serial-number: 3A6502B2A2E7
     firmware-type: ar7240
  factory-firmware: 3.0
  current-firmware: 6.42.3
  upgrade-firmware: 6.43.4

我需要为 "upgrade-firmware" 字符串过滤它并得到如下输出:

upgrade-firmware: 6.43.4

我应该使用 regex_replace?或者我可以使用 grep 或类似的东西?

非常感谢任何想法。

谢谢

(更新)

使用from_yaml合并字典。例如

    - set_fact:
        minfo: "{{ minfo|default({})|combine(item|from_yaml) }}"
      loop: "{{ rb_info.stdout_lines }}"
    - debug:
        var: minfo['upgrade-firmware']

给予

  minfo['upgrade-firmware']: 6.43.4

(备案)

  1. 稳健的解决方案是将数据写入模板include_vars。下面的任务
    - tempfile:
      register: tempfile
    - template:
        src: minfo.j2
        dest: "{{ tempfile.path }}"
    - include_vars:
        file: "{{ tempfile.path }}"
        name: minfo
    - debug:
        var: minfo

使用模板

    shell> cat minfo.j2 
    {% for item in rb_info.stdout_lines %}
    {{ item }}
    {% endfor %}

应该给

    "minfo": {
        "current-firmware": "6.42.3", 
        "factory-firmware": 3.0, 
        "firmware-type": "ar7240", 
        "model": "751G-2HnD", 
        "routerboard": true, 
        "serial-number": "3A6502B2A2E7", 
        "upgrade-firmware": "6.43.4"
    }
  1. 下面的任务创建变量 upgrade_firmware
    - set_fact:
        upgrade_firmware: "{{ item.split(':').1|trim }}"
      loop: "{{ rb_info.stdout_lines|map('quote')|map('trim')|list }}"
      when: item is search('^upgrade-firmware')
    - debug:
        var: upgrade_firmware
  1. 可以将所有的参数都放入字典
    - set_fact:
        minfo: "{{ minfo|default({})|
                   combine({item.split(':').0: item.split(':').1|trim}) }}"
      loop: "{{ rb_info.stdout_lines|map('quote')|map('trim')|list }}"
    - debug:
        var: minfo['upgrade-firmware']