Automating VergeOS Network Management with CLI Scripts
A comprehensive guide to managing VergeOS virtual networks through the command line
Introduction
Managing virtual networks in VergeOS through the web UI is great for one-off tasks, but when you're dealing with multiple networks, standardized configurations, or infrastructure-as-code workflows, you need automation. In this post, I'll walk you through two powerful bash scripts I've developed for VergeOS network automation: a network management CLI and a comprehensive test suite.
These scripts leverage the VergeOS API to provide full CRUD (Create, Read, Update, Delete) operations on virtual networks, complete with validation, error handling, and retry logic.
Prerequisites
Before diving into network automation, you'll need to set up secure API access to your VergeOS instance. I've covered this in detail in my previous post: Securing VergeOS API Access with Cloudflare Tunnels and Service Tokens.
What you'll need:
- VergeOS instance with API access
- Cloudflare Tunnel configured for secure access
- Service token credentials (Client ID and Secret)
- The
vergeos-cli-token.shauthentication wrapper (from the previous post)
Once you have these prerequisites in place, you're ready to automate your network management!
Local-Only Option
If you're running these scripts from within your local network and don't need to traverse a Cloudflare Tunnel, I've also created a local version of the toolset that skips the Cloudflare authentication layer.
Local Scripts:
vergeos-cli-local.sh: Handles direct API authentication (replacesvergeos-cli-token.sh)vergeos-network-manager-local.sh: The network manager adapted for local usetest-vergeos-network-manager-local.sh: The test suite for the local version
These scripts function identically to their Cloudflare-enabled counterparts but connect directly to the VergeOS API IP/hostname, making them ideal for internal management servers or jump boxes.
The local scripts are available at the bottom of the article!
Note on SSL: The local CLI script (vergeos-cli-local.sh) includes the --insecure flag for curl commands. This is necessary when connecting to VergeOS nodes via IP address or internal hostnames that use self-signed certificates.
The Network Manager Script
Overview
The vergeos-network-manager.sh script provides a complete command-line interface for managing VergeOS virtual networks. It supports:
- Network Operations: List, show, create, update, delete
- Power Management: Power on/off networks
- Configuration Management: Apply firewall rules and DNS settings
- 50+ Configurable Parameters: From basic settings to advanced features
- Input Validation: Enum validation with helpful error messages
- Retry Logic: Automatic retries for transient failures
Key Features
1. Comprehensive Field Support
The script supports updating over 50 network parameters, organized into categories:
Network Configuration:
- Name, description, enabled status
- Network type (internal, external, DMZ, core, physical, BGP, VPN)
- Layer 2 configuration (VLAN, VXLAN, bonding)
IP Configuration:
- IP address type (static, dynamic, BGP)
- Network CIDR, gateway, router IP
- MTU settings (including jumbo frames)
DHCP Management:
- Enable/disable DHCP server
- DHCP range configuration
- Sequential IP assignment
- Convenient
dhcp_rangeshortcut
DNS Configuration:
- DNS mode (disabled, simple, bind, network)
- DNS server list
- Domain and hostname settings
Advanced Features:
- Statistics and packet tracing
- Rate limiting with configurable units
- Port mirroring
- Gateway monitoring
- PXE boot configuration
2. Smart Defaults
The script defaults to clean, no-color output for easy parsing and logging. Enable colors when you want them:
# Default: clean output
./vergeos-network-manager.sh list
# With colors for terminal viewing
./vergeos-network-manager.sh --color list
3. Robust Error Handling
All operations include:
- API error detection and reporting
- Input validation for enum fields
- Automatic retries for transient failures
- Graceful degradation
Usage Examples
Listing Networks
./vergeos-network-manager.sh list
Output:
=== Virtual Networks ===
[1] DMZ - Type: dmz - Network: 100.64.0.0/16 - IP: N/A
[2] Core - Type: core - Network: 100.96.0.0/24 - IP: N/A
[3] External - Type: external - Network: 192.168.1.0/24 - IP: N/A
[17] kubernetes - Type: internal - Network: 10.0.6.0/24 - IP: 10.0.6.1
Viewing Network Details
./vergeos-network-manager.sh show 17
This returns the complete network configuration in JSON format, including:
- IP addressing and DHCP settings
- DNS configuration
- Attached NICs
- Firewall rules
- Statistics and logs
Creating a New Network
# Simple internal network
./vergeos-network-manager.sh create "Lab Network" internal "10.10.10.0/24"
# Network with DHCP enabled
./vergeos-network-manager.sh create "Dev Network" internal "192.168.100.0/24" "Development environment" true
Updating Network Configuration
The update command is incredibly flexible:
# Set MTU to jumbo frames
./vergeos-network-manager.sh update 17 mtu 9000
# Configure DHCP range (convenient shortcut)
./vergeos-network-manager.sh update 17 dhcp_range 10.0.6.100-10.0.6.200
# Set DNS servers
./vergeos-network-manager.sh update 17 dnslist "192.168.1.250,8.8.8.8"
# Enable statistics
./vergeos-network-manager.sh update 17 statistics true
# Set domain name
./vergeos-network-manager.sh update 17 domain "homelab.local"
# Configure rate limiting
./vergeos-network-manager.sh update 17 rate_limit 1000
./vergeos-network-manager.sh update 17 rate_limit_type "mbytes/second"
Power Management
# Power on a network
./vergeos-network-manager.sh poweron 17
# Power off a network
./vergeos-network-manager.sh poweroff 17
Applying Configuration Changes
# Refresh network configuration (applies firewall rules)
./vergeos-network-manager.sh apply-rules 17
# Refresh network configuration (applies DNS settings)
./vergeos-network-manager.sh apply-dns 17
Both commands use the refresh action with automatic retry logic (up to 3 attempts with 2-second delays).
Deleting Networks
The delete function includes safety features:
- Confirmation prompt
- Automatic power-off before deletion
- Error handling for common issues
./vergeos-network-manager.sh delete 17
Interactive Mode
For a guided experience:
./vergeos-network-manager.sh interactive
This walks you through network creation with prompts for all required fields.
The Test Suite
Why Test Automation?
When building infrastructure automation tools, comprehensive testing is crucial. The test-vergeos-network-manager.sh script provides:
- 27 automated tests across 7 functional areas
- Pass/fail tracking with detailed reporting
- Automatic cleanup of test resources
- CI/CD integration via exit codes
Test Coverage
The test suite validates:
-
Basic Commands (3 tests)
- Help documentation
- Network listing
- Invalid command handling
-
Network Retrieval (3 tests)
- Show existing networks
- Parameter validation
- Non-existent network handling
-
Network Creation (2 tests)
- Successful creation
- Missing parameter validation
-
Field Updates (12 tests)
- String fields (description, hostname, domain)
- Boolean fields (statistics, DHCP)
- Integer fields (MTU)
- DHCP range shortcut
- Enum validation (DNS mode, network type)
- Unknown field handling
-
Power Management (3 tests)
- Power on/off operations
- Parameter validation
-
Configuration Actions (3 tests)
- Apply firewall rules
- Apply DNS settings
- Parameter validation
-
Cleanup (1 test)
- Network deletion with auto power-off
Running the Tests
./test-vergeos-network-manager.sh
Sample output:
==========================================
VergeOS Network Manager Test Suite
==========================================
Testing script: ./vergeos-network-manager.sh
==========================================
SECTION 1: Basic Command Tests
==========================================
[TEST 1] Help command
Command: ./vergeos-network-manager.sh help
✓ PASS - Command succeeded as expected
[TEST 2] List networks
Command: ./vergeos-network-manager.sh list
✓ PASS - Command succeeded as expected
...
==========================================
TEST SUMMARY
==========================================
Total Tests: 27
Passed: 27
Failed: 0
Pass Rate: 100%
==========================================
ALL TESTS PASSED! ✓
==========================================
Test-Driven Development
The test suite helped identify and fix several issues during development:
- Shell quoting issues with jq and the
$keyfield - Incorrect API action names for firewall and DNS operations
- API behavior differences (e.g., non-existent networks return empty objects)
- Network deletion requirements (must power off first)
By encoding these learnings into the test suite, we ensure they don't regress in future updates.
Real-World Use Cases
1. Infrastructure as Code
Store network configurations in version control:
#!/bin/bash
# networks.sh - Define all lab networks
# Create department networks
./vergeos-network-manager.sh create "Engineering" internal "10.0.10.0/24" "Engineering department" true
./vergeos-network-manager.sh create "Sales" internal "10.0.20.0/24" "Sales department" true
./vergeos-network-manager.sh create "Guest" internal "10.0.99.0/24" "Guest WiFi" true
# Configure DHCP ranges
./vergeos-network-manager.sh update 10 dhcp_range 10.0.10.100-10.0.10.200
./vergeos-network-manager.sh update 11 dhcp_range 10.0.20.100-10.0.20.200
./vergeos-network-manager.sh update 12 dhcp_range 10.0.99.100-10.0.99.200
2. Standardized Configuration
Apply consistent settings across multiple networks:
#!/bin/bash
# standardize-networks.sh
NETWORKS=(17 18 19) # Network IDs
for net in "${NETWORKS[@]}"; do
echo "Configuring network $net..."
./vergeos-network-manager.sh update $net mtu 9000
./vergeos-network-manager.sh update $net statistics true
./vergeos-network-manager.sh update $net dnslist "192.168.1.250,8.8.8.8"
./vergeos-network-manager.sh apply-dns $net
done
3. Disaster Recovery
Quickly recreate network configurations:
#!/bin/bash
# backup-networks.sh - Export all network configs
./vergeos-network-manager.sh list | while read line; do
KEY=$(echo $line | grep -oP '\[\K[0-9]+')
if [ -n "$KEY" ]; then
./vergeos-network-manager.sh show $KEY > "network-$KEY.json"
fi
done
4. Monitoring and Alerting
Integrate with monitoring systems:
#!/bin/bash
# check-network-health.sh
CRITICAL_NETWORKS=(17 18) # Production networks
for net in "${CRITICAL_NETWORKS[@]}"; do
STATUS=$(./vergeos-network-manager.sh show $net | jq -r '.enabled')
if [ "$STATUS" != "true" ]; then
echo "ALERT: Network $net is disabled!"
# Send to monitoring system
fi
done
Best Practices
1. Use Version Control
Store your network automation scripts in Git:
- Track changes over time
- Enable collaboration
- Facilitate rollbacks
2. Test Before Production
Always test network changes in a lab environment:
# Test in lab
./test-vergeos-network-manager.sh
# If all tests pass, apply to production
./apply-production-config.sh
3. Document Your Networks
Use the description field extensively:
./vergeos-network-manager.sh update 17 description "Kubernetes cluster network - 3 nodes - Production"
4. Implement Idempotency
Design scripts to be safely re-runnable:
# Check if network exists before creating
if ! ./vergeos-network-manager.sh show 17 &>/dev/null; then
./vergeos-network-manager.sh create "kubernetes" internal "10.0.6.0/24"
fi
5. Use Meaningful Names
Network names should be descriptive:
- ✅
kubernetes-prod - ✅
dmz-web-servers - ❌
network1 - ❌
test
Technical Deep Dive
API Authentication Flow
The scripts use a layered authentication approach:
- Cloudflare Service Token - Validates access to the tunnel
- VergeOS API Token - Authenticates to the VergeOS API
- Token Caching - Stores tokens with expiration tracking
- Automatic Renewal - Refreshes expired tokens transparently
This is all handled by the vergeos-cli-token.sh wrapper, which the network manager calls for every API operation.
Error Handling Strategy
The scripts implement multiple layers of error handling:
# 1. Input validation
if [[ ! "$value" =~ ^(internal|external|dmz)$ ]]; then
echo "Invalid network type"
return 1
fi
# 2. API error detection
if echo "$RESPONSE" | jq -e '.err' > /dev/null 2>&1; then
ERROR=$(echo "$RESPONSE" | jq -r '.err')
echo "API Error: $ERROR"
return 1
fi
# 3. Retry logic for transient failures
while [ $retry_count -lt $max_retries ]; do
# Attempt operation
if [ $? -eq 0 ]; then
return 0
fi
sleep 2
retry_count=$((retry_count + 1))
done
Field Type Handling
The update function intelligently handles different field types:
- Strings: Wrapped in jq
--argfor proper escaping - Booleans: Passed as JSON booleans via
--argjson - Integers: Validated and passed as numbers
- Enums: Validated against allowed values before submission
This ensures type safety and prevents API errors from malformed requests.
Lessons Learned
1. API Documentation vs. Reality
The VergeOS API documentation lists apply and applydns as valid actions, but the actual API only accepts refresh. Always test against the real API, not just the documentation.
2. Shell Quoting is Tricky
The $key field in JSON responses required careful escaping:
# Wrong - shell interprets $key
jq -r '.[\"$key\"]'
# Right - proper escaping
jq -r '.["$key"]'
3. SSL and Local IPs
When moving from a Cloudflare-proxied environment (which handles valid SSL certificates) to direct local IP access, SSL validation becomes an issue. The local scripts had to be updated to handle self-signed certificates gracefully using curl's --insecure flag to ensure reliable connectivity to the API.
4. State Management Matters
Networks must be powered off before deletion. The script now handles this automatically, but it took a failed test to discover this requirement.
5. Test Everything
The test suite caught issues that manual testing missed:
- Edge cases (empty values, non-existent resources)
- API behavior differences
- Race conditions in power state changes
Future Enhancements
Potential improvements for future versions:
- Bulk Operations - Update multiple networks simultaneously
- Configuration Templates - Pre-defined network templates
- Diff/Preview Mode - Show changes before applying
- JSON Import/Export - Full network configuration backup/restore
- Ansible Integration - VergeOS network module
- Webhook Support - Trigger actions on network events
- Validation Rules - Custom validation for network configurations
Conclusion
These scripts transform VergeOS network management from a manual, UI-driven process into a fully automated, testable, and version-controlled workflow. Whether you're managing a handful of networks or orchestrating complex multi-tenant environments, command-line automation provides:
- Consistency - Standardized configurations across all networks
- Speed - Bulk operations complete in seconds
- Reliability - Tested, validated operations with error handling
- Auditability - Version-controlled infrastructure changes
- Repeatability - Documented, reproducible processes
The combination of the network manager and test suite provides a solid foundation for VergeOS network automation. With 100% test coverage and comprehensive field support, these scripts are production-ready and battle-tested.
Getting Started
Ready to automate your VergeOS networks? Here's your roadmap:
-
Set up secure API access following the Cloudflare Tunnel guide
-
Download the scripts:
vergeos-cli-token.sh(authentication wrapper)vergeos-network-manager.sh(network management CLI)test-vergeos-network-manager.sh(test suite)
-
Configure credentials:
# The CLI will prompt for: # - VergeOS server URL # - Cloudflare service token (if using the standard version) # - VergeOS username/password ./vergeos-network-manager.sh listNote: If using the local version, simply run
./vergeos-network-manager-local.sh listand provide the internal URL and credentials. -
Run the test suite:
# For Cloudflare/Remote access: ./test-vergeos-network-manager.sh # For Local access: ./test-vergeos-network-manager-local.sh -
Start automating:
./vergeos-network-manager.sh help
Happy automating! If you have questions or suggestions for improvements, feel free to reach out. I'd love to hear how you're using these scripts in your homelab.
Related Posts
Local only files
Cloudflare version