← All articles

Cloud

Network Automation with Ansible

Network Automation with Ansible

Ansible automates infrastructure configuration through declarative playbooks that describe desired state rather than imperative command sequences. For network engineering, Ansible connects to devices via SSH or HTTP APIs, executes platform-specific modules, and reports changes with idempotency — running the same playbook twice produces the same result without unintended side effects. Network teams adopt Ansible for configuration backup, compliance auditing, standardized deployment, and controlled change rollout at scale across heterogeneous device estates.

Ansible requires no agent on managed devices. The control node — a Linux workstation, CI/CD runner, or Ansible Automation Platform cluster — connects outward to network devices using credentials stored in vault systems. This pull-based model suits network infrastructure where installing agents on routers and switches is impractical. Execution parallelism through forks configures hundreds of devices concurrently with rolling strategies that limit blast radius during changes.

Core Concepts

Inventory defines managed devices organized into groups — core_routers, campus_switches, firewalls_dc. Static inventory files work for small environments; dynamic inventory plugins query IPAM, NetBox, or cloud APIs for current device lists. Group variables and host variables provide site-specific parameters — SNMP communities, syslog servers, NTP sources — without hardcoding values in playbooks. Hierarchies allow common variables at all:children level with overrides at group and host levels.

Playbooks contain plays that map hosts to roles and tasks. Roles bundle reusable task sequences with defaults, handlers, and templates — a base_config role might configure hostname, DNS, NTP, and logging consistently across platforms with platform-specific task files selected by ansible_network_os. Tasks call modules — ios_config, junos_config, arista_config, nxos_config — that abstract CLI or API interaction into declarative resource definitions.

Network Collections

Ansible Galaxy collections package modules for vendor platforms and cloud APIs. Cisco IOS, IOS-XE, NX-OS, Juniper Junos, Arista EOS, and Palo Alto networks each have dedicated collections maintained by vendors and community contributors. Install collections via ansible-galaxy and pin versions in requirements.yml for reproducible CI/CD environments. Module documentation specifies required connection plugins — network_cli for SSH CLI, httpapi for REST APIs, netconf for NETCONF sessions.

Resource modules configure specific subsystems — ios_interfaces, junos_bgp, eos_vlan — with structured parameters rather than raw CLI commands. This approach survives minor OS syntax changes better than template-generated command lists. When resource modules lack coverage, command module or cli_config with manual command sequences fills gaps at the cost of reduced idempotency guarantees.

Safe Automation Workflow

Start with read-only automation. Nightly configuration backup playbooks connect to every device, retrieve running configuration, and commit to Git repositories with timestamps and device identifiers. Configuration drift detection compares live config against Git HEAD, alerting when unauthorized changes occur. These workflows deliver immediate value without production change risk and build organizational confidence in automation tooling.

Progress to compliance validation playbooks that assert required settings — NTP configured, SNMPv3 enabled, AAA authentication mandatory — and report violations without remediating automatically. Compliance reporting for audits becomes a playbook execution rather than manual CLI inspection across hundreds of devices. Only after read and validate workflows are reliable should teams automate remediation changes.

Controlled Change Rollout

Production configuration changes run through check mode first — ansible-playbook --check shows what would change without applying it. Limit execution to canary devices with --limit before broad rollout. Use serial keyword to update devices in batches — five switches at a time — preventing total outage if a playbook contains errors. Maximum failure percentage settings abort playbooks if too many devices fail, signaling stop before completing a dangerous change across the entire fleet.

Integrate Ansible with CI/CD pipelines. Pull requests against playbook repositories trigger check mode runs against lab devices or virtual instances. Approved merges execute against production inventory during maintenance windows with approval gates. Store playbook execution logs and device output in centralized systems for change audit trails. Pair Ansible changes with rollback playbooks tested in lab before production execution.

Integration and Scaling

Ansible Automation Platform — formerly Tower — provides RBAC, workflow templates, job scheduling, and credential management for team-scale operations. Event-driven automation responds to SNMP traps or syslog events with remediation playbooks. Integrate with ServiceNow or Jira for change ticket linkage. Dynamic inventory from NetBox ensures new devices receive baseline configuration automatically upon IPAM registration.

Ansible complements rather than replaces domain expertise. Playbooks encode expert knowledge into repeatable, reviewable automation. Network engineers who invest in Ansible skills reduce toil on repetitive tasks and redirect effort toward architecture and troubleshooting — while maintaining the discipline of peer review, testing, and incremental adoption that prevents automation from becoming a faster way to break production at scale.

Platform-Specific Considerations

Juniper devices support NETCONF and commit-confirmed operations that automatically roll back configuration unless explicitly confirmed within a timeout window — an invaluable safety net for automated changes on production routers. Cisco IOS-XE supports programmatic CLI through network_cli and RESTCONF through httpapi connection plugins; choose RESTCONF when available for structured responses that parse more reliably than screen-scraped CLI output. Arista EOS exposes a rich eAPI JSON interface that Ansible modules wrap into idempotent resource declarations for VLANs, interfaces, and BGP neighbors.

Handle platform differences through role variables rather than conditional spaghetti in shared tasks. A single playbook should call role tasks that internally branch on ansible_network_os, keeping playbooks readable for reviewers who may not know every vendor syntax. Test platform-specific roles against virtual lab instances — Cisco VIRL, Juniper vMX, Arista cEOS — before touching production hardware. Lab fidelity matters: features absent in virtual images should be flagged as manual verification items in change documentation.

Credential rotation requires Ansible Vault or external secrets managers integrated through lookup plugins. Never store passwords in plaintext inventory files committed to Git. Service accounts for automation should have minimum privilege — configure-only where possible, not full enable-level access on every device. Audit automation account sessions through TACACS+ logging identical to human administrator sessions.

Failure Recovery Patterns

Implement automatic configuration rollback on detected failure during playbook execution. Cisco commit-confirmed, Juniper commit confirmed, and Arista commit timer provide native rollback windows. For platforms without native rollback, capture running configuration before changes and deploy restore playbooks triggered when post-change validation tasks fail connectivity or service health checks.

Maintain emergency break-glass procedures for manual device access when automation systems are unavailable. Automation dependency without manual fallback creates single points of failure during controller outages, credential system failures, or Ansible platform maintenance. Quarterly manual configuration exercises ensure engineers retain hands-on skills automation should augment rather than replace entirely.