Network Automation and Software-Defined Networking Questions
Programmatic and automated network operation: network automation tooling (Ansible network modules, Netmiko, NAPALM, Nornir, Jinja2 templating, ZTP), choosing between CLI-scraping libraries and model-driven programmability (NETCONF, RESTCONF, gNMI, YANG) across multi-vendor fleets, idempotent and declarative-versus-imperative design, a network source of truth (NetBox) and intended-versus-running configuration drift reconciliation, Git-based versioning and review of device configuration and automation code, pre- and post-change validation (for example Batfish) including lab or emulated test environments, CI/CD and staged, canary or rollback-safe rollout of configuration to large device fleets with concurrency control and credential and secret handling for automation, automated site and leaf-switch provisioning, and event-driven remediation from streaming telemetry. Also software-defined networking: control and data-plane separation, controller architecture and state consistency, controller-managed overlays and tenant network virtualization, SD-WAN controller orchestration and programmable data planes (P4). Boundary: general scripting and Terraform practice, shell craft, IAM, incident response, protocol design, data-centre fabric and WAN topology design (including choosing EVPN-VXLAN or SD-WAN), and network fault diagnosis are covered elsewhere.
How would you combine offline analysis of device configs with live telemetry to validate a risky change such as a BGP route policy or an access-control update? Describe the pre-deploy, in-flight and post-deploy steps and what each can miss.
Sample Answer
Direct answer
Use offline analysis to prove the change does what you intend on a model of the network, use live telemetry to prove the model matches reality and to catch what the model cannot see, and use both before, during and after the push, with an explicit abort rule for each stage. Neither is sufficient alone: offline analysis checks configuration logic against a snapshot, telemetry (live counters and state read from the running devices) shows real behavior but only after the change is live somewhere. I use BGP route policy and ACL (access-control list, an ordered permit/deny list for traffic) updates as the example. A BGP route policy is the rule set a router applies to routes it receives from or sends to a neighbor: it can accept, reject or tag them, or change how attractive they are.
Pre-deploy (offline, plus a live baseline)
- Snapshot current and candidate configurations into Batfish, an open source network configuration analysis tool that builds a model of routing and forwarding from the configs, with no live device state.
- Differential reachability: compare the two snapshots.
differentialReachabilityreturns example flows that succeed in one snapshot but not in the other, so an unintended change in connectivity appears as a concrete flow. The examples are not a complete list of every affected flow: review every flow returned, not just the one you aimed at, then fix the cause and re-run until the table is empty. With pybatfish, Batfish's Python client, the call looks likebf.q.differentialReachability().answer(snapshot='candidate', reference_snapshot='current').frame(), wheresnapshotis the candidate configuration andreference_snapshotis the one you compare against. The result is a table with one row per example flow, with columnsFlow,Snapshot_Traces,Snapshot_TraceCount,Reference_TracesandReference_TraceCount: the flow (source and destination address, protocol, ports) and how it was forwarded or dropped in each snapshot. An empty table means no flow in the searched header space succeeds in one snapshot and fails in the other (Batfish describes the question as returning example flows that are successful in one snapshot but not in another); it does not show a flow that is dropped in both snapshots for different reasons, so treat it as strong evidence, not proof that nothing changed. A row for a flow from a customer subnet to the internet that now ends in a drop is the signal to stop. - Policy-specific questions:
testRoutePoliciesshows how a given route is processed by a routing policy;searchRoutePoliciesfinds routes for which a policy permits or denies, with constraints;testFiltersshows whether a flow is permitted by an ACL and which line matched. For example,bf.q.testFilters(headers=HeaderConstraints(srcIps='10.10.10.1', dstIps='218.8.104.58', applications=['dns']), nodes='rtr-with-acl', filters='acl_in').answer().frame()returns a row with the device (Node), the ACL (Filter_Name), theFlow, theAction(for instancePERMIT) andLine_Content, the exact ACL line that decided it (in Batfish's documented example,660 permit udp 10.10.10.0/24 218.8.104.58/32 eq domain). Run before and after the change, a flippedActionor a different matching line is the unintended effect. These calls come from the Batfish documentation and were not run here, which needs a Batfish server. Use these as assertions: customer prefixes must still be advertised to the transit peers (the upstream internet providers you buy connectivity from), bogons (address ranges that should never appear on the public internet, such as private or reserved space) must still be denied, management traffic must still be permitted. - Capture the live baseline you will compare against later: BGP session states, received and advertised prefix counts per neighbor (a prefix is one announced address block, such as 203.0.113.0/24), ACL hit counters (how many packets each ACL line has matched so far), interface error and traffic counters, and synthetic probe results (test packets you send on a schedule to measure loss).
What it can miss: the model does not know live state (what a peer actually announces today), hardware limits (for example ACL memory), or device software bugs, and Batfish documents thatsearchRoutePoliciessupports only common forms of prefix, community (a tag attached to a route that policies match on) and AS-path (the list of networks, by AS number, a route has passed through) matching and may return no answer even where a behavior exists, so empty results are not proof of safety.
In-flight (canary with a timer)
- Push to one low-blast-radius device first (a canary: the first small slice that tests the change on real traffic) (one redundant edge of a pair), with a confirmed commit or commit-confirm timer so an unconfirmed change reverts (NETCONF default 600 seconds; NAPALM
commit_config(revert_in=...)). - Compare telemetry against the offline prediction: the prefix count advertised to each neighbor should equal what the model predicted, sessions stay Established, ACL hit counters increment on permit lines and drop lines as expected.
- Abort rule written before the push, for example: any BGP session leaves Established, or the advertised prefix count differs from prediction, or probe loss exceeds baseline: revert, do not investigate while live.
What it can miss: low-volume or rare flows, paths used only during failures (the backup path), effects that appear later (timers, route refresh, which is a neighbor re-sending all its routes on request, and convergence, the time the network takes to settle on new paths after a peer reset), and a canary that does not represent the rest.
Post-deploy
Confirm the change (cancel the timer) only after the checks pass, then widen in stages, with the same assertions rerun against live data, and a soak period (a waiting time with the change live and monitored) that includes a daily traffic peak. Re-snapshot the live configs and re-run differential analysis so the model matches reality for the next change.
What it can miss: failure-only behavior stays unproven until a failure happens, so schedule a controlled failover test for high-risk policies.
Worked example
Hypothetical change: set a lower local preference (a number used to choose between several paths to the same destination: higher wins; it steers your own network's outbound path choice and is not sent to other autonomous systems over eBGP, per RFC 4271 section 5.1.5) on routes learned from a secondary transit provider, and tighten an inbound ACL on management. Differential analysis should show zero changed reachability for customer flows and one intended change (management from an old jump host now denied). Pre-change baseline says 410 prefixes advertised to transit A (numbers are made up for this example).
Why the count of prefixes advertised to transit A is the right canary: local preference changes which path is preferred for the routes you receive, not which prefixes you announce to a provider, provided the export policy toward transit A sends only your own and your customers' prefixes (the usual arrangement). The model predicts the advertised set is unchanged, so the count must stay 410. If it moves, the edit touched something it was not meant to, for example an export filter or a prefix list shared with the policy you edited. The same 410 afterward lets the rollout continue; 409 or 412 stops it, and you revert and compare the advertised lists to find the 1 or 2 prefixes that appeared or vanished. The count is a cheap proxy: it can hide one prefix added and one removed, so also compare the actual prefix list when it differs from prediction or when the change touches exports.
Trade-offs and pitfalls
- Offline analysis is only as good as the snapshot: stale configs give confident wrong answers. Take the snapshot from the device, not from the repo, for the baseline.
- Treating a green pre-check as permission to skip the canary is the common mistake.
- Too many abort metrics produce false aborts: pick a few that map to user impact.
Write a Python function that uses NAPALM to make sure VLANs 100 (named apps) and 101 (named db) exist on a device, creating only what is missing. It must be safe to run repeatedly, handle connection and commit errors cleanly, and have a dry-run mode that shows the planned change without applying it. Show the key NAPALM calls and the control flow.
Sample Answer
Direct answer
Make the function idempotent (running it twice leaves the device exactly as running it once) by reading state first, then proposing only the missing delta, and make the safety come from NAPALM's candidate-config workflow: load the missing VLANs as a merge candidate (a proposed configuration staged on the device, not yet running, to be merged into the existing one), inspect the diff, discard it in dry-run mode, otherwise commit, verify, and roll back if verification fails. The example targets Arista EOS, where the VLAN syntax is vlan 100 followed by name apps (check the vendor's VLAN configuration guide for your release). Another vendor changes the rendering function and the diff behavior, not the control flow.
Approach
- Read.
get_vlans()returns each VLAN's name and member interfaces. The NAPALM documentation shows integer VLAN ids as keys, but the EOS driver builds them from eAPI (Arista's JSON-over-HTTP management interface) JSON where they are strings, so the code converts withint(). The shape is a dictionary keyed by VLAN id, for example{"100": {"name": "apps", "interfaces": []}}on EOS, which is whyread_vlansturns it into{100: "apps"}. Support for this getter: EOS, IOS, Junos, NX-OS and NX-OS over SSH have it; IOS-XR does not (NAPALM support matrix), so the same function on IOS-XR needs a different read such as parsing the configuration. - Plan.
missingis desired VLANs whose id is not on the device. A VLAN that exists under a different name is reported and left alone, because the request is to create only what is missing. (Flip that single rule if renaming is wanted.) - Stage.
load_merge_candidate(config=...)loads the configuration to be merged into the running configuration at commit. On EOS this opens a named configuration session (a private scratch copy of the configuration that only takes effect when committed); nothing is running yet.compare_config()returns the diff between running and candidate. - Dry run. Print the diff,
discard_config(), done. The device's running configuration was never touched. - Apply.
commit_config(), read the VLANs again, androllback()if they are not there. - Errors. A bad candidate raises
MergeConfigException, a failed commit raisesCommitError, and connection problems raiseConnectionException(its subclasses include authentication, timeout and unsupported-version errors). On the eAPI transport the driver'sopen()only builds the client, and the first real request (show version) goes through pyeapi, so an unreachable host or an HTTP 401 raisespyeapi.eapilib.ConnectionError, which is not a NAPALMConnectionException. The code catches both. Theexceptblock discards the candidate on any failure so a half-loaded session is not left holding the configuration lock. The connection is always closed.
Code
from napalm.base.exceptions import ConnectionException
from pyeapi.eapilib import ConnectionError as EapiConnectionError
DESIRED = {100: "apps", 101: "db"}
def render(vlans):
# Arista EOS: "vlan <id>" enters VLAN mode, "name <name>" names the VLAN.
return "\n".join(f"vlan {vid}\nname {name}" for vid, name in sorted(vlans.items()))
def read_vlans(device):
# EOS returns VLAN ids as strings in eAPI JSON, so normalise to int.
return {int(vid): info["name"] for vid, info in device.get_vlans().items()}
def ensure_vlans(device, desired, dry_run=True):
try:
device.open()
except (ConnectionException, EapiConnectionError) as exc:
return f"UNREACHABLE ({type(exc).__name__}): {exc}"
try:
current = read_vlans(device)
missing = {v: n for v, n in desired.items() if v not in current}
notes = [f"VLAN {v} exists as '{current[v]}', wanted '{n}': left alone"
for v, n in sorted(desired.items())
if v in current and current[v] != n]
if not missing:
return "\n".join(["NO CHANGE"] + notes)
device.load_merge_candidate(config=render(missing))
diff = device.compare_config()
if not diff:
device.discard_config()
return "\n".join(["NO CHANGE (empty diff)"] + notes)
if dry_run:
device.discard_config()
return "\n".join(["DRY RUN, planned change:", diff] + notes)
device.commit_config()
after = read_vlans(device)
if any(after.get(v) != n for v, n in missing.items()):
device.rollback()
return "ROLLED BACK: VLANs not present after commit"
return "\n".join(["COMMITTED:", diff] + notes)
except Exception as exc: # MergeConfigException, CommitError, eAPI errors
try:
device.discard_config()
except Exception:
pass
return f"FAILED, candidate discarded ({type(exc).__name__}): {exc}"
finally:
device.close()
Live use needs a device and credentials. Save the code above as ensure_vlans.py, then open the real driver and call the same function:
import os
from napalm import get_network_driver
from ensure_vlans import DESIRED, ensure_vlans
driver = get_network_driver("eos")
dev = driver(hostname="sw1.example.net", username="automation", password=os.environ["NET_PW"],
optional_args={"transport": "https"})
print(ensure_vlans(dev, DESIRED, dry_run=True))
The get_vlans, load_merge_candidate, compare_config, commit_config and rollback calls on a real switch were not run here; this block needs one. The control flow runs against an in-memory stand-in with the same method names. Save it as demo.py in the same directory as ensure_vlans.py (after pip install napalm):
from napalm.base.exceptions import CommitError
from ensure_vlans import DESIRED, ensure_vlans
class FakeDevice:
"""In-memory stand-in with the same method names as a NAPALM driver."""
def __init__(self, vlans, fail_commit=False):
self.vlans, self.pending, self.fail_commit = dict(vlans), {}, fail_commit
def open(self): pass
def close(self): pass
def get_vlans(self):
return {str(v): {"name": n, "interfaces": []} for v, n in self.vlans.items()}
def load_merge_candidate(self, config):
lines = config.splitlines()
for i in range(0, len(lines), 2):
self.pending[int(lines[i].split()[1])] = lines[i + 1].split()[1]
def compare_config(self):
return "\n".join(f"+vlan {v}\n+ name {n}" for v, n in sorted(self.pending.items()))
def discard_config(self): self.pending = {}
def commit_config(self):
if self.fail_commit:
raise CommitError("commit rejected")
self.vlans.update(self.pending)
self.pending = {}
def rollback(self): pass
cases = [
("dry run, nothing exists", FakeDevice({1: "default"}), True),
("apply", FakeDevice({1: "default"}), False),
("second run", FakeDevice({1: "default", 100: "apps", 101: "db"}), False),
("only 101 missing", FakeDevice({1: "default", 100: "apps"}), False),
("100 has another name", FakeDevice({1: "default", 100: "web", 101: "db"}), False),
("commit rejected", FakeDevice({1: "default"}, fail_commit=True), False),
]
for label, dev, dry in cases:
print(f"--- {label}")
print(ensure_vlans(dev, DESIRED, dry_run=dry))
print("device VLANs:", dev.vlans)
Output:
--- dry run, nothing exists
DRY RUN, planned change:
+vlan 100
+ name apps
+vlan 101
+ name db
device VLANs: {1: 'default'}
--- apply
COMMITTED:
+vlan 100
+ name apps
+vlan 101
+ name db
device VLANs: {1: 'default', 100: 'apps', 101: 'db'}
--- second run
NO CHANGE
device VLANs: {1: 'default', 100: 'apps', 101: 'db'}
--- only 101 missing
COMMITTED:
+vlan 101
+ name db
device VLANs: {1: 'default', 100: 'apps', 101: 'db'}
--- 100 has another name
NO CHANGE
VLAN 100 exists as 'web', wanted 'apps': left alone
device VLANs: {1: 'default', 100: 'web', 101: 'db'}
--- commit rejected
FAILED, candidate discarded (CommitError): commit rejected
device VLANs: {1: 'default'}
The stand-in prints a simplified diff. A real EOS device returns the text of its own session diff, so the exact lines will differ.
Key points
- Run it twice. The "second run" and "only 101 missing" cases show idempotence: no VLAN is rewritten, and a partial state converges to the full state.
- Dry run is real staging. On EOS the candidate lives in a configuration session that
discard_config()aborts, so a dry run costs one session and leaves the running configuration untouched. - Commit confirm for risky changes.
commit_config(revert_in=<seconds>)asks for an automatic revert unless confirmed. In the EOS driver this uses a session commit timer (the device reverts the session on its own if you do not confirm before the timer expires),confirm_commit()finalizes it androllback()aborts a pending one. Use it when the change could cut off the management path. - Platform limits that change the answer. For a first implementation on EOS, the limits that matter are the
messageargument and therollback()coverage; the version and other-vendor notes matter when you widen the scope.- EOS:
commit_config(message=...)raisesNotImplementedError. Compare and merge need EOS 4.15.0F or later, and the driver in NAPALM 5.2.0 refuses to open on EOS older than 4.23.0.commit_config()first runscopy startup-config flash:rollback-0androllback()runsconfigure replace flash:rollback-0, so it only covers changes committed through the API, and any change made outside the API since that copy was taken is reverted along with it (NAPALM EOS notes). - IOS: the archive feature must be enabled on a local filesystem for automatic rollback, and the candidate's indentation must exactly match the running configuration for the diff to work.
- NX-OS: the merge diff is documented as very simplistic.
- EOS:
- Locking. If another session already holds the EOS configuration lock, the load raises a session-locked error; the handler reports it and a later run retries safely.
Complexity
In plain terms, the cost grows linearly with the number of VLANs and the number of device round trips stays fixed. Time is O(d) for d desired VLANs for the planning loop, plus a constant number of device round trips (read, load, compare, commit, read again). The device-side cost depends on the platform. Memory is O(v) for v VLANs on the device, because the whole VLAN table is read into one dictionary.
Edge cases
| Case | Behavior |
|---|---|
| Both VLANs present | No candidate is loaded, status "NO CHANGE" |
| One VLAN present | Only the missing one is rendered and committed |
| VLAN present with another name | Reported and left alone |
| Device unreachable or bad credentials | Returned as UNREACHABLE; no state touched. Run against a closed port the message ends Socket error during eAPI connection: [Errno 111] Connection refused, and against a server answering 401 with an empty body it ends Unauthorized. (any response body follows that text) |
| Commit rejected or driver error | Candidate discarded; the device is unchanged unless the commit had already applied, in which case a rerun reads the real state and converges |
| VLAN id outside 1 to 4094 | 1 to 4094 is the usable 802.1Q range (0 and 4095 are reserved), so validate ids before rendering |
| VLAN name rules | Name length and allowed characters differ by platform and release, so validate names against the target's rules before rendering |
Several automation jobs and operators can try to change the same device at once. Propose how you would prevent races, keep device state consistent, allow human overrides, and resolve conflicts.
Sample Answer
Direct answer
Make one writer per device the invariant. Put a per-device lock with an expiry (a lease) and a fencing token (a number that rises with every grant, so the device-side check can tell a current holder from a stale one) in front of every change, funnel automation through one queue that allows a single in-flight job per device, and use the device's own transaction features (a candidate configuration is a draft copy that takes effect only when committed; a confirmed commit applies it with a timer and reverts unless you confirm) as the last line of defence. Humans are not blocked out: they place a visible, time-limited hold on the device, automation skips it, and the resulting difference (drift) is resolved through an explicit policy (intent wins unless someone adopts the manual change into the source of truth, the database that records what each device should look like).
Prevent races
- Pessimistic locking for writes (take the lock before you change anything). Device changes are short and the cost of a conflicting write is an outage, so take a lock first. Optimistic locking (read a version, write only if it is unchanged) is the right tool for the shared intent store, where conflicts are rare and a retry is cheap: a git merge conflict or a compare-and-swap, an update that succeeds only if the stored value still equals what you read.
- Where the lock lives. A lease in a shared store (database row, etcd, a small replicated key-value store, Redis with care) keyed by device, with a time-to-live, and a fencing token that increases on every grant. The job must re-check it just before the commit step. Run the demo below to see a stalled job lose its lease and get rejected.
- On the device. NETCONF (the IETF configuration protocol over SSH) defines a lock operation on a datastore, which is a named store of configuration on the device: the running datastore holds the configuration currently in effect, and the candidate datastore holds the draft. The lock lasts until released or the session closes. The server rejects a lock request in three cases: another session already holds the lock; you ask to lock the candidate datastore while it has uncommitted changes; or you ask to lock the running datastore while a confirmed commit is pending. Example: a second job asking to lock running while a first job's confirmed commit is waiting for its confirmation is refused. A dropped session releases it, which simplifies crash recovery. On devices without it (CLI-only), the lease in your store is the only exclusion, so say so and keep the window short.
- Throttling against device limits. Bound a worker pool (for example 50 workers fleet-wide), allow one in-flight job per device and a lower cap per vendor or per management API, and back off with jitter (a small random extra delay, so retries from many workers do not all land at the same instant) when a device returns busy or an API returns a rate-limit error, instead of retrying at once from every worker. Gate by maintenance window: a job outside its window stays queued.
Keep device state consistent
Every job follows the same lifecycle: acquire lease, capture running config, render intended config, show the diff, apply to the candidate or with a commit-confirm timer, verify, confirm or roll back, release. A confirmed commit that is not confirmed reverts: the NETCONF default confirm-timeout is 600 seconds, and if the session that issued it terminates before the timeout the server must restore the earlier configuration (unless a persist token was used). NAPALM (a multi-vendor Python library) exposes the same idea as commit_config(revert_in=...), with confirm_commit(), has_pending_commit() and rollback().
Human overrides and conflicts
- An operator sets a hold (owner, reason, expiry, for example 4 hours) in the same store. Automation that sees a hold skips the device and reports, never queues behind it indefinitely.
- Drift detection treats a change made during a hold as pending adoption: within the expiry the owner either opens a change to the source of truth that adopts it, or the next run reverts it. Without an expiry, holds become permanent exceptions.
- Conflict policy: intent wins by default; two automation jobs touching the same device are serialized, never merged; a job whose precondition changed (device config hash differs from the one it diffed against) aborts and re-plans.
Worked example
Job A (BGP policy) takes the lease on edge1 with token 1 and a 30 second TTL, then its SSH session hangs. At t=45 s the lease has expired and job B (an access-control list, ACL, update) gets token 2; it pushes at t=50 s. When job A wakes at t=70 s, its pre-commit check fails. Reproducible demo (pure Python, pinned times, runs unchanged):
class LeaseStore:
"""Per-device lease with a fencing token. 'now' is passed in so the demo is deterministic."""
def __init__(self):
self.holder = {} # device -> (owner, token, expires_at)
self.counter = 0
def acquire(self, device, owner, now, ttl):
cur = self.holder.get(device)
if cur and cur[2] > now:
return None # someone else holds a live lease
self.counter += 1
self.holder[device] = (owner, self.counter, now + ttl)
return self.counter
def still_valid(self, device, token, now):
cur = self.holder.get(device)
return bool(cur) and cur[1] == token and cur[2] > now
store, applied = LeaseStore(), []
def push(device, owner, token, now, change):
# gate checked immediately before the commit step
if not store.still_valid(device, token, now):
print(f"t={now:>3}s {owner}: REJECTED (lease lost), change '{change}' not pushed")
return
applied.append((device, owner, change))
print(f"t={now:>3}s {owner}: pushed '{change}' with token {token}")
tA = store.acquire("edge1", "job-A", now=0, ttl=30)
print("job-A token:", tA)
print("job-B at t=10:", store.acquire("edge1", "job-B", now=10, ttl=30)) # denied
# job-A stalls (hung SSH session) past its 30 s lease
tB = store.acquire("edge1", "job-B", now=45, ttl=30)
print("job-B token at t=45:", tB)
push("edge1", "job-B", tB, 50, "acl-update")
push("edge1", "job-A", tA, 70, "bgp-policy") # A wakes up late
print("applied:", applied)
Output:
job-A token: 1
job-B at t=10: None
job-B token at t=45: 2
t= 50s job-B: pushed 'acl-update' with token 2
t= 70s job-A: REJECTED (lease lost), change 'bgp-policy' not pushed
applied: [('edge1', 'job-B', 'acl-update')]
Honest limit: the device does not know about my token. The check protects against a stale job only up to the moment of the check, so a job that passes it and then stalls inside the commit can still race. Timeline: at t=29 job A passes the check and its token is still valid; at t=30 the lease expires; at t=45 job B takes the lease with token 2, and at t=50 it pushes; at t=55 job A, which already passed its check, finishes its commit and overwrites job B's change. Nothing in the lease store can stop that last write. Closing that last window needs the device-side lock or candidate datastore, which is why both layers are used.
Trade-offs and pitfalls
- Lease TTL too short: healthy slow jobs lose their lease mid-change. Too long: a crashed job blocks the device. Renew the lease while work is progressing and keep the TTL longer than the worst normal job.
- A global lock serializes the whole fleet and defeats parallelism: lock per device, and add a per-site lock only for changes that must be coordinated (both ends of a link).
- Unconfirmed retries of non-idempotent commands (appending a line twice) turn a timeout into a second change: make steps idempotent (safe to run twice) or verify state before retrying.
Write an Ansible playbook for a group of Cisco IOS edge routers that sets the hostname and an NTP server. Make it safe to re-run, and explain what must be in place on the control node and the devices for it to work.
Sample Answer
Direct answer
Use the Cisco IOS resource modules (Ansible modules that manage one feature, such as hostname or NTP, as structured data rather than raw command lines) (cisco.ios.ios_hostname and cisco.ios.ios_ntp_global) with state: merged. They compare the desired value with the device's running configuration and only send commands when something differs, so the playbook is safe to re-run. The control node needs ansible-core, the cisco.ios and ansible.netcommon collections (installable bundles of modules and plugins) and an SSH library; each device needs SSH reachable from the control node, a login account, and enable-mode access (IOS's privileged mode, entered with the enable command, where configuration is allowed), all declared as inventory variables (values attached to a host or group, here in group_vars) for the network_cli connection (Ansible's way of driving a device's command line over SSH).
The playbook (site.yml)
---
- name: Baseline hostname and NTP on IOS edge routers
hosts: edge_routers
gather_facts: false
vars:
ntp_servers:
- 192.0.2.10
- 192.0.2.11
tasks:
- name: Set the hostname from the inventory name
cisco.ios.ios_hostname:
config:
hostname: "{{ inventory_hostname }}"
state: merged
notify: Back up running config
tags: [hostname]
- name: Declare the NTP servers
cisco.ios.ios_ntp_global:
config:
servers:
- server: "{{ ntp_servers[0] }}"
prefer: true
- server: "{{ ntp_servers[1] }}"
state: merged
notify: Back up running config
tags: [ntp]
- name: Save only when running and startup differ
cisco.ios.ios_config:
save_when: modified
handlers:
- name: Back up running config
cisco.ios.ios_config:
backup: true
backup_options:
dir_path: ./backups
filename: "{{ inventory_hostname }}.cfg"
What the playbook's lines do: hosts: edge_routers selects the inventory group; gather_facts: false skips Ansible's default fact collection, which expects a general-purpose server and not a router; vars holds values reused by tasks; each task calls a module, and the first uses inventory_hostname (the device's name in the inventory) so the router's hostname always equals its inventory name; notify queues a handler, a task that runs only if a notifying task changed something, and handlers run once at the end of the play, so the backup happens after the changes; tags label tasks so you can run a slice.
Inventory (inventory.ini) and connection variables (group_vars/edge_routers.yml):
[edge_routers]
edge-rtr-01 ansible_host=198.51.100.11
edge-rtr-02 ansible_host=198.51.100.12
---
ansible_connection: ansible.netcommon.network_cli
ansible_network_os: cisco.ios.ios
ansible_user: automation
ansible_become: true
ansible_become_method: enable
# ansible_network_os selects the platform driver; ansible_become with method enable enters enable mode after login.
# ansible_password and ansible_become_password: keep in Ansible Vault, or use SSH keys for the login
Why it is safe to re-run
- A resource module reads the current configuration, builds the intended one and sends only the difference. With
state: mergedit combines your values with existing settings and leaves other NTP servers alone.mergedis the state to know first, because it only adds or corrects.replacedandoverriddenwould also remove unlisted entries, which is a bigger blast radius than this task needs. notifyfires the handler only if the task reported a change, and handlers run once at the end of the play. So a second run with nothing to change reportschanged=0, takes no backup and writes nothing. The end of such a run looks like this (illustrative, not executed against a device):
PLAY RECAP
edge-rtr-01 : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
edge-rtr-02 : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
ok=3 counts the three tasks, and changed=0 is the evidence of idempotency.
save_when: modifiedcopies running-config to startup-config only if it differs from what was last saved, so an unchanged device is not rewritten. (changedwould save only when this task itself changed something, andneveris the default.)- The handler's
backup: truestores the running configuration under./backups. Because handlers run after the tasks, this file is a snapshot of the new state; to keep a pre-change copy for rollback, add abackup: truetask at the top of the play.
ios_config versus resource modules, and the idempotency trap
cisco.ios.ios_config pushes raw lines: you give lines and optionally parents (the section they belong to) and it diffs them as text against the running configuration (match: line by default). It is the tool for features no resource module covers, but its lines must match the device's running-config text exactly, including full-form keywords. The module documentation states that abbreviated commands are not idempotent, and shows the full-form pattern:
- name: Shut an interface (full-form keywords so the diff works)
cisco.ios.ios_config:
lines: [shutdown]
parents: interface GigabitEthernet1/0/11 # not "int gig1/0/11"
Resource modules such as cisco.ios.ios_vlans take structured data instead (vlan_id, name, state: active, shutdown: disabled) and have their own state choices: merged (the default), replaced, overridden, deleted and purged change the device, gathered reads the device's current VLANs back as structured data, and rendered and parsed work from text or data you supply without changing it. Prefer them where one exists, and fall back to ios_config where none does.
Tags and the backup trigger
Tags let you run one slice: ansible-playbook -i inventory.ini site.yml --tags ntp touches only NTP, and --limit edge-rtr-01 restricts it to one router. If you would rather tie the backup to a result than to notify, register the task and add when: result.changed (or set changed_when on a command task) to a separate backup task; the handler form is shorter and runs once however many tasks changed.
What I ran, and what needs a device
Executed in a python:3.12-slim container with ansible-core, ansible-lint and the cisco.ios collection: ansible-playbook -i inventory.ini site.yml --syntax-check passed, ansible-lint passed the production profile, and the rendered state produced this offline output from the same values (these are the exact commands the playbook would send to the router):
"hostname edge-rtr-01"
"ntp server 192.0.2.10 prefer"
"ntp server 192.0.2.11"
The real play and the second-run changed=0 check need a live IOS device and were not executed. The rendered state still requires the network_cli connection type to be set on the host (ansible_connection: local is rejected), though it does not log in to a device.
Trade-offs and pitfalls
- Bad variables push bad config just as consistently as good ones: use
serial(batch size) on a big fleet so a mistake hits a few devices first. - Keep credentials out of the inventory file; Ansible Vault (Ansible's built-in encryption for secret values) or a key-based login both work.
- Treat
ios_configlines like code under test: run twice and require the second run to report no change.
What does a practical testing strategy look like for network configuration changes and for the automation code that produces them? Give concrete things you would test before, during and after a change, and where virtual routers fit.
Sample Answer
Direct answer
Test in layers that get slower and more realistic: fast offline tests of the code and templates on every commit, an offline analysis of the generated configs, a run on virtual routers, then checks wrapped around the real change (a baseline before, post-checks per batch during, a soak and comparison after). The earlier a layer, the more often it runs and the cheaper a failure. Virtual routers prove logic and syntax on the target software; they do not prove scale or hardware behaviour.
The layers
| When | Layer | Concrete tests | Catches |
|---|---|---|---|
| Before, every commit | Lint and unit tests | yamllint, ansible-lint, template render tests, data validation | Typos, bad data, a template that emits the wrong line |
| Before, every commit | Offline config analysis | Batfish (an open-source tool that reads config files and models the network they describe, without any device) on the rendered configs | Undefined references, session mismatches, reachability changes |
| Before, per merge request | Virtual lab | containerlab topology with virtual routers and switches | Syntax the real software rejects, protocol behaviour |
| During | Pre-checks, canary, per-batch post-checks | Baseline capture, stop on first failure | Real-device surprises with small blast radius |
| After | Verification and soak | Compare with baseline, watch alarms | Slow failures such as flaps and leaks |
Testing the automation code and templates
The code that produces configs is software and gets unit tests. This suite renders a template for a switch, checks that the trunk allows exactly the declared VLANs (virtual LANs, numbered Layer 2 segments), that rendering is deterministic, that an overlapping subnet or an out-of-range VLAN id is rejected, and that a missing variable fails loudly (the template environment uses StrictUndefined, which turns a missing variable into an error instead of an empty string):
templates/access_switch.j2
{% for v in vlans %}
vlan {{ v.id }}
name {{ v.name }}
{% endfor %}
interface {{ uplink }}
switchport mode trunk
switchport trunk allowed vlan {{ vlans | map(attribute='id') | sort | join(',') }}
render.py
import ipaddress
from jinja2 import Environment, FileSystemLoader, StrictUndefined
env = Environment(loader=FileSystemLoader("templates"), undefined=StrictUndefined,
trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True)
def validate(data):
ids = [v["id"] for v in data["vlans"]]
assert len(ids) == len(set(ids)), "duplicate VLAN id"
assert all(1 <= i <= 4094 for i in ids), "VLAN id outside 1-4094"
nets = [ipaddress.ip_network(v["subnet"]) for v in data["vlans"] if "subnet" in v]
for i, a in enumerate(nets):
for b in nets[i + 1:]:
assert not a.overlaps(b), f"{a} overlaps {b}"
def render(data):
validate(data)
return env.get_template("access_switch.j2").render(**data)
test_render.py
import re
import pytest
from render import render
GOOD = {"uplink": "TenGigabitEthernet1/0/1",
"vlans": [{"id": 10, "name": "users", "subnet": "10.1.10.0/24"},
{"id": 20, "name": "voice", "subnet": "10.1.20.0/24"}]}
def test_trunk_allows_exactly_the_declared_vlans():
out = render(GOOD)
allowed = re.search(r"allowed vlan ([\d,]+)", out).group(1)
assert allowed == "10,20"
def test_render_is_deterministic():
assert render(GOOD) == render(GOOD)
def test_never_emits_allow_all():
assert "allowed vlan all" not in render(GOOD)
def test_missing_variable_fails_loudly():
with pytest.raises(Exception):
render({"vlans": GOOD["vlans"]})
def test_overlapping_subnets_rejected():
bad = {**GOOD, "vlans": GOOD["vlans"] + [{"id": 30, "name": "x", "subnet": "10.1.10.128/25"}]}
with pytest.raises(AssertionError):
render(bad)
def test_vlan_id_range_rejected():
bad = {**GOOD, "vlans": [{"id": 4095, "name": "x"}]}
with pytest.raises(AssertionError):
render(bad)
How the files fit together: access_switch.j2 loops over vlans to print each vlan and name pair and then one trunk line whose allowed list comes from the same data, render.py validates the data (duplicate ids, id range, overlapping subnets) before rendering, and each test in test_render.py checks one of those behaviours by name: test_trunk_allows_exactly_the_declared_vlans reads the allowed vlan line the template's last line produces, test_overlapping_subnets_rejected exercises the overlap check in validate, and test_vlan_id_range_rejected the 1 <= i <= 4094 check.
Run pip install jinja2 pytest and then python -m pytest -q: all six tests pass. A test suite that has never failed has not been shown to detect anything, so prove it can: change the template's last line to switchport trunk allowed vlan all and two tests fail (test_trunk_allows_exactly_the_declared_vlans and test_never_emits_allow_all). Revert, and they pass again.
Offline analysis of what you generated
Batfish parses configuration files without touching a device and answers questions about the network they describe: configuration properties such as undefined references (an ACL (access control list) or route-map named but never defined), BGP (Border Gateway Protocol) and OSPF (Open Shortest Path First) session compatibility (the bgpSessionStatus and ospfSessionCompatibility questions, each a named Batfish query whose result is a table: bgpSessionStatus has one row per configured BGP peering with a status of NOT_COMPATIBLE, ESTABLISHED or NOT_ESTABLISHED, while ospfSessionCompatibility lists the OSPF sessions that are compatible, so a neighbour you expect that has no row is the finding), forwarding and reachability, and differentialReachability, which compares two snapshots (before and after the change) and returns flows that succeed in one snapshot but not in the other. Run it on the current configs and on the rendered candidate and fail the merge request if reachability changes in a way the change did not intend. For example, the plain reachability question returns one row per flow (a flow is a sample packet defined by source, destination and protocol) with its traces and a trace count; differentialReachability returns only the flows whose success differs between the two snapshots, so an empty result means no tested flow went from delivered to dropped or the reverse, and any row names a flow that now behaves differently. A flow that is still delivered but takes a different path is not reported, which is why path-sensitive intent (traffic must traverse the firewall) needs its own reachability assertion.
Where virtual routers fit
Containerlab builds a lab from a YAML topology file (containerlab deploy -t topology.clab.yml, containerlab destroy -t topology.clab.yml) and can run Cisco virtual platforms (such as CSR1000v, Nexus 9000v and Catalyst 9000v), Arista, Juniper, SONiC and FRRouting. Use it for three jobs:
- Apply the real rendered config to the same software version you run, so syntax or feature differences surface before production.
- Check protocol outcomes: BGP and OSPF neighbours reach the expected state, expected prefixes are received, a failed link converges.
- Test the automation tool itself (the code that pushes configs, including any part of it that manages BGP) in a topology built to mimic one site.
Limits to state out loud: virtual images do not reproduce hardware forwarding, queueing and QoS (quality of service), line-rate behaviour or scale, so a pass proves the logic, not capacity. Of the platform names above, use the image that matches what runs in production: the point is software parity, not variety.
Safeguards so a lab test of the automation tool can never cause a routing outage:
- The lab management network has no route to production, and lab credentials are different from production credentials, so a copy-paste mistake cannot authenticate to a real router.
- The lab uses private AS (autonomous system, a network under one routing policy) numbers (RFC 6996 reserves 64512 to 65534 for 16-bit private use) and no session to a real peer.
- The tool refuses any target not in the
labinventory group, and defaults to dry run. - Configs under test carry no production prefixes or route-targets (the tags, used in VPN setups, that decide which routes are shared between customers or sites), so a leak cannot import or export a real route.
Layer 2 checks for a switching change
After the change is applied (in the lab, then per batch in production), assert on state read from the device rather than on the push succeeding:
- Switchport and trunk assertions: a trunk is a link that carries several VLANs at once.
show interfaces trunkshows the allowed-VLAN list of each trunk, and it must equal the intended list: a healthy result lists exactly 10 and 20 in the example above, while a broken one lacks an id (the VLAN was dropped from the list) or lists the whole range 1 to 4094 instead of just the intended ids (the restriction was lost: Cisco's trunk guide says all VLAN IDs 1 to 4094 are allowed by default, andallis the configuration keyword, not what the show command prints).show vlan briefshows each VLAN's name, status and ports: every intended VLAN exists and is active, and access ports sit in the intended VLAN; a missing row or a status other than active is a failure. - STP (Spanning Tree Protocol) state:
show spanning-tree rootandshow spanning-tree vlan <id>must show that the intended switch is root for each VLAN, with no port in an unexpected blocking state (a port STP deliberately switches off to prevent a loop) and no new inconsistent ports. A broken result is a different switch being root, which usually means someone's priority setting changed. - Connectivity smoke tests: from each switch ping its default gateway, a host in each changed VLAN, and a device on the far side of each trunk, comparing success with the baseline taken before the change.
During and after
- Before: capture a baseline (the configs, the trunk and STP outputs, BGP session counts) and refuse to start if the network is already unhealthy.
- During: apply to a canary first, run the same assertions after each batch, stop at the first failed assertion, and use a timed revert on the device where the platform supports it.
- After: compare with the baseline, then watch alarms for a soak period (a deliberate waiting time under normal load before calling the change done). Slow faults (a flapping link that repeatedly goes up and down, a route leak where routes are advertised to a neighbour that should not receive them, a memory leak) only appear with time.
Pitfalls
- Testing only that the push succeeded: success means the device accepted the lines, not that the network behaves.
- A lab that differs from production in software version: pin the same image.
- Letting the lab share a management path with production.
Unlock Full Question Bank
Get access to all 43 Network Automation and Software-Defined Networking interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.