【问题标题】:Ansible regex replace in variable to cisco interface namesAnsible 正则表达式将变量替换为 cisco 接口名称
【发布时间】:2022-01-23 22:40:20
【问题描述】:

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

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

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

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

例如,我正在寻找 GigabitEthernet1/1/1 以结束 Gig1/1/1

【问题讨论】:

  • 不完全清楚你的输出应该是什么?然后GigabitEthernet1/1/1 应该以Gig 的第3 个字符结尾,还是应该是1/1/1?还是1/1
  • 抱歉,查找 GigabitEthernet1/1/1 为 Gig1/1/1

标签: ansible network-programming


【解决方案1】:

鉴于您希望前三个字符以及最后 3 个数字用斜杠分隔,那么正则表达式 (.{3}).*([0-9]+\/[0-9]+\/[0-9]+) 应该为您提供两个包含这两个要求的捕获组。

在 Ansible 中,您可以使用 regex_search 提取这些组,然后在 join Jinja filter 的帮助下将它们加入。

鉴于剧本:

- hosts: localhost
  gather_facts: no

  tasks:
    - debug:
        msg: >- 
          description
          {{
            item.value[0].port 
            | 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:
          eth0:
            - port: GigabitEthernet1/1/1
              host: example.org
          eth1:
            - port: HundredGigabitEthernet1/1/1
              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"

【讨论】:

    猜你喜欢
    • 2019-11-11
    • 2012-08-26
    • 1970-01-01
    • 2021-06-12
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    相关资源
    最近更新 更多