如何在Ansible中基于两个字典列表生成Cisco ASA路由命令?
如何用Ansible基于VRF匹配生成Cisco ASA路由命令
要实现按VRF属性匹配生成目标路由命令,核心思路是先构建VRF到接口、网关的映射表,再遍历子网列表拼接命令。以下是具体实现步骤和完整Playbook:
实现步骤
- 构建VRF映射表:将
dict1中的数据转换成以VRF名称为键的字典,方便后续快速查找对应接口名称和网关。 - 生成路由命令:遍历
dict2中的子网条目,结合映射表中的信息,拼接出符合Cisco ASA格式的路由命令。 - (可选)推送配置到设备:使用Ansible的Cisco ASA模块将生成的命令部署到目标设备。
完整Playbook示例
--- - name: 生成并配置Cisco ASA路由 hosts: asa_devices vars: dict1: - name: Interface_LAN vrf: LAN gw: 10.10.10.1 vlan: 10 - name: Interface_DMZ vrf: DMZ gw: 10.20.20.1 vlan: 20 dict2: - name: LAN vrf: LAN subnet: 192.168.100.0 - name: LAN2 vrf: LAN subnet: 192.168.200.0 - name: DMZ vrf: DMZ subnet: 192.168.300.0 tasks: - name: 构建VRF到接口、网关的映射 set_fact: vrf_to_intf_gw: >- {%- set map = {} -%} {%- for intf in dict1 -%} {%- set _ = map.__setitem__(intf.vrf, {'intf_name': intf.name, 'gw': intf.gw}) -%} {%- endfor -%} {{ map }} - name: 生成路由命令列表 set_fact: asa_route_commands: >- {%- set cmds = [] -%} {%- for subnet in dict2 -%} {%- set cmd = "route " ~ vrf_to_intf_gw[subnet.vrf].intf_name ~ " " ~ subnet.subnet ~ " 255.255.255.0 " ~ vrf_to_intf_gw[subnet.vrf].gw ~ " 1" -%} {%- set _ = cmds.append(cmd) -%} {%- endfor -%} {{ cmds }} - name: 查看生成的路由命令 debug: var: asa_route_commands - name: 部署路由配置到ASA cisco.asa.asa_config: lines: "{{ item }}" before: "no route {{ item.split(' ')[1] }} {{ item.split(' ')[2] }} {{ item.split(' ')[3] }} {{ item.split(' ')[4] }}" match: exact loop: "{{ asa_route_commands }}"
关键说明
- VRF映射表:通过Jinja2模板循环
dict1,手动构建键为VRF名称、值为接口和网关信息的字典,确保后续匹配效率。 - 命令拼接:固定使用
255.255.255.0作为子网掩码、1作为管理距离,若需调整可直接修改模板中的对应字段。 - 设备部署:使用
cisco.asa.asa_config模块时,before参数用于先清除同条目旧路由,避免配置冲突;match: exact保证最终配置与生成命令完全一致。
内容的提问来源于stack exchange,提问作者mosesiamnot
相关产品推荐
相关产品推荐

