'Ansible regex replace in variable to cisco interface names

I'm currently working with a script to create interface descriptions based on CDP neighbor info, but it's placing the full names e.g., GigabitEthernet1/1/1, HundredGigabitEthernet1/1/1.

My regex is weak, but I would like to do a regex replace to keep only the first 3 chars of the interface name.

I think a pattern like (dredGigatbitEthernet|abitEthernet|ntyGigabitEthernet|etc) should work, but not sure how to put that into the playbook line below to modify the port value

nxos_config:
  lines:
  - description {{ item.value[0].port }} ON {{ item.value[0].host }} 

E.g, I am looking for GigabitEthernet1/1/1 to end up as Gig1/1/1

Here is an example of input data:

{ 
  "FastEthernet1/1/1": [{
    "host": "hostname", 
    "port": "Port 1"  
  }] 
}

Final play to make it correct using ansible net neighbors as the source

Thank you - I updated my play, adjusted for ansible net neighbors

- name: Set Interface description based on CDP/LLDP discovery
  hosts: all
  gather_facts: yes
  connection: network_cli
  tasks:
    - debug:
        msg: "{{ ansible_facts.net_neighbors }}"
    - debug:
        msg: >- 
          description
          {{
            item[0].port 
            | regex_search('(.{3}).*([0-9]+\/[0-9]+\/[0-9]+)', '\1', '\2') 
            | join 
          }}
          ON {{ item.value[0].host }}"
      loop: "{{ ansible_facts.net_neighbors | dict2items }}"
      loop_control:
        label: "{{ item.key }}"


Thanks for the input!



Solution 1:[1]

Given that you want the three first characters along with the last 3 digits separated by a slash, then the regex (.{3}).*([0-9]+\/[0-9]+\/[0-9]+) should give you two capturing groups containing those two requirements.

In Ansible, you can use regex_search to extract those groups, then join them back, with the help on the join Jinja filter.

Given the playbook:

- hosts: localhost
  gather_facts: no

  tasks:
    - debug:
        msg: >- 
          description
          {{
            item.key 
            | regex_search('(.{3}).*([0-9]+\/[0-9]+\/[0-9]+)', '\1', '\2') 
            | join 
          }}
          ON {{ item.value[0].host }}"
      loop: "{{ interfaces | dict2items }}"
      loop_control:
        label: "{{ item.key }}"
      vars:
        interfaces:
          GigabitEthernet1/1/1:
            - port: Port 1 
              host: example.org
          HundredGigabitEthernet1/1/1:
            - port: Port 2
              host: example.com

This yields:

TASK [debug] ***************************************************************
ok: [localhost] => (item=eth0) => 
  msg: description Gig1/1/1 ON example.org"
ok: [localhost] => (item=eth1) => 
  msg: description Hun1/1/1 ON example.com"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1