Home > OS >  Pulling the value of the MAC address and adding the ":" character
Pulling the value of the MAC address and adding the ":" character

Time:02-24

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?

CodePudding user response:

try this playbook:

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

CodePudding user response:

flatten the data then map regex_replace and trim. For example

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

gives

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