An Introduction to Configuring Policy-Based Routing on Cisco Routers

Policy-Based Routing (PBR) is an essential feature that network administrators leverage to enhance the flexibility and control of routing decisions in modern network infrastructures. Unlike traditional routing, which depends heavily on destination-based decisions, PBR empowers network engineers to customize how traffic is forwarded based on a wide range of factors, such as source address, protocol type, and even time of day. This flexibility is particularly valuable in today’s dynamic network environments, where applications like cloud services, video conferencing, and real-time communication compete for limited bandwidth.

This guide provides a detailed breakdown of PBR, explaining its key functionalities, use cases, and how it is implemented in a network environment. The goal is to equip network administrators with a deep understanding of how to configure and optimize PBR for their infrastructure, using real-world examples and best practices. By the end of this article, you will have a solid foundation in PBR, which will help you make better routing decisions based on the unique needs of your network.

Traditional Routing vs. Policy-Based Routing

In traditional IP routing, routing decisions are typically made based on destination IP addresses, hop count, and other metrics like bandwidth or administrative distance. Routing protocols such as RIP, OSPF, and EIGRP determine the best path to a destination network by evaluating these factors. While this method works well in simple environments, it does not provide the flexibility needed for complex, multi-service networks.

Policy-Based Routing addresses this limitation by allowing administrators to define policies that determine how specific traffic flows should be handled. Instead of relying solely on the destination IP address, PBR can evaluate the source IP, application type, time of day, and even user-defined attributes. This provides a more granular control over how traffic is routed through the network, making it possible to apply different routing policies for different types of traffic.

For example, consider a scenario where a company needs to route VoIP traffic over a high-speed, low-latency link, while general web traffic can be sent over a more cost-efficient connection. Policy-Based Routing makes this possible by allowing engineers to create policies that prioritize certain types of traffic, ensuring that critical services receive the necessary bandwidth and performance.

Key Use Cases for Policy-Based Routing

Policy-based routing is particularly useful in environments that require more advanced routing decisions. Some common use cases include:

  1. Traffic Prioritization for Business Applications: In organizations where multiple applications vie for network resources, PBR can ensure that high-priority traffic like VoIP, video conferencing, or cloud applications receives preferential treatment. This can help maintain performance levels even when the network is congested. 
  2. Multi-WAN Setups: For businesses with multiple internet connections, PBR allows administrators to control which traffic goes through which WAN link. For example, you could route business-critical traffic through a high-speed, dedicated WAN link, while non-essential traffic uses a less expensive broadband connection. This can improve both redundancy and cost-effectiveness. 
  3. Segregating Departmental Traffic: Companies often have different departments with varying network needs. For example, the engineering team may require higher bandwidth and lower latency than the marketing team. With PBR, administrators can route traffic from specific departments to specific links based on the network demands. 
  4. Time-Based Traffic Control: In many cases, certain traffic, like backup data, may only need to flow during off-peak hours. PBR enables administrators to configure time-based policies that automatically route traffic through less expensive or lower-priority links during non-business hours, reducing costs and optimizing network performance. 

By enabling traffic management based on customized rules, PBR allows network administrators to optimize resource usage, improve network performance, and prioritize services that are crucial to the business.

Cisco Implementation of Policy-Based Routing

In Cisco environments, Policy-Based Routing is typically configured using a combination of Access Control Lists (ACLs), Route Maps, and Interface Configuration. This approach provides the flexibility to define which traffic is subject to policy-based routing and how it should be handled.

  1. Access Control Lists (ACLs): ACLs are used to identify the traffic that will be affected by the policy. An ACL can be based on attributes like source or destination IP address, protocol type, or other factors that define the characteristics of the traffic. In our example, we would create an ACL to match the traffic from a specific department or application that needs to follow a specific route. 
  2. Route Maps: A Route Map is used to define the policies that control how traffic is handled once it matches the conditions specified in the ACL. Each Route Map consists of multiple sequence statements, where each statement defines a routing rule. These rules could specify the next hop or interface through which traffic should be forwarded. 
  3. Interface Configuration: Once the ACL and Route Map have been configured, they need to be applied to the relevant interfaces. This involves associating the Route Map with an ingress interface, ensuring that traffic entering the router through that interface is evaluated and routed according to the defined policies. 

A Real-World Example of Policy-Based Routing

Consider a scenario in which a company has two WAN connections: a high-speed, low-latency link (Serial0/0) and a slower, cost-effective link (Serial0/1). The IT department needs access to cloud services and requires a fast connection, while general traffic can be routed through the slower link. In this case, Policy-Based Routing allows administrators to create a policy that sends all traffic from the IT department through the faster link, while traffic from other departments uses the slower link.

Let’s assume the IT department uses the 10.1.0.0/16 subnet, and all other traffic originates from different subnets, such as 10.2.0.0/16.

Step 1: Creating the Access List

The first step in configuring Policy-Based Routing is to create an Access List (ACL) that matches the traffic to which the policy will apply. For this example, we need to target the IT department’s traffic, which uses the 10.1.0.0/16 subnet.

Router(config)# access-list 50 permit 10.1.0.0 0.0.255.255

 

This ACL allows traffic from the 10.1.0.0/16 subnet to be matched and processed by the policy.

Step 2: Defining the Route Map

Next, we define a Route Map that will apply the desired policy. In this case, we want the IT department’s traffic to be routed through the high-speed link (Serial0/0).

Router(config)# route-map IT-Fast permit 10

Router(config-route-map)# match ip address 50

Router(config-route-map)# set interface serial0/0

 

This Route Map matches the traffic defined by ACL 50 (the IT department’s traffic) and routes it through the Serial0/0 interface, which is the high-speed WAN link.

Step 3: Applying the Route Map to an Interface

Finally, we apply the Route Map to an ingress interface. Assuming traffic enters the router through the FastEthernet0/0 interface, we would apply the Route Map to that interface:

Router(config)# interface fastEthernet0/0

Router(config-if)# ip policy route-map IT-Fast

 

At this point, all inbound traffic on the FastEthernet0/0 interface will be evaluated against the IT-Fast Route Map. If the traffic matches the policy, it will be forwarded through the high-speed WAN link.

Verification and Monitoring

After configuring Policy-Based Routing, it’s important to verify that the policy is working as expected. One way to do this is by using the show route-map command to view the route map’s statistics, including how many packets matched each sequence.

Router# show route-map

 

The output will show the match counts and applied policies, helping administrators verify that traffic is being routed as intended.

Important Considerations for Using Policy-Based Routing

While Policy-Based Routing offers powerful control over traffic, it comes with a few trade-offs that administrators must be aware of:

  1. Processing Overhead: Unlike traditional routing, which uses hardware-based acceleration, Policy-Based Routing often operates in the software forwarding path, requiring more CPU resources. In environments with heavy traffic or complex policy rules, this can result in increased latency and reduced performance. 
  2. Routing Table Ignored: By default, Policy-Based Routing bypasses the standard routing table. This provides flexibility but can lead to issues if the next-hop IP becomes unreachable. It’s important to implement fallback mechanisms to avoid blackhole routing. 
  3. Limited to Inbound Interfaces: PBR can only be applied to traffic entering a router, not exiting it. This limitation requires careful planning of where policies should be placed within the network topology. 

 

Advanced Policy-Based Routing Techniques in Cisco Networks

Introduction to Advanced Policy-Based Routing

In the first part of this series, we explored the basics of Policy-Based Routing (PBR) and its importance in enabling customized traffic forwarding based on specific network requirements. In this second part, we will dive deeper into more advanced PBR features and their practical applications in Cisco networks. While the foundational concepts focused on basic route maps, ACLs, and interface configurations, advanced PBR involves more sophisticated techniques such as conditional matching, route-map integration with NAT, load balancing, and using IP SLA for dynamic failover.

As networks become more complex with the rise of cloud services, real-time communications, and software-defined environments, administrators must employ more refined PBR strategies to optimize network traffic. This part will discuss how to configure advanced features, providing network engineers with the tools they need to handle more complex routing scenarios.

Conditional Matching with Route Maps

Route maps in Cisco IOS act as conditional statements that allow for more granular traffic control. By default, a route map matches traffic based on an Access Control List (ACL). However, in complex networks, you may want to apply multiple conditions or criteria for traffic selection. Cisco’s route map functionality allows for conditional logic similar to “if-else” statements, enabling you to evaluate traffic based on multiple factors such as source IP, destination IP, protocol type, packet size, and more.

Example: Routing HTTP Traffic for Marketing Department

Imagine an organization that wants to route all HTTP traffic from the marketing department (IP range: 10.3.0.0/16) over a dedicated ISP link for analytics purposes. Non-HTTP traffic from the same subnet can go over a general-purpose WAN link. By using advanced matching in the route map, you can easily define these routing conditions.

Step 1: Define an Extended Access List

The first step is to create an extended ACL that matches only HTTP traffic (port 80) from the marketing department:

Router(config)# access-list 101 permit tcp 10.3.0.0 0.0.255.255 any eq 80

 

This ACL ensures that only HTTP traffic from the 10.3.0.0/16 subnet is selected.

Step 2: Create a Route Map with Extended Matching

Next, create a route map that applies a routing policy for this traffic:

Router(config)# route-map Marketing-HTTP permit 10

Router(config-route-map)# match ip address 101

Router(config-route-map)# set interface Serial0/2

 

In this configuration, the route map will route all HTTP traffic from the marketing department (as defined by ACL 101) through the Serial0/2 interface, which is connected to the dedicated ISP link.

Step 3: Add More Conditions in the Route Map

You can also add more match conditions to further refine the routing decision. For example, you could route traffic based on packet size, input interface, or protocol type. To match packets of a certain size, you could use the following configuration:

Router(config-route-map)# match length 100 1500

 

This command ensures that only packets within the specified length range are routed according to the policy.

Using Next-Hop IP vs. Set Interface

In PBR configurations, administrators can choose between two primary actions for defining how matched traffic is routed: specifying a next-hop IP address or setting an egress interface. Each of these actions has specific use cases and implications.

Set Next-Hop IP: This action forwards the traffic to a specific next-hop IP address. It’s useful when you want the router to forward traffic to an external device (such as a firewall or another router). The router will perform a recursive lookup to determine the best interface for the next-hop IP.

Example:

Router(config-route-map)# set ip next-hop 192.168.100.1

Set Interface: This action forces the router to use a specific interface for forwarding traffic, bypassing the routing table. It is typically used in point-to-point WAN environments where no intermediate router or next-hop IP is required.

Example:

Router(config-route-map)# set interface Serial0/1

Choosing between these two actions depends on the network topology and the specific requirements of the routing decision. In general, setting the next-hop IP is more flexible, while setting the interface is used in simpler setups.

Tracking Next-Hop Availability with IP SLA

A key limitation of traditional Policy-Based Routing is the inability to handle dynamic failover scenarios. If a specified next-hop becomes unavailable, traffic might still be routed to the failed destination, causing service disruptions. To address this, Cisco has integrated PBR with IP SLA (Service Level Agreements) and object tracking, which allows routers to dynamically verify the reachability of a next-hop IP address before forwarding traffic.

Example: Using IP SLA to Track Next-Hop Availability

In this example, we configure an IP SLA probe to send ICMP pings to the next-hop IP (192.168.100.1) and track its availability. If the next-hop becomes unreachable, the router will automatically fall back to an alternate routing path.

Step 1: Configure the IP SLA Probe

Router(config)# ip sla 1

Router(config-ip-sla)# icmp-echo 192.168.100.1

Router(config-ip-sla)# frequency 10

Router(config-ip-sla)# exit

Router(config)# ip sla schedule 1 start-time now life forever

 

This configuration sends ICMP ping requests every 10 seconds to the next-hop IP address 192.168.100.1.

Step 2: Track the SLA Status

Now, we configure object tracking to monitor the status of the IP SLA probe:

Router(config)# track 1 ip sla 1 reachability

 

This tracking object monitors the reachability of the next-hop IP. If the next-hop becomes unreachable, the tracking object will report a “down” status, prompting the router to adjust its routing decision.

Step 3: Update the Route Map to Use the SLA Tracking Object

Finally, we update the route map to use the tracking object. If the next-hop IP is reachable, the router will forward traffic to it. If it becomes unreachable, the router will fall back to the default routing table.

Router(config)# route-map SLA-Policy permit 10

Router(config-route-map)# match ip address 110

Router(config-route-map)# set ip next-hop verify-availability 192.168.100.1 track 1

 

This configuration ensures that the router will only forward traffic to the next-hop IP if it is reachable, providing more reliable and dynamic routing behavior.

Policy-Based Routing with NAT Integration

In environments that use Network Address Translation (NAT), Policy-Based Routing can be used in conjunction with NAT to direct traffic through different WAN links and assign specific public IPs based on the routing decision. For example, certain users might be routed through one WAN link and assigned a specific public IP, while others might use a different WAN link and public IP.

Example: Split NAT Based on Source Subnet

In this case, we want to route finance users (10.10.10.0/24) through WAN1 and assign them a specific public IP (209.165.200.1), while all other users will use WAN2 and get a different public IP (209.165.201.1).

Step 1: Define NAT Pools

First, define two NAT pools for the different public IP addresses:

ip nat pool FINANCE-PUBLIC 209.165.200.1 209.165.200.1 netmask 255.255.255.0

ip nat pool GENERAL-PUBLIC 209.165.201.1 209.165.201.1 netmask 255.255.255.0

 

Step 2: Create ACLs to Identify Traffic

Next, create ACLs to match traffic from the finance department and other users:

access-list 10 permit 10.10.10.0 0.0.0.255

access-list 20 permit any

 

Step 3: Apply NAT Based on Source ACLs

Now, configure NAT to use the appropriate pool based on the source ACL:

ip nat inside source list 10 pool FINANCE-PUBLIC

ip nat inside source list 20 pool GENERAL-PUBLIC

 

Step 4: Apply PBR for Traffic Segregation

Finally, apply a PBR route map to direct traffic from the finance department through Serial0/0 (WAN1) and all other users through Serial0/1 (WAN2):

IP policy route-map Finance-Policy

 

This integration of PBR and NAT ensures that traffic from specific subnets is routed to the appropriate WAN link and translated to the correct public IP address.

Load Balancing with Policy-Based Routing

While Policy-Based Routing does not support automatic load balancing like Equal-Cost Multi-Path (ECMP), it can still be configured to distribute traffic manually across multiple paths. For example, traffic from different subnets or users can be routed through different WAN links, providing load balancing at the application level.

Example: Load Balancing by Source Subnet

In this example, traffic from Subnet A (10.10.0.0/24) will be routed through ISP1 (Serial0/0), while traffic from Subnet B (10.20.0.0/24) will go through ISP2 (Serial0/1).

Step 1: Define ACLs for Traffic Segmentation

access-list 101 permit ip 10.10.0.0 0.0.0.255 any

access-list 102 permit ip 10.20.0.0 0.0.0.255 any

 

Step 2: Create Route Maps for Each Subnet

route-map LB-A permit 10

match ip address 101

set ip next-hop 192.0.2.1

 

route-map LB-B permit 10

match ip address 102

set ip next-hop 192.0.2.2

 

Step 3: Apply Route Maps to the Interface

Apply these route maps to the inbound interface, ensuring that traffic from each subnet follows the appropriate WAN link:

interface GigabitEthernet0/1

IP policy route-map LB-A

 

interface GigabitEthernet0/2

IP policy route-map LB-B

 

This configuration manually distributes traffic between two WAN links, providing a basic form of load balancing.

Verification and Troubleshooting

As with any routing configuration, verifying and troubleshooting are crucial to ensure that your PBR configuration works as intended. Useful commands include: Show route-map: Check the hit counters and sequence details of your route maps.

 

  • Show IP policy: Verify that the route map is applied to the correct interfaces. 
  • Debug IP policy: Inspect real-time packet matches (use with caution, as it can be CPU-intensive). 
  • Show track: Monitor the status of SLA-based next-hop tracking. 

Real-World Applications and Design Considerations for Policy-Based Routing in Cisco Networks

Introduction to Real-World Applications of Policy-Based Routing

In the previous sections of this series, we discussed the basics and advanced techniques of Policy-Based Routing (PBR), focusing on how network administrators can use PBR to create more flexible, efficient, and resilient routing policies. In this part of the series, we will explore the practical applications of PBR in real-world networks, including enterprise environments, multi-WAN configurations, and cloud optimization. We will also cover the best practices for implementing PBR, as well as common pitfalls to avoid when designing and deploying PBR policies.

Policy-Based Routing is not just a theoretical concept; it is widely used in production networks to manage complex traffic patterns, enforce compliance, enhance performance, and ensure security. Whether it’s for prioritizing business-critical applications, routing traffic based on departmental needs, or optimizing cloud-based services, PBR plays a vital role in modern network design.

Policy-Based Routing in Enterprise Network Design

In enterprise networks, Policy-Based Routing is often used to enforce specific routing decisions that go beyond the capabilities of traditional routing protocols. Unlike standard routing, which makes forwarding decisions based solely on destination IP addresses, PBR allows for more granular control by evaluating additional packet attributes such as source IP, application type, protocol, and even time of day.

Some of the most common enterprise use cases for PBR include:

  1. Enforcing Application-Specific Paths 

Many organizations rely on business-critical applications that require low latency and high bandwidth. PBR allows network administrators to ensure that these applications are routed over the most suitable paths, thereby ensuring performance and availability.

For example, an organization may have cloud-based software (e.g., customer relationship management systems) that requires a high-speed, low-latency connection. By using PBR, administrators can route traffic from specific applications through a dedicated link with higher priority, ensuring that performance is not compromised during peak traffic periods.

  1. Sending Traffic to Security Appliances 

In compliance-driven environments, security inspection often needs to occur before traffic reaches the internet. For example, HTTP and HTTPS traffic might need to pass through a security appliance for filtering and logging before being allowed access to external networks. PBR can be used to route specific traffic types (e.g., web traffic) to a next-generation firewall (NGFW) or intrusion prevention system (IPS) for inspection.

Here’s how it could be configured:

  • Define an ACL that matches HTTP and HTTPS traffic. 
  • Create a route map to direct that traffic to the NGFW. 
  • Apply the route map to the appropriate interface to enforce the policy. 
  1. Routing Traffic to Different ISPs for Different Departments 

Many large organizations maintain multiple internet connections for reasons such as redundancy, performance optimization, and cost management. PBR can be used to route traffic from different departments or user groups to different ISPs. For instance, the finance department might need to use a dedicated ISP for secure transactions, while the marketing department can use a less expensive connection for general browsing and email.

The configuration could be as follows:

  • Create an access list for each department’s subnet. 
  • Define a route map that sends traffic from the finance department through one ISP, while traffic from other departments goes through a different ISP. 
  1. Time-Based Routing for Off-Peak Traffic 

Another useful feature of PBR is its ability to perform time-based routing. This can be especially beneficial for organizations that need to route traffic based on different business hours. For example, backup traffic or software updates can be scheduled to occur during off-hours to minimize the impact on production traffic.

For this purpose, administrators can define time-based ACLs and route maps to ensure that traffic is routed according to a predefined schedule.

Common Real-World Use Cases for Policy-Based Routing

  1. Split ISP Routing for Departments 

In large organizations, it’s common to have different departments that require varying levels of internet access. PBR allows you to direct traffic from specific subnets to specific ISPs, ensuring that departments with more stringent requirements (e.g., finance) receive the best possible performance, while other departments (e.g., marketing) are routed through a more cost-effective link.

Here’s an example configuration:

  • Engineering subnet (10.10.10.0/24) should go through ISP1 (192.0.2.1) for better performance. 
  • Finance subnet (10.20.20.0/24) should go through ISP2 (198.51.100.1) for compliance reasons. 

The configuration steps would involve creating access lists for each subnet and then defining a route map for each department, directing traffic through the appropriate ISP.

  1. Sending Traffic to Security Appliances 

In many enterprise networks, security appliances such as firewalls and intrusion detection systems (IDS) must inspect certain types of traffic before it reaches its destination. For example, HTTP and HTTPS traffic can be routed through a security appliance for inspection.

The ACL for matching HTTP and HTTPS traffic would look like this:

access-list 110 permit tcp any any eq 80

access-list 110 permit tcp any any eq 443

 

The route map would then send this traffic to the next-hop IP of the firewall:

route-map TO-FIREWALL permit 10

match ip address 110

set ip next-hop 10.1.1.10! IP of the firewall

 

Using PBR for Cloud Optimization

Cloud services have become an essential part of modern enterprise networks, and ensuring that cloud-related traffic is routed efficiently is critical. PBR can be used to direct cloud traffic (such as traffic to SaaS applications like Microsoft 365 or Salesforce) over a dedicated path, optimizing performance and reducing latency.

For example, if your network has multiple WAN links, you can use PBR to route traffic for cloud services over a high-performance link, while other general-purpose traffic uses a less expensive connection. This can be achieved by defining IP prefix lists for known cloud IP ranges and then using route maps to steer the traffic accordingly.

Here’s how you might configure PBR to route cloud traffic:

ip prefix-list OFFICE365 seq 5 permit 13.107.0.0/16

ip prefix-list OFFICE365 seq 10 permit 40.96.0.0/12

route-map CLOUD-PBR permit 10

match ip address prefix-list OFFICE365

set ip next-hop 192.168.100.1! Optimized path

 

Integrating PBR with Virtual Routing and Forwarding (VRF)

In multi-tenant environments, such as data centers or service provider networks, multiple VRFs (Virtual Routing and Forwarding instances) are often used to separate traffic for different customers or departments. PBR can be integrated with VRFs to ensure that traffic is routed appropriately across different VRF instances.

For example, if traffic from VRF A needs to reach DNS servers located in VRF B, PBR can be used to route the traffic through the appropriate path:

route-map PBR-VRF-DNS permit 10

match ip address 150

set ip next-hop 10.200.1.1

 

This configuration enables cross-VRF routing, where the traffic from VRF A is routed to the DNS server in VRF B.

PBR and Quality of Service (QoS)

PBR and QoS often work together to optimize traffic behavior. While PBR is used to classify and route traffic, QoS can be used to prioritize or throttle traffic based on application needs. For example, video traffic can be routed through a low-latency link using PBR, while QoS ensures that the video packets are given high priority over other types of traffic.

An example of integrating PBR with QoS could be:

route-map VIDEO-PBR permit 10

match ip dscp af41

set ip next-hop 192.0.2.1

 

In this case, the video traffic is routed through an optimized path, and QoS ensures that the video packets are prioritized.

Best Practices for Implementing Policy-Based Routing

While PBR is a powerful tool, it’s important to follow best practices when designing and deploying PBR policies to avoid performance issues and misconfigurations. Here are some key best practices to consider:

  1. Minimize PBR Use: PBR should only be used when necessary. It adds complexity to the network, and in most cases, dynamic routing protocols (such as OSPF or EIGRP) can handle routing decisions more efficiently. 
  2. Ensure Route Maps Have a Catch-All Permit Entry: Always include a final permit statement in your route maps to allow unmatched traffic to be processed by the standard routing table. Without this, packets that do not match any criteria will be dropped. 

route-map MY-PBR permit 20

 

  1. Use IP SLA for Dynamic Failover: Always integrate IP SLA to monitor next-hop availability and ensure automatic failover if the primary next-hop becomes unreachable. 
  2. Apply Route Maps to the Correct Interface: PBR is applied only to inbound traffic, so be sure to apply the route map to the correct interface to avoid unexpected behavior. 
  3. Test and Monitor PBR Configurations: Always test your PBR configurations in a controlled environment before applying them in production. Use tools like show route-map, show ip policy, and debug ip policy to verify that traffic is being routed as expected. 

Common Pitfalls to Avoid

  1. Routing Loops: Ensure that route maps are carefully crafted to avoid routing loops. This can happen if policies conflict or create circular routing paths. 
  2. Traffic Blackholing: If a policy directs traffic to a next-hop that becomes unavailable and no failover mechanism is in place, traffic may be blackholed. Always test your failover configurations thoroughly. 
  3. Overloading the CPU: Complex PBR configurations can increase the load on the router’s CPU, especially in high-throughput environments. Make sure your hardware is capable of handling the additional processing required by PBR. 

Conclusion

Policy-Based Routing provides network administrators with fine-grained control over how traffic flows through the network. By using PBR, organizations can enforce specific routing policies for different applications, departments, or services, improving performance, security, and compliance. As we have seen, PBR is applicable in a wide range of scenarios, from traffic prioritization to multi-WAN configurations and cloud optimization.

In the next part of this series, we will explore the integration of Policy-Based Routing with automation tools like Python, RESTCONF, and NETCONF. These technologies enable network engineers to automate PBR configuration and management, making it easier to handle large-scale deployments and dynamic network changes.

Automating Policy-Based Routing with Python, RESTCONF, and NETCONF

Introduction to Automating Policy-Based Routing

As network infrastructures grow in complexity, the manual configuration of Policy-Based Routing (PBR) becomes increasingly inefficient and error-prone. In large-scale environments, where network configurations change frequently and traffic patterns fluctuate, network engineers need tools that can automate the creation, deployment, and management of routing policies. Automation not only accelerates configuration but also reduces the risk of human error, improves consistency, and enhances scalability.

In this part of the series, we explore how to automate Policy-Based Routing (PBR) using programming languages like Python and network automation protocols such as RESTCONF and NETCONF. We will cover the basics of these tools, how they integrate with Cisco network devices, and how you can use them to automate PBR configurations more dynamically and programmatically..

With the evolution of software-defined networking (SDN) and intent-based networking, network automation is becoming an essential part of managing modern networks. Automation tools like Python, RESTCONF, and NETCONF allow network administrators to treat infrastructure as code, making it easier to configure and modify routing policies on the fly. This approach reduces the time spent on manual configurations, improves network reliability, and enables better management of large networks.

Why Automate Policy-Based Routing?

Manual configuration of PBR policies can be cumbersome, especially in large or dynamic environments. Here are some scenarios where automating PBR configuration can be beneficial:

  1. Dynamic Routing Policy Changes: In dynamic networks, routing policies may need to change based on application performance, traffic patterns, or other real-time factors. Automating PBR allows these changes to be made programmatically in response to network conditions. 
  2. Scalability: As networks expand, the number of PBR configurations increases, making manual configuration increasingly impractical. Automation ensures that PBR policies can be consistently applied across multiple devices without requiring direct interaction with each router. 
  3. Frequent Failover Decisions: In networks with high availability requirements, failover decisions based on real-time traffic conditions or device status must be made quickly. Automating PBR ensures that traffic is routed to backup paths without delay in the event of a failure. 
  4. Multi-Device Environments: For networks that span multiple sites or data centers, manually configuring PBR across all devices is time-consuming and error-prone. Automation helps to deploy consistent PBR policies across many routers, ensuring uniformity in traffic management. 

Automation Toolchain Overview

To automate PBR in Cisco networks, network engineers can use a variety of tools. The most commonly used tools for network automation include:

  1. Python: Python is a general-purpose scripting language that is widely used in network automation. It has strong support for libraries like requests for interacting with web APIs, and ncclient for interacting with network devices using NETCONF. Python can be used to build automation scripts that create and deploy PBR policies dynamically. 
  2. RESTCONF: RESTCONF is a RESTful API that allows network administrators to interact with Cisco IOS XE devices using HTTP or HTTPS. RESTCONF provides a simple way to manage device configurations, including access lists, route maps, and interface policies. With RESTCONF, administrators can automate the configuration of PBR policies via a programmatic interface. 
  3. NETCONF: NETCONF is an XML-based protocol that provides a more structured and transactional approach to network device configuration. NETCONF is often used in environments where network configurations are managed as part of a broader orchestration platform. With NETCONF, network engineers can automate PBR by editing the device configuration using structured YANG data models. 
  4. Cisco DevNet Sandbox: Cisco DevNet offers a cloud-based sandbox environment for testing network automation scripts. It allows engineers to experiment with Python, RESTCONF, and NETCONF without impacting live production networks. It’s an excellent tool for learning and testing automation scripts before deploying them in a real environment. 
  5. Ansible/Nornir (Optional): Higher-level network automation frameworks like Ansible and Nornir can be used to run Python scripts in bulk, managing multiple devices at once. These tools allow for greater flexibility and easier orchestration across complex network environments. 

Automating Policy-Based Routing with Python and RESTCONF

One of the most straightforward ways to automate PBR configuration is by using Python and RESTCONF. RESTCONF allows network administrators to interact with Cisco devices via HTTP or HTTPS, sending and receiving data in JSON format. This makes it easy to integrate PBR configuration tasks into Python scripts.

Step 1: Enabling RESTCONF on Cisco Devices

Before you can interact with a Cisco device using RESTCONF, you need to ensure that RESTCONF is enabled on the device. This typically involves enabling the HTTP server and ensuring that the device is configured to accept secure connections.

Here is how you can enable RESTCONF on a Cisco router:

conf t

restconf

ip http secure-server

username netadmin privilege 15 secret cisco123

crypto key generate rsa modulus 2048

show restconf

 

Once RESTCONF is enabled, you can use Python to send HTTP requests to the device’s RESTCONF API and retrieve or modify the configuration.

Step 2: Building a Python Script for PBR Configuration

Using Python, you can send HTTP requests to the Cisco device’s RESTCONF API to configure PBR elements such as access lists, route maps, and interfaces. Below is a simple Python script that demonstrates how to create an access list and configure it for use in PBR.

Python Script Example:

Import requests,

import json

from requests. Auth import HTTPBasicAuth

 

# Define the device credentials and target URL

device = {

    “host”: “10.0.0.1”,

    “port”: “443”,

    “user”: “netadmin”,

    “password”: “cisco123”

}

 

headers = {

    “Content-Type”: “application/yang-data+json”,

    “Accept”: “application/yang-data+json”

}

 

# Define the access list payload

url = f”https://{device[‘host’]}:{device[‘port’]}/restconf/data/Cisco-IOS-XE-native:native/ip/access-list/extended=TRAFFIC-FILTER”

payload = {

    “Cisco-IOS-XE-acl: extended”: [

        {

            “name”: “TRAFFIC-FILTER”,

            “access-list-seq-rule”: [

                {

                    “sequence”: 10,

                    “ace-rule”: {

                        “action”: “permit”,

                        “protocol”: “ip”,

                        “source”: {“any”: [None]},

                        “destination”: {“any”: [None]}

                    }

                }

            ]

        }

    ]

}

 

# Send the request to create the access list

response = requests.put(url, auth=HTTPBasicAuth(device[“user”], device[“password”]), headers=headers, data=json.dumps(payload), verify=False)

 

# Print the response

print(response.status_code)

print(response.text)

 

This script creates an access list called TRAFFIC-FILTER that permits all IP traffic. Once the access list is created, you can proceed to automate other PBR components such as route maps and interface bindings.

Step 3: Automating Route Maps and Interfaces

Once the ACLs are in place, you can use similar Python scripts to create route maps and bind them to interfaces. RESTCONF provides paths for creating route maps, setting up match conditions, and applying policies to interfaces.

For example, here’s how you can create a route map and apply it to an interface:

# Define the route map payload

route_map_url = f”https://{device[‘host’]}:{device[‘port’]}/restconf/data/Cisco-IOS-XE-native:native/route-map”

route_map_payload = {

    “Cisco-IOS-XE-native:route-map”: [

        {

            “name”: “PBR-ROUTE-MAP”,

            “route-map-seq-rule”: [

                {

                    “sequence”: 10,

                    “match”: {

                        “ip-address”: “TRAFFIC-FILTER”

                    },

                    “set”: {

                        “interface”: “Serial0/1”

                    }

                }

            ]

        }

    ]

}

 

# Send the request to create the route map

route_map_response = requests.put(route_map_url, auth=HTTPBasicAuth(device[“user”], device[“password”]), headers=headers, data=json.dumps(route_map_payload), verify=False)

print(route_map_response.status_code)

print(route_map_response.text)

 

Once the route map is created, you can apply it to the interfaces that will use it. By automating these tasks, you can ensure that PBR policies are consistently applied across your network.

Step 4: Automating Failover and Monitoring with IP SLA

A common requirement in policy-based routing is the need for dynamic failover, especially in multi-WAN environments. To automate failover, you can integrate PBR with IP SLA (Service Level Agreements) to track the availability of next-hop IPs.

Here’s how you can automate IP SLA configuration using Python and RESTCONF:

# Define the IP SLA probe payload

sla_url = f”https://{device[‘host’]}:{device[‘port’]}/restconf/data/Cisco-IOS-XE-native:native/ip/ip-sla”

sla_payload = {

    “Cisco-IOS-XE-ip-sla:ip-sla”: [

        {

            “sla-id”: 1,

            “icmp-echo”: {

                “destination”: “192.168.100.1”,

                “frequency”: 10

            }

        }

    ]

}

 

# Send the request to create the IP SLA probe

sla_response = requests.put(sla_url, auth=HTTPBasicAuth(device[“user”], device[“password”]), headers=headers, data=json.dumps(sla_payload), verify=False)

print(sla_response.status_code)

print(sla_response.text)

 

This script sets up an IP SLA probe that sends ICMP echo requests to the next-hop IP (192.168.100.1) every 10 seconds. By integrating IP SLA with PBR, you can automatically adjust traffic paths based on the availability of the next-hop, ensuring high network availability.

Automation with NETCONF

While RESTCONF is a simple and effective tool for automating network configurations, NETCONF offers a more structured and transactional approach. NETCONF allows for more detailed control over configuration management using YANG models and XML-based requests.

Here’s an example of how to automate PBR with NETCONF using Python and the ncclient library:

From ncclient import manager

 

# Define the device connection details

device = {

    “host”: “10.0.0.1”,

    “port”: 830,

    “username”: “netadmin”,

    “password”: “cisco123”

}

 

# Create a connection to the device

With the manager.connect(host=device[“host”], port=device[“port”], username=device[“username”], password=device[“password”], hostkey_verify=False) as m:

    # Define the NETCONF filter for creating an ACL

    netconf_filter = “””

    <filter>

        <native xmlns=”http://cisco.com/ns/yang/Cisco-IOS-XE-native”>

            <ip>

                <access-list>

                    <extended>

                        <name>TRAFFIC-FILTER</name>

                        <access-list-seq-rule>

                            <sequence>10</sequence>

                            <ace-rule>

                                <action>permit</action>

                                <protocol>ip</protocol>

                                <source><any/></source>

                                <destination><any/></destination>

                            </ace-rule>

                        </access-list-seq-rule>

                    </extended>

                </access-list>

            </ip>

        </native>

    </filter>

    “””

    # Send the NETCONF request to create the ACL

    reply = m.edit_config(target=”running”, config=netconf_filter)

    print(reply)

 

This NETCONF-based script creates an access list called TRAFFIC-FILTER, just like the RESTCONF example, but using a structured XML configuration.

Conclusion

Automating Policy-Based Routing with Python, RESTCONF, and NETCONF enhances the flexibility, scalability, and reliability of network configurations. By automating the creation and deployment of PBR policies, network engineers can ensure consistent policy application across multiple devices, handle dynamic routing decisions, and improve overall network performance.

As networks become increasingly complex, the ability to automate routine tasks like PBR configuration is essential for modern network management. The use of tools like Python and RESTCONF, combined with platforms like Cisco DevNet and NETCONF, empowers engineers to efficiently manage network routing and respond to changing network conditions in real time.

 

img