拉取MAC地址的值并添加“:”字符

Pulling the value of the MAC address and adding the ":" character

我有以下值:

    stdout_lines: [
        [
            "iso.3.6.1.2.1.17.4.3.1.1.0.80.121.102.104.4 \"00 50 79 66 68 04 \""
        ],
        [
            "iso.3.6.1.2.1.17.4.3.1.1.0.80.121.102.104.6 \"00 50 79 66 68 06 \""
        ],
        [
            "iso.3.6.1.2.1.17.4.3.1.1.0.80.121.102.104.8 \"00 50 79 66 68 08 \""
        ]
    ]

我想获取以下形式的 MAC 地址值:

00:50:79:66:68:04
00:50:79:66:68:06
00:50:79:66:68:08

这就是我想在我的剧本中做的事情:

        - set_fact:
            mac: "{{ stdout_lines|first|regex_replace(_regex, _replace)|trim }}"
          vars:
            _regex: '.*"(.*)"'
            _replace: ''

        - set_fact:
            matched: "{{ matched|d([]) + [item[2:]|join(':')] }}"
          with_items:
             - "{{ mac }}"

原来是一些废话。我做错了什么?

flatten 数据然后 map regex_replace and trim。例如

    - set_fact:
        mac: "{{ stdout_lines|
                 flatten|
                 map('regex_replace', _regex, _replace)|
                 map('trim')|
                 map('split')|
                 map('join', ':')|
                 list }}"
      vars:
        _regex: '.*"(.*)"'
        _replace: ''

给予

mac:
  - 00:50:79:66:68:04
  - 00:50:79:66:68:06
  - 00:50:79:66:68:08

试试这个剧本:flatten 列表,用 regex_searchtrimreplace 捕获字符串的右侧部分 space by :

- name: "make this working"
  hosts: localhost
  vars:
    mac: 
      - - iso.3.6.1.2.1.17.4.3.1.1.0.80.121.102.104.4 "00 50 79 66 68 04 "
      - - iso.3.6.1.2.1.17.4.3.1.1.0.80.121.102.104.6 "00 50 79 66 68 06 "
      - - iso.3.6.1.2.1.17.4.3.1.1.0.80.121.102.104.8 "00 50 79 66 68 08 "
  
  tasks:
    - set_fact:
        result: "{{ result | d([]) + [reg] }}"
      loop: "{{ mac | flatten }}"
      vars:
        reg: "{{ item | regex_search('(\d\d ){6}') | trim | replace(' ',':')}}"
    
    - debug:
        var: result

结果:

ok: [localhost] => {
    "result": [
        "00:50:79:66:68:04",
        "00:50:79:66:68:06",
        "00:50:79:66:68:08"
    ]
}