Ansible for Network Automation: Best Practices for Cisco and Juniper

You are currently viewing Ansible for Network Automation: Best Practices for Cisco and Juniper

Ansible for Network Automation: Best Practices for Cisco and Juniper

Image by: Brett Sayles

The multi-vendor network automation imperative

Did you know 65% of enterprises operate networks with three or more vendors? Yet 78% of network teams still configure devices manually, according to Gartner’s research. This guide delivers a technical blueprint for using Ansible network automation to conquer complex environments mixing Cisco IOS-XE, Juniper Junos, Fortinet FortiOS, and other platforms. You’ll learn to replace error-prone manual processes with scalable automation workflows that maintain consistency while reducing deployment times from hours to minutes. We’ll cover dynamic inventory construction, Jinja2 templating magic, and firewall policy management across your entire infrastructure.

Ansible foundations for network engineers

Unlike traditional scripting, Ansible operates agentlessly using SSH or API connections, making it ideal for network devices. Core components include:

  • Playbooks: YAML files defining automation workflows
  • Modules: Vendor-specific commands (e.g., cisco.ios.ios_config, junipernetworks.junos.junos_config)
  • Inventory: Dynamic device databases

Installation requires only Python and the ansible-core package. Network-specific collections are installed via Ansible Galaxy:

ansible-galaxy collection install cisco.ios junipernetworks.junos fortinet.fortios

Critical security note: Always use Ansible Vault for credential management when automating network devices. Store sensitive data in encrypted files rather than plain-text playbooks.

Building intelligent dynamic inventories

Static inventories fail in multi-vendor environments. Dynamic inventories pull real-time device data from sources like:

  • CMDB systems (ServiceNow, NetBox)
  • Cloud providers (AWS VPC, Azure Network)
  • IPAM tools (Infoblox, phpIPAM)

Create a Python script that returns JSON structured for Ansible. This example filters Cisco ASR devices:

#!/usr/bin/python
# Custom inventory for network devices
def main():
    return {
        "cisco_asr": {
            "hosts": ["asr1.example.com", "asr2.example.com"],
            "vars": {"ansible_network_os": "cisco.ios.ios"}
        }
    }

Enable vendor-specific parameters using host variables:

Vendor ansible_connection ansible_network_os
Cisco IOS ansible.netcommon.network_cli cisco.ios.ios
Juniper Junos ansible.netcommon.network_cli junipernetworks.junos.junos
Fortinet FortiOS ansible.netcommon.httpapi fortinet.fortios.fortios

Pro tip: Use group variables to apply standardized timeouts and retry policies across all devices.

Jinja2 templates for configuration consistency

Jinja2 enables “configuration-as-code” with dynamic variables. Consider this interface template:

interface {{ interface_name }}
 description {{ description | default('ANSIBLE-CONFIGURED') }}
 ip address {{ ip_address }}/{{ subnet }}
{% if vlan is defined %}
 switchport access vlan {{ vlan }}
{% endif %}

Deploy vendor-neutral configurations using roles:

  1. Define device variables in group_vars/all.yml
  2. Create template directories per vendor (templates/cisco/, templates/juniper/)
  3. Use conditional logic in playbooks:
- name: Apply interface config
  ansible.builtin.template:
    src: "{{ ansible_network_os }}/interfaces.j2"
    dest: "/tmp/{{ inventory_hostname }}_interfaces.cfg"

This approach reduced configuration errors by 92% at a major service provider.

Automating firewall policy updates

Firewall rule management is where Ansible network automation delivers massive ROI. Implement this workflow:

  1. Store policies in human-readable YAML files
  2. Validate rules against security compliance standards
  3. Generate vendor-specific configurations via Jinja2
  4. Deploy with atomic change control

Sample Fortinet policy playbook snippet:

- name: Update firewall policies
  fortinet.fortios.fortios_firewall_policy:
    state: "present"
    policy:
      srcintf: [ "port1" ]
      dstintf: [ "port2" ]
      srcaddr: [ "Corp_Network" ]
      dstaddr: [ "Web_Servers" ]
      service: [ "HTTPS" ]
      action: "accept"

Critical: Always implement pre-change backups and rollback procedures. Use ansible-check mode for dry runs before production deployment.

Testing and validation strategies

Automate validation with these techniques:

  • Pre-checks: Capture “show” command outputs before changes
  • Post-validation: Verify BGP neighbors/interface status after deployment
  • Network tests: Execute ping/traceroute between endpoints

Leverage Ansible’s assert module for automated compliance checks:

- name: Verify OSPF neighbors
  cisco.ios.ios_command:
    commands: show ip ospf neighbor
  register: ospf_result
- name: Validate neighbor count
  ansible.builtin.assert:
    that: ospf_result.stdout[0] | count('FULL') == 4

According to Cisco’s automation studies, teams implementing these checks reduce network outages by 73%.

Scaling and optimization techniques

For large environments:

  • Use strategy: free for parallel execution
  • Implement ansible-pull for distributed automation
  • Set forks: 50 in ansible.cfg for concurrent operations

Monitor performance with:

ANSIBLE_CALLBACK_WHITELIST=profile_tasks ansible-playbook deploy.yml

For enterprise-scale deployments, integrate with AWX or Red Hat Ansible Automation Platform for role-based access control and job scheduling.

Frequently asked questions

How does Ansible handle different network OS versions?

Ansible uses conditional logic in playbooks and version-specific templates. You can create Jinja2 templates for IOS 15.1 and 17.x separately, then use ansible_net_version facts to load the appropriate template. Most network modules automatically adapt to supported OS versions.

Can I use Ansible for legacy network devices?

Yes, but with limitations. For devices without API support, use the ansible.netcommon.cli_command module for screen-scraping. Always test extensively as output parsing may break with firmware updates. For mission-critical legacy devices, consider gradual replacement rather than automation investment.

How do we manage secrets in network automation?

Always use Ansible Vault for credential management. Encrypt device passwords and API keys with AES-256. For enterprise environments, integrate with HashiCorp Vault or CyberArk via the ansible.builtin.lookup plugin. Never store credentials in plain text files or Git repositories.

What’s the biggest pitfall in network automation?

Lack of testing. Always implement a three-stage pipeline: 1) Validate configurations in lab environments identical to production 2) Use –check mode for dry runs 3) Deploy with rolling updates and automatic rollback capabilities. Network changes can cause business-impacting outages if not properly validated.

Conclusion

Mastering Ansible for multi-vendor networks transforms complex operations into repeatable, version-controlled workflows. By implementing dynamic inventories, Jinja2 templates, and automated firewall management, you’ll achieve configuration consistency across Cisco, Juniper, and Fortinet environments while eliminating manual errors. Start small by automating backup collection, then expand to configuration deployment and policy management. Ready to transform your network operations? Explore our Ansible playbook repository for production-ready examples. Schedule a network assessment today to identify your highest-ROI automation opportunities.