Battle-tested Ansible playbooks for safe rolling BGP changes on Cisco IOS‑XR

Battle-tested Ansible playbooks for safe rolling BGP changes on Cisco IOS‑XR

Rolling BGP changes on IOS‑XR look easy until you hit the real constraints: long commit times, route-policy blast radius, BFD interactions, RPKI state, multi-vendor edges, and the fact that “one wrong neighbor change” can leak or withdraw hundreds of thousands of routes. This post focuses on battle-tested ansible patterns for making changes safely, repeatably, and with tight verification/rollback loops.

Change strategy: canary groups, maintenance windows, and preconditions

1) Segment the network into “risk domains”

Do not roll BGP changes across a whole region as a single batch. Create inventory groups aligned to operational blast radius:

  • canary: 1–2 routers (or one per POP/leaf-spine block)
  • wave1 / wave2 / wave3: increasing size
  • critical: route reflectors, Internet edge, DCI border (often last, or separate runbooks)

Example inventory idea:

  • xr_canary
  • xr_wave1
  • xr_wave2
  • xr_rr (route reflectors)
  • xr_edge (transit/peering)

Then enforce ordering with ansible serial and explicit plays per group.

2) Use maintenance windows, but don’t rely on them

Maintenance windows reduce human surprise, not technical risk. A battle-tested approach is:

  • Schedule the window
  • Enforce preconditions (below)
  • Roll canary
  • Verify stability (not just “BGP is up”)
  • Continue waves only if gates pass

3) Preconditions checklist (automatable)

Gate the run before touching config:

  • Device reachable and authenticated
  • No outstanding config lock / commit in progress
  • BGP process healthy (no large-scale churn already happening)
  • Memory/CPU not in distress (avoid “commit won’t complete” scenarios)
  • For route-policy changes:
  • Confirm expected prefix counts (baseline snapshots)
  • Confirm RPKI state (if used) isn’t already degraded
  • For neighbor changes:
  • Confirm peer is stable (no recent flaps)
  • Confirm BFD/session timers are not mid-migration elsewhere

You can encode these as read-only tasks that must succeed before configuration tasks run.


Playbook patterns: idempotent templates, check-mode, async commits

IOS‑XR automation pitfalls usually come from mixing imperative CLI pushes with weak verification. Prefer model-driven or structured config when possible, but XR CLI templates can be safe if you enforce idempotence and verification.

Pattern A: Idempotent configuration rendering

Use Jinja2 templates for IOS‑XR config snippets, and push with a module that supports “replace lines” semantics. For IOS‑XR, common choices include:

  • cisco.iosxr.iosxr_config (CLI-based, commit aware)
  • NETCONF/YANG (more rigorous, but heavier operationally)

Keep templates minimal and scoped. Don’t render the whole BGP config unless you truly intend to manage it end-to-end.

Pattern B: Check-mode as a first-class stage

In practice:

  1. Run --check --diff against canary only
  2. Review diff (ideally posted to change review tooling)
  3. Run live canary apply
  4. Expand waves

Check-mode isn’t perfect (network modules vary), but it catches template errors and unintended diffs.

Pattern C: Async design for long-running commits

XR commits can take time, especially with large RIBs, policy changes, or route refresh. A useful approach:

  • Launch commit as an async job
  • Poll completion
  • Timebox it (avoid hanging changes)

Also add throttle/serial to prevent committing on too many boxes at once.

Example playbook: rolling route-policy + neighbor changes with gates and rollback hooks

Notes:
- This example uses CLI verification commands; adapt to your environment (RRs, add-path, BFD, RPKI, etc.).
- Treat “route advertised” checks carefully: they can be expensive on large tables. Sample a subset or use policy-based counters/telemetry where possible.

yaml
---
- name: Rolling BGP change on IOS-XR (canary then waves)
  hosts: xr_canary
  gather_facts: no
  serial: 1
  vars:
    change_id: "chg-2026-01-bgp-policy-tune"
    commit_timeout_sec: 600
    expected_up_neighbors_min: 10
    max_allowed_flaps_5m: 0

    # Example knobs (keep these scoped)
    bgp_asn: 65000
    peer_group: "TRANSIT_V4"
    neighbor_ip: "192.0.2.1"

  tasks:
    - name: Preconditions - ensure BGP summary is available
      cisco.iosxr.iosxr_command:
        commands:
          - "show bgp summary"
          - "show configuration lock"
      register: precheck

    - name: Preconditions - fail if config lock exists
      ansible.builtin.fail:
        msg: "Config lock present; aborting change."
      when: "'Configuration is locked' in (precheck.stdout[1] | default(''))"

    - name: Snapshot - capture baseline BGP summary
      cisco.iosxr.iosxr_command:
        commands:
          - "show bgp summary"
          - "show bgp neighbors {{ neighbor_ip }} | include BGP state|Last read|Last write"
      register: baseline

    - name: Render candidate config snippet (route-policy + neighbor)
      ansible.builtin.template:
        src: "templates/bgp_change_iosxr.j2"
        dest: "/tmp/{{ inventory_hostname }}-{{ change_id }}.cfg"

    - name: Push candidate config (merge) - NO COMMIT yet (staged)
      cisco.iosxr.iosxr_config:
        src: "/tmp/{{ inventory_hostname }}-{{ change_id }}.cfg"
        match: line
        replace: line
        # Some environments prefer commit in a separate step for better control
      register: cfg_push

    - name: Commit (async) - timeboxed
      cisco.iosxr.iosxr_config:
        lines:
          - "commit"
      async: "{{ commit_timeout_sec }}"
      poll: 0
      register: commit_job

    - name: Wait for commit completion
      ansible.builtin.async_status:
        jid: "{{ commit_job.ansible_job_id }}"
      register: commit_status
      until: commit_status.finished
      retries: "{{ (commit_timeout_sec // 10) | int }}"
      delay: 10

    - name: Immediate verification - BGP summary after change
      cisco.iosxr.iosxr_command:
        commands:
          - "show bgp summary"
          - "show bgp neighbors {{ neighbor_ip }} | include BGP state|Last read|Last write"
      register: post

    - name: Gate - require neighbor to be Established
      ansible.builtin.fail:
        msg: "Neighbor {{ neighbor_ip }} not Established after commit; trigger rollback."
      when: "'Established' not in (post.stdout[1] | default(''))"
      notify: rollback_now

    - name: Gate - require minimum number of up neighbors (basic sanity)
      ansible.builtin.assert:
        that:
          - post.stdout[0] is search("BGP summary")
        fail_msg: "BGP summary output unexpected; cannot validate safely."

  handlers:
    - name: rollback_now
      listen: rollback_now
      block:
        - name: Attempt immediate rollback to previous config (commit replace / rollback)
          cisco.iosxr.iosxr_command:
            commands:
              # IOS-XR rollback options vary by operational practice.
              # Common patterns include "rollback configuration last 1" then "commit"
              - "rollback configuration last 1"
              - "commit"
        - name: Capture debug outputs for incident analysis
          cisco.iosxr.iosxr_command:
            commands:
              - "show logging | last 100"
              - "show bgp summary"
              - "show bgp neighbors {{ neighbor_ip }}"
      rescue:
        - name: Escalate - rollback failed, require manual intervention
          ansible.builtin.fail:
            msg: "Rollback attempt failed; stop further waves."

And an example templates/bgp_change_iosxr.j2 snippet:

jinja2
router bgp {{ bgp_asn }}
 neighbor-group {{ peer_group }}
  address-family ipv4 unicast
   route-policy SET_LOCALPREF_200 in
!
neighbor {{ neighbor_ip }}
 use neighbor-group {{ peer_group }}
!
route-policy SET_LOCALPREF_200
  set local-preference 200
  pass
end-policy

Safe deployment mechanics: staged push, live verification, health-check gates

1) Staged push: separate “load” from “commit”

A reliable operational pattern:

  • Load candidate config (merge/replace lines)
  • Validate device state (pre-commit checks)
  • Commit (async)
  • Verify immediately post-commit
  • Verify again after a stabilization delay (e.g., 2–5 minutes)

This catches delayed failures like route-refresh storms, BFD-induced flaps, or policy-driven churn.

2) Live verification tasks (beyond “Established”)

Useful verification commands on IOS‑XR:

  • Session state and churn:
  • show bgp summary
  • show bgp neighbors <ip>
  • show bgp neighbors <ip> | include Established|Idle|Active|Flap
  • Prefix counters (per neighbor/AF):
  • show bgp neighbors <ip> advertised-routes (use with caution)
  • show bgp neighbors <ip> routes / received-routes (may require policy knobs)
  • Route-policy sanity:
  • show rpl route-policy <name> (or equivalent in your release)
  • BFD:
  • show bfd neighbors
  • Platform health:
  • show processes cpu | include one minute
  • show memory summary
  • show logging | last 50

Gating should be explicit and conservative:
- Fail the play if:
- neighbor goes non-Established
- unexpected drop in accepted prefixes beyond a threshold
- CPU spikes beyond acceptable bounds during commit/refresh
- repeated flaps within a short window

3) Serial + blast-radius controls

Controls that matter in production:

  • serial: 1 for canary, then serial: 2 or serial: 10% for waves
  • max_fail_percentage: 0 for strict aborts
  • Separate plays per group, rather than trying to be clever with dynamic grouping mid-run
  • Set forks conservatively for XR commit-heavy work

Automated rollback and mitigation: detect failures, revert fast, remediate

1) Failure detection: treat symptoms, not just task failures

Many “bad BGP changes” still result in successful commits. Detection should include:

  • Neighbor state degraded (Idle/Active)
  • Prefix counts collapse or balloon (leak)
  • Route-policy not applied as expected
  • Excessive session flaps after the change
  • Unexpected changes in bestpath selection (if you can measure it)

Encode these as asserts that can trigger rollback handlers.

2) Immediate revert paths that work under pressure

Battle-tested rollback options on IOS‑XR (choose one and standardize):

  • rollback configuration last 1 + commit (simple, fast)
  • rollback configuration to <commit-id> (more controlled if you track commit IDs)
  • “Known good” config replace (strongest, but requires canonical source-of-truth)

Important: if your change includes multiple edits (policy + neighbor), rollback should revert the entire atomic change. Avoid partial manual cleanup in the automated path.

3) Automated mitigation for flaps or leaks

If rollback isn’t enough or isn’t immediate, automated mitigations can reduce blast radius:

  • Temporarily apply an outbound deny policy on the affected neighbor-group (contain leak)
  • Drop local-pref on suspect routes (de-preference)
  • Temporarily shut a single eBGP session if it’s the leak source (only when pre-approved)

These mitigations should be explicit “break glass” tasks and require a clear operator decision (e.g., -e break_glass=true), because they can also cause outages.


Post-deploy validation and metrics: telemetry, logs, and incident-learned checks

1) Integrate telemetry (gNMI/NETCONF/SNMP) for objective validation

CLI checks are necessary but not sufficient at scale. Collect:

  • BGP session state changes (per neighbor)
  • Prefix counters (accepted/advertised) per AF
  • CPU/memory during commit and route-refresh windows
  • Interface drops/errors if BGP rides unstable links

Practical integrations:

  • gNMI streaming for neighbor state + counters (best for near-real-time)
  • NETCONF polls for structured operational data (depends on platform/model maturity)
  • SNMP for quick compatibility and baseline counters (less expressive)

At minimum, write play results (who changed, when, commit result, key counters) to a log sink.

2) Log decisions and checkpoints

A simple but effective practice:

  • Record baseline outputs (BGP summary, neighbor details)
  • Record post-change outputs at T+0 and T+5m
  • Record whether gates passed, and why a rollback happened

This makes incident review and continuous improvement possible.

3) Lessons learned from real incidents (translated into checks)

Common failure modes and the checks that prevent repeats:

  • Route-policy typo turns “pass” into “drop”
  • Add: prefix-count threshold gates; test route-policy rendering in check-mode/diff
  • Community match too broad causes leak
  • Add: advertised-route sampling to a known test prefix-set; outbound policy counters (telemetry)
  • Commit completes but triggers route-refresh storm
  • Add: CPU gates + post-commit stabilization delay + wave spacing
  • Changing neighbor-group affects unexpected neighbors
  • Add: inventory mapping (which peers inherit the group) and assert expected neighbor list before commit

Sample XR debug/inspection commands during incident response:

text
show bgp summary
show bgp neighbors 192.0.2.1
show bgp neighbors 192.0.2.1 | include Last reset|Flap|Notification
show logging | include BGP|RPL|ROUTE
show processes cpu | exclude 0.00
show memory summary
show route-policy SET_LOCALPREF_200
show bfd neighbors

Common pitfalls

  • Treating “commit success” as “change success”: BGP can be broken with a perfectly successful commit.
  • Rolling too fast: a route-policy change can cause delayed churn; build in stabilization time.
  • Over-scoped templates: managing the entire BGP stanza increases unintended diffs and risk.
  • Verification commands that are too expensive: advertised-routes on full tables can be slow; sample, filter, or use telemetry counters.
  • No consistent rollback mechanism: decide and standardize on one rollback method (and test it).
  • Ignoring inheritance: neighbor-groups and route-policies can affect more peers than intended—assert the impacted set before changes.
  • No baselines: without baseline prefix/session metrics, it’s hard to know what “healthy” looks like.

Key takeaways

  • Use canary + waves + strict gates to control blast radius for BGP changes.
  • Treat preconditions, commit handling, verification, and rollback as a single workflow, not separate scripts.
  • Design ansible playbooks to be idempotent, check-mode friendly, and timeboxed with async commits.
  • Verification must include session health + prefix sanity + platform health, not just “Established”.
  • Build automated rollback and (optional) break-glass mitigations, and validate with telemetry where possible.