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

Viewed 80

I have the following value:

    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 \""
        ]
    ]

I want to get the MAC address values in the following form:

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

That's what I'm trying to do in my playbook:

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

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

It turns out some nonsense. What am I doing wrong?

2 Answers

flatten the data then map regex_replace and trim. For example

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

gives

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

try this playbook: flatten the list, trap the right part of string with regex_search, trim and replace the 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

result:

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