Multi-Vendor Network Automation with Ansible and Jinja2 - 夜莺博客

Multi-Vendor Network Automation with Ansible and Jinja2

Managing a mixed network by hand means logging into three different CLIs for every change — and every missed commit or forgotten write memory is an outage waiting to happen. Ansible solves this with an abstraction layer: you define the desired state once, and vendor-specific modules render it correctly for each platform. This practical guide, based on a real multi-vendor rollout managing Juniper MX routers, Cisco Catalyst switches, and MikroTik routers, shows the exact inventory, Jinja2 templates, and playbook structure that makes one codebase drive every vendor, plus the lessons learned in production.

1. Defining a Multi-Vendor Inventory

Set ansible_network_os per host so Ansible loads the correct module set and connection type (network_cli for Cisco, netconf for Juniper):

[campus_switches]
sw-cisco-01 ansible_host=10.0.1.10 ansible_network_os=cisco.ios.ios
sw-juniper-01 ansible_host=10.0.1.20 ansible_network_os=junipernetworks.junos.junos
sw-mikrotik-01 ansible_host=10.0.1.30 ansible_network_os=community.general.routeros

2. Abstracting Configs with Jinja2 Templates

Define the data once in group_vars, then map it to each vendor's syntax:

# group_vars/all.yml
system_banner: "Authorized Access Only. All activities are logged."
# templates/cisco_ios.j2
banner motd ^
{{ system_banner }}
^
# templates/juniper_junos.j2
set system login message "{{ system_banner }}"

3. The Playbook: Idempotent Vendor-Specific Modules

- name: Deploy Multi-Vendor System Config
  hosts: campus_switches
  gather_facts: false
  tasks:
    - name: Push Cisco Configuration
      cisco.ios.ios_config:
        src: templates/cisco_ios.j2
      when: ansible_network_os == 'cisco.ios.ios'

    - name: Push Juniper Configuration
      junipernetworks.junos.junos_config:
        load: merge
        src: templates/juniper_junos.j2
      when: ansible_network_os == 'junipernetworks.junos.junos'

The config modules are idempotent — they compare current state and only push what changed, so re-running the playbook is safe.

Hard-Won Lessons from Production

  • Trust but verify with check_mode: run with --check first to see the diff before touching production.
  • Disable gather_facts unless you need serial numbers — it cut execution time by ~40%.
  • Encrypt secrets with ansible-vault; never store SSH passwords or SNMP strings in plain text.
  • Standardize naming: interface names like GigabitEthernet0/1 vs ge-0/0/0 turn Jinja2 logic into nested if-statements.

With this workflow, changes go through Git pull requests and CI/CD, creating a full audit trail. For more automation ideas, see our NVIDIA Air + Ansible design automation article, the ArubaOS-CX REST API automation guide, and the multi-vendor CLI cheat sheet for the manual fallback.

原文链接:https://itnotes.dev/multi-vendor-network-automation-a-practical-guide-to-ansible-and-jinja2/