Ansible正则表达式将变量中的正则表达式替换为cisco接口名称



我目前正在使用一个基于CDP邻居信息创建接口描述的脚本,但它会放置全名,例如GigabitEthernet1/1/1HundredGigabitEthernet1/1/1

我的正则表达式很弱,但我想做一个正则表达式替换,只保留接口名称的前3个字符。

我认为像(dredGigatbitEthernet|abitEthernet|ntyGigabitEthernet|etc)这样的模式应该有效,但不确定如何将其放入下面的剧本行中以修改端口值

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

例如,我正在寻找最终成为Gig1/1/1GigabitEthernet1/1/1

以下是输入数据的示例:

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

最终播放,使用易解析的网络邻居作为源使其正确

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

感谢您的投入!

假设您希望前三个字符和最后三个数字由斜杠分隔,那么regex(.{3}).*([0-9]+/[0-9]+/[0-9]+)应该为您提供两个包含这两个要求的捕获组。

在Ansible中,您可以使用regex_search提取这些组,然后在joinJinja筛选器的帮助下将它们重新加入。

给出剧本:

- 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

这产生:

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"

最新更新