SiamCafe.net Blog
Technology

Segment Routing Automation Script สร้างระบบ Network Automation สำหรับ SR-MPLS

segment routing automation script
Segment Routing Automation Script | SiamCafe Blog
2026-01-11· อ. บอม — SiamCafe.net· 1,356 คำ

Segment Routing ?????????????????????

Segment Routing (SR) ???????????? network architecture ?????????????????? source routing ???????????????????????????????????? packet ????????????????????? source node ??????????????? path ????????????????????????????????? ordered list ????????? segments (instructions) ???????????????????????????????????????????????? hop ????????????????????????????????? ??????????????? control plane ???????????????????????? ?????????????????????????????? RSVP-TE ???????????? LDP

SR ?????? 2 data plane ???????????? SR-MPLS ????????? MPLS labels ???????????? segment identifiers (SIDs) ????????????????????? existing MPLS infrastructure, SRv6 ????????? IPv6 extension headers ???????????????????????? segments ?????? IPv6 address ????????????????????? MPLS

???????????????????????? Segment Routing Simplified control plane ????????????????????? LDP/RSVP signaling, Traffic Engineering ???????????????????????? RSVP-TE, Scalable ?????????????????? network ????????????????????????, Programmable ??????????????? path ??????????????????????????????, Automation friendly ????????? controller-based approach ??????????????? ???????????????????????????????????? ISP ????????? data center ????????????????????????????????????????????????????????????????????? SR ????????? traditional MPLS

??????????????????????????????????????????????????? Segment Routing

Configuration ?????????????????? Cisco IOS-XR ????????? Junos

# === Segment Routing Configuration ===

# 1. Cisco IOS-XR ??? SR-MPLS with IS-IS
cat > sr_iosxr.cfg << 'EOF'
! Enable Segment Routing globally
segment-routing
 global-block 16000 23999
!
router isis CORE
 is-type level-2-only
 net 49.0001.0000.0000.0001.00
 address-family ipv4 unicast
  metric-style wide
  segment-routing mpls
  segment-routing prefix-sid-map advertise-local
 !
 interface Loopback0
  passive
  address-family ipv4 unicast
   prefix-sid index 1
  !
 !
 interface GigabitEthernet0/0/0/0
  point-to-point
  address-family ipv4 unicast
   metric 10
  !
 !
 interface GigabitEthernet0/0/0/1
  point-to-point
  address-family ipv4 unicast
   metric 10
  !
!
! TI-LFA (Topology Independent Loop-Free Alternate)
router isis CORE
 address-family ipv4 unicast
  fast-reroute per-prefix
  fast-reroute per-prefix ti-lfa
 !
!
! Verify
! show isis segment-routing label table
! show mpls forwarding
! show isis adjacency
EOF

# 2. Juniper Junos ??? SR-MPLS with OSPF
cat > sr_junos.cfg << 'EOF'
set protocols ospf source-packet-routing
set protocols ospf area 0.0.0.0 interface lo0.0 passive
set protocols ospf area 0.0.0.0 interface lo0.0 source-packet-routing node-segment ipv4-index 1
set protocols ospf area 0.0.0.0 interface ge-0/0/0.0 interface-type p2p
set protocols ospf area 0.0.0.0 interface ge-0/0/1.0 interface-type p2p

set protocols source-packet-routing srgb start-label 16000 index-range 8000
set protocols source-packet-routing node-segment ipv4-index 1

set protocols ospf traffic-engineering
set protocols ospf traffic-engineering advertisement always
EOF

# 3. Arista EOS ??? SR-MPLS with IS-IS
cat > sr_arista.cfg << 'EOF'
segment-routing mpls
  no shutdown
  global-block 16000 23999
!
router isis CORE
  net 49.0001.0000.0000.0003.00
  is-type level-2
  address-family ipv4 unicast
    segment-routing mpls
  !
  segment-routing prefix-sid-map advertise-local
!
interface Loopback0
  isis enable CORE
  node-segment ipv4 index 3
EOF

echo "SR configurations created"

Automation Script ???????????? Python

Python scripts ?????????????????? SR automation

#!/usr/bin/env python3
# sr_automation.py ??? Segment Routing Automation
import json
import logging
from typing import Dict, List

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("sr_auto")

class SRAutomation:
    """Segment Routing Network Automation"""
    
    def __init__(self):
        self.inventory = {}
        self.sid_allocation = {}
        self.next_sid_index = 1
    
    def add_node(self, hostname, loopback_ip, platform, interfaces):
        """Add network node to inventory"""
        sid_index = self.next_sid_index
        self.next_sid_index += 1
        
        self.inventory[hostname] = {
            "loopback": loopback_ip,
            "platform": platform,
            "sid_index": sid_index,
            "prefix_sid": 16000 + sid_index,
            "interfaces": interfaces,
        }
        self.sid_allocation[hostname] = sid_index
        return self.inventory[hostname]
    
    def generate_config(self, hostname):
        """Generate SR configuration for a node"""
        node = self.inventory.get(hostname)
        if not node:
            return {"error": f"Node {hostname} not found"}
        
        if node["platform"] == "iosxr":
            return self._gen_iosxr(hostname, node)
        elif node["platform"] == "junos":
            return self._gen_junos(hostname, node)
        else:
            return {"error": f"Unsupported platform: {node['platform']}"}
    
    def _gen_iosxr(self, hostname, node):
        config = f"""! SR Config for {hostname}
segment-routing
 global-block 16000 23999
!
router isis CORE
 is-type level-2-only
 net 49.0001.{node['loopback'].replace('.', '')}.00
 address-family ipv4 unicast
  metric-style wide
  segment-routing mpls
 !
 interface Loopback0
  passive
  address-family ipv4 unicast
   prefix-sid index {node['sid_index']}
"""
        for iface in node["interfaces"]:
            config += f""" !
 interface {iface['name']}
  point-to-point
  address-family ipv4 unicast
   metric {iface.get('metric', 10)}
"""
        return {"hostname": hostname, "platform": "iosxr", "config": config}
    
    def _gen_junos(self, hostname, node):
        config = f"""# SR Config for {hostname}
set protocols ospf source-packet-routing
set protocols source-packet-routing srgb start-label 16000 index-range 8000
set protocols source-packet-routing node-segment ipv4-index {node['sid_index']}
set protocols ospf area 0.0.0.0 interface lo0.0 passive
set protocols ospf area 0.0.0.0 interface lo0.0 source-packet-routing node-segment ipv4-index {node['sid_index']}
"""
        for iface in node["interfaces"]:
            config += f"set protocols ospf area 0.0.0.0 interface {iface['name']} interface-type p2p\n"
        return {"hostname": hostname, "platform": "junos", "config": config}
    
    def validate_sids(self):
        """Validate SID allocation (no conflicts)"""
        sids = {}
        conflicts = []
        for hostname, node in self.inventory.items():
            sid = node["prefix_sid"]
            if sid in sids:
                conflicts.append({"sid": sid, "nodes": [sids[sid], hostname]})
            sids[sid] = hostname
        
        return {
            "total_nodes": len(self.inventory),
            "sids_allocated": len(sids),
            "conflicts": conflicts,
            "valid": len(conflicts) == 0,
        }

# Demo
sr = SRAutomation()

sr.add_node("PE1", "10.0.0.1", "iosxr", [
    {"name": "GigabitEthernet0/0/0/0", "metric": 10},
    {"name": "GigabitEthernet0/0/0/1", "metric": 20},
])
sr.add_node("P1", "10.0.0.2", "iosxr", [
    {"name": "GigabitEthernet0/0/0/0", "metric": 10},
    {"name": "GigabitEthernet0/0/0/1", "metric": 10},
])
sr.add_node("PE2", "10.0.0.3", "junos", [
    {"name": "ge-0/0/0.0", "metric": 10},
])

# Generate configs
for hostname in sr.inventory:
    result = sr.generate_config(hostname)
    print(f"\n=== {hostname} ({result['platform']}) ===")
    print(result["config"][:200] + "...")

# Validate
validation = sr.validate_sids()
print(f"\nSID Validation: {'PASS' if validation['valid'] else 'FAIL'}")
print(f"Nodes: {validation['total_nodes']}, SIDs: {validation['sids_allocated']}")

Traffic Engineering ???????????? SR-TE

SR Traffic Engineering policies

# === SR-TE Policy Configuration ===

# 1. SR-TE Policy (IOS-XR)
cat > sr_te_policy.cfg << 'EOF'
! SR-TE Policy: Low-Latency Path PE1 ??? PE3
segment-routing
 traffic-eng
  policy LOW-LATENCY-PE3
   color 100 end-point ipv4 10.0.0.3
   candidate-paths
    preference 200
     explicit segment-list SL-LOW-LATENCY
    !
    preference 100
     dynamic
      pcep
      !
      metric
       type latency
      !
     !
    !
   !
  !
  segment-list SL-LOW-LATENCY
   index 10 mpls label 16002
   index 20 mpls label 16003
  !
  segment-list SL-HIGH-BW
   index 10 mpls label 16004
   index 20 mpls label 16003
  !
  ! On-Demand Next-Hop (ODN)
  on-demand color 100
   dynamic
    pcep
    !
    metric
     type latency
    !
   !
  !
  on-demand color 200
   dynamic
    metric
     type igp
    !
    constraints
     bandwidth 1000000
    !
   !
  !
EOF

# 2. Steering traffic into SR-TE Policy
cat > sr_te_steering.cfg << 'EOF'
! BGP Color Community for automatic steering
router bgp 65000
 address-family ipv4 unicast
  network 192.168.1.0/24 route-policy SET-COLOR-100
 !
!
route-policy SET-COLOR-100
 set extcommunity color 100
end-policy
!
! Or use static route
router static
 address-family ipv4 unicast
  192.168.100.0/24 sr-policy LOW-LATENCY-PE3
EOF

# 3. Verify SR-TE
cat > verify_commands.sh << 'EOF'
#!/bin/bash
# IOS-XR Verification Commands
echo "=== SR-TE Verification ==="
echo "show segment-routing traffic-eng policy"
echo "show segment-routing traffic-eng forwarding"
echo "show segment-routing traffic-eng topology"
echo "show segment-routing traffic-eng policy color 100"
echo "show isis segment-routing label table"
echo "show mpls forwarding"
echo "traceroute sr-mpls 10.0.0.3/32"
EOF

echo "SR-TE configured"

Monitoring ????????? Troubleshooting

????????????????????????????????? SR network

#!/usr/bin/env python3
# sr_monitor.py ??? SR Network Monitor
import json
import logging
from typing import Dict, List

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("monitor")

class SRMonitor:
    def __init__(self):
        self.nodes = {}
    
    def health_check(self):
        return {
            "network_status": {
                "total_nodes": 12,
                "sr_enabled": 12,
                "isis_adjacencies": 28,
                "isis_adjacencies_up": 28,
                "sr_te_policies": 8,
                "sr_te_policies_up": 7,
                "sr_te_policies_down": 1,
            },
            "sid_table": {
                "PE1": {"loopback": "10.0.0.1", "sid": 16001, "status": "active"},
                "P1": {"loopback": "10.0.0.2", "sid": 16002, "status": "active"},
                "P2": {"loopback": "10.0.0.3", "sid": 16003, "status": "active"},
                "PE2": {"loopback": "10.0.0.4", "sid": 16004, "status": "active"},
                "PE3": {"loopback": "10.0.0.5", "sid": 16005, "status": "active"},
            },
            "ti_lfa_coverage": {
                "total_prefixes": 45,
                "protected_prefixes": 43,
                "coverage_pct": 95.6,
                "unprotected": ["10.0.100.0/24", "10.0.200.0/24"],
            },
        }
    
    def troubleshooting_guide(self):
        return {
            "sr_sid_not_installed": {
                "symptoms": "Prefix-SID ?????????????????????????????? label table",
                "checks": [
                    "show isis segment-routing label table",
                    "show isis database detail",
                    "show segment-routing mapping-server prefix-sid-map",
                ],
                "common_causes": [
                    "IS-IS/OSPF adjacency down",
                    "SRGB range conflict",
                    "Prefix-SID index ?????????",
                    "Segment routing ?????????????????? enable ?????? IGP",
                ],
            },
            "sr_te_policy_down": {
                "symptoms": "SR-TE policy status down",
                "checks": [
                    "show segment-routing traffic-eng policy detail",
                    "show segment-routing traffic-eng topology",
                    "show pce lsp detail",
                ],
                "common_causes": [
                    "Endpoint unreachable",
                    "Explicit segment-list ?????? SID ????????? invalid",
                    "PCEP session down (?????????????????? PCE)",
                    "Constraint ??????????????????????????? satisfy ?????????",
                ],
            },
            "traffic_not_steered": {
                "symptoms": "Traffic ????????????????????? SR-TE policy",
                "checks": [
                    "show segment-routing traffic-eng forwarding",
                    "show cef [prefix] detail",
                    "show bgp [prefix] detail",
                ],
                "common_causes": [
                    "Color community ??????????????????",
                    "Autoroute ?????????????????? configure",
                    "Static route ?????????????????? point ?????? policy",
                ],
            },
        }

monitor = SRMonitor()
health = monitor.health_check()
print("SR Network Health:")
for key, val in health["network_status"].items():
    print(f"  {key}: {val}")

print(f"\nTI-LFA Coverage: {health['ti_lfa_coverage']['coverage_pct']}%")

guide = monitor.troubleshooting_guide()
print("\nTroubleshooting Guide:")
for issue, info in guide.items():
    print(f"  {issue}: {info['symptoms']}")

CI/CD ?????????????????? Network Automation

Pipeline ?????????????????? deploy SR configuration

# === Network CI/CD Pipeline ===

# GitHub Actions for SR Config Deployment
cat > .github/workflows/sr-deploy.yml << 'EOF'
name: SR Config Deployment

on:
  push:
    branches: [main]
    paths: ['configs/**', 'scripts/**']
  pull_request:
    branches: [main]

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.12'
      
      - name: Install Dependencies
        run: |
          pip install netmiko napalm pyyaml jinja2 pytest
      
      - name: Validate SID Allocation
        run: python scripts/validate_sids.py configs/inventory.yaml
      
      - name: Lint Configs
        run: python scripts/lint_configs.py configs/
      
      - name: Dry Run (Lab)
        if: github.event_name == 'pull_request'
        run: |
          python scripts/deploy.py \
            --inventory configs/inventory.yaml \
            --dry-run \
            --target lab

  deploy-staging:
    needs: validate
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    environment: staging
    steps:
      - uses: actions/checkout@v4
      
      - name: Deploy to Staging
        run: |
          python scripts/deploy.py \
            --inventory configs/inventory.yaml \
            --target staging \
            --commit-confirm 300
      
      - name: Verify Staging
        run: python scripts/verify_sr.py --target staging
      
      - name: Rollback on Failure
        if: failure()
        run: python scripts/rollback.py --target staging

  deploy-production:
    needs: deploy-staging
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v4
      
      - name: Deploy to Production (Rolling)
        run: |
          python scripts/deploy.py \
            --inventory configs/inventory.yaml \
            --target production \
            --rolling \
            --batch-size 2 \
            --commit-confirm 600
      
      - name: Verify Production
        run: python scripts/verify_sr.py --target production
EOF

echo "CI/CD pipeline configured"

FAQ ??????????????????????????????????????????

Q: Segment Routing ????????? MPLS LDP ???????????????????????????????????????????

A: LDP (Label Distribution Protocol) ????????? signaling protocol ?????????????????? IGP ???????????????????????? labels ????????? router ????????????????????? LDP session ????????? neighbor ?????????????????? state ???????????? ??????????????????????????? traffic engineering ?????????????????? ????????????????????? RSVP-TE ??????????????? Segment Routing ????????? IGP (IS-IS/OSPF) ??????????????? distribute SIDs ????????????????????? signaling protocol ??????????????? state ????????????????????????????????? ?????????????????? traffic engineering ??????????????? (SR-TE) ????????????????????? automation ??????????????????????????? ?????? protocol ????????? 3 (IGP+LDP+RSVP-TE) ??????????????? 1 (IGP+SR) network ????????????????????????????????? troubleshoot ????????????????????????

Q: SR-MPLS ????????? SRv6 ??????????????????????????????????

A: SR-MPLS ????????? MPLS labels deploy ?????????????????? existing MPLS network interop ????????? legacy MPLS ????????? overhead ????????? (4 bytes per label) mature ?????? vendor support ??????????????? ??????????????? Service Provider ??????????????? MPLS ???????????????????????? SRv6 ????????? IPv6 headers ????????????????????? MPLS infrastructure programmable ????????????????????? (SRv6 Network Programming) overhead ????????????????????? (128-bit SID) ????????????????????? vendor support ??????????????????????????? ??????????????? greenfield deployments ????????? data center ???????????????????????? SR-MPLS ???????????? safe choice ?????????????????? production SRv6 ??????????????????????????????????????????????????????????????? ecosystem mature

Q: TI-LFA ????????????????????? ??????????????????????????????????

A: TI-LFA (Topology Independent Loop-Free Alternate) ???????????? fast-reroute mechanism ?????????????????? Segment Routing ??????????????? link ???????????? node ????????? TI-LFA ?????? switch traffic ?????? backup path ??????????????? 50ms (sub-second) ???????????????????????????????????? IGP convergence (????????????????????????????????? seconds) TI-LFA ?????????????????? traditional LFA ??????????????? ????????? 100% coverage (protect ?????????????????? prefix ??????????????? topology), ?????????????????????????????? topology ????????? network, ????????? segment routing ??????????????? backup path (push additional SIDs), ??????????????? backup path ??????????????????????????? ????????????????????? manual configure ????????? SP network ?????????????????? SR ????????????????????? TI-LFA ??????????????? sub-50ms failover

Q: Network Automation ?????????????????? SR ????????? tools ?????????????

A: Tools ???????????????????????? Configuration management ????????? Ansible + Jinja2 templates ?????????????????? generate ????????? push configs, Netmiko/NAPALM ?????????????????? device interaction ???????????? SSH Validation ????????? Batfish ?????????????????? config analysis offline, pytest ?????????????????? network testing Monitoring ????????? Telegraf + InfluxDB + Grafana ?????????????????? telemetry, gNMI/gRPC streaming telemetry ?????????????????? real-time Controller ????????? Cisco XTC (XR Transport Controller) ???????????? open-source PCE ?????????????????? SR-TE path computation CI/CD ????????? GitHub Actions ???????????? GitLab CI ?????????????????? config deployment pipeline ???????????????????????? Ansible + Jinja2 + Git ???????????? foundation ??????????????????????????? tools ??????????????????????????????????????????

📖 บทความที่เกี่ยวข้อง

Segment Routing Data Pipeline ETLอ่านบทความ → Segment Routing API Gateway Patternอ่านบทความ → Segment Routing อ่านบทความ → Segment Routing CDN Configurationอ่านบทความ → Segment Routing Consensus Algorithmอ่านบทความ →

📚 ดูบทความทั้งหมด →