Automating ArubaOS-CX Switches with the REST API and Postman - 夜莺博客

Automating ArubaOS-CX Switches with the REST API and Postman

ArubaOS-CX switches expose a full RESTful API that lets you treat switch configuration like any other software-defined resource — read state, push config, and automate workflows without ever opening an SSH session. This tutorial walks through a proven Postman collection of 13 requests that covers the whole lifecycle: logging in, reading interface state, uploading a complete configuration, and building a VLAN workflow step by step. It is the fastest way to get comfortable with AOS-CX programmability before you move on to Ansible or scripting.

Prerequisites and Initial Switch Setup

You need Postman (v7.2.2 or later) and an AOS-CX capable switch — a virtual AOS-CX switch works perfectly for testing. On the switch, enable the REST server and create an API user:

switch(config)# rest access-mode read-write enabled
switch(config)# username apiadmin password Aruba123
switch(config)# vlan 7
switch(config)# interface 1/1/4

Set a Postman environment variable named host to the switch management IP (e.g. 192.168.121.2) so every request resolves against the right device.

Importing the Collection

In Postman, click Import → Import from Link and paste the collection URL from the Aruba Community post. You get 13 requests labelled Aruba Andy's AOS-CX Collection covering login, logout, and read/write operations.

Why Automate AOS-CX Over REST Instead of SSH

Screen-scraping an SSH session with Expect or a Python wrapper works, but it is brittle: a firmware upgrade changes a prompt or a paging behaviour and every script breaks. The REST API is a stable, versioned contract. ArubaOS-CX exposes the same configuration database that the CLI writes to, so anything you can type you can also POST as JSON. The practical benefits are worth spelling out:

  • Structured data in, structured data out. A GET on an interface returns JSON with typed fields and standard units. You never parse a column of text that shifts by one space between firmware releases.
  • Idempotence is achievable. A PUT to a resource sets the end state; re-running it does not stack duplicate commands the way re-running a CLI snippet can.
  • Validation before apply. AOS-CX returns HTTP status codes (200, 201, 204, 400, 401, 404) so your automation knows immediately whether a change landed, instead of grepping for an error string in a log.
  • No terminal emulation. You do not need expect, paramiko or a jump host with an interactive session. Plain HTTPS on port 443 is enough, which simplifies firewall rules and logging.
  • Same interface as the GUI. The Web UI of an AOS-CX switch is a REST client. Watching a browser session in developer tools is a legitimate way to learn which endpoint a given GUI action uses.

The trade-off: the REST API is not a replacement for every CLI command. Some diagnostic and debug operations are CLI-only, and bulk operations are often faster as a single fullconfigs PUT than as dozens of small calls. Treat REST as the primary automation interface and SSH as the escape hatch.

Understanding the AOS-CX REST API Structure

All requests share a common shape:

https://{host}/rest/{version}/{resource-path}

The version segment (for example v10.04, v10.06, v10.09) must match a version the switch supports. You can discover what is available without authenticating:

curl -k https://192.168.121.2/rest/v10.04
curl -k https://192.168.121.2/rest/v10.04/system

The top-level resources you will use most often are:

Resource Purpose
/rest/v10.04/login Authenticate and obtain a session cookie
/rest/v10.04/logout End the session
/rest/v10.04/system Device identity, hostname, management info
/rest/v10.04/system/interfaces All interfaces and their state
/rest/v10.04/system/vlans VLAN database
/rest/v10.04/fullconfigs/running-config The entire running configuration as JSON
/rest/v10.04/system/vsx VSX peer state (on VSX-capable models)

Because the API mirrors the configuration tree, the URL itself documents intent: /system/vlans/7 is VLAN 7, and /system/interfaces/1%2F1%2F4 is interface 1/1/4 with the slashes URL-encoded.

The Key Requests

Login and Logout

The login request is a POST that authenticates the API user and returns a session cookie. Always send a logout when you finish — sessions left open until idle timeout are a small but avoidable hygiene issue.

In Postman, the login request is a POST to {{host}}/rest/v10.04/login with a JSON body:

{
  "username": "apiadmin",
  "password": "Aruba123"
}

On success the switch returns 200 OK and sets a session cookie. Postman stores that cookie automatically in its cookie jar, and every subsequent request in the collection rides on it. Two gotchas trip people up here: first, a self-signed certificate means Postman must have SSL verification turned off for the request; second, if you restart the switch or the session times out, every later request returns 401 Unauthorized — re-run login and continue.

Show Running-Config and Upload Full-Config

The most instructive pair: run show running-config on the switch, then GET the running config via the API and compare the JSON formatting with the CLI output. You can paste the API response body into the Upload Full-Config PUT request to overwrite the switch config programmatically — exactly how you would seed a new device. The endpoint is:

GET  {{host}}/rest/v10.04/fullconfigs/running-config
PUT  {{host}}/rest/v10.04/fullconfigs

When you PUT a full config, send the JSON body returned by the GET, optionally with a query parameter to control whether the change is written to the startup configuration. A realistic golden-config workflow looks like this: pull the running config from a known-good reference switch once, store it in git, render the device-specific parts (hostname, management IP, VSX parameters) with a template, then PUT the result to each new switch out of the box.

VLAN and Interface Workflow

  • Create vlan7 — POST to create the VLAN.
  • Map 1/1/4 to vlan7 — the tricky one: this only works if the interface has never been defined on the switch. If the port already exists in config, the request fails — a known quirk of how AOS-CX maps physical interfaces to logical ports (see the AOS-CX REST API Guide, section on ports and interfaces).
  • Review 1/1/4 — GET to inspect the interface state.
  • Bring 1/1/4 up — PUT to edit the interface admin state.
  • Delete vlan7 — DELETE, with a worthwhile experiment: delete a VLAN that is still referenced by an interface and observe the behavior.

The create-VLAN call in raw form is a POST whose body carries the VLAN id as the key:

POST {{host}}/rest/v10.04/system/vlans
{ "id": 7, "name": "USERS", "admin": "up" }

To attach a physical port to that VLAN you PUT to the interface resource with a body that references the VLAN:

PUT {{host}}/rest/v10.04/system/interfaces/1%2F1%2F4
{ "vlan_trunks": [], "vlan_tag": "/rest/v10.04/system/vlans/7",
  "vlan_mode": "access", "user_config": { "admin": "up" } }

The quirk mentioned above is worth internalising: the interface object in the REST model must already exist for certain writes to succeed, and some attributes are only settable while the port is not otherwise referenced. This is exactly the kind of behaviour that makes a lab switch with the same firmware version as production a genuine requirement, not a nice-to-have. If a PUT returns 400 with a "resource not found" style message, check whether the interface needs to be created first or whether the port is a member of a LAG.

Diagnostics Over the API

Ping and traceroute are also exposed as API requests — identical to the Diagnostics tools in the switch GUI, which makes them easy to embed in health-check scripts. Both are POSTs under a diagnostics resource:

POST {{host}}/rest/v10.04/system/ping
{ "destination": "10.10.10.10", "source": "vlan100", "count": 5 }

POST {{host}}/rest/v10.04/system/traceroute
{ "destination": "8.8.8.8", "source": "vlan100" }

Because the response is JSON, a monitoring script can assert on loss percentage and average round-trip time directly instead of parsing the CLI's dot-dot-dot output.

Using Postman Environments and Variables Properly

A collection that hard-codes IP addresses and credentials is a collection nobody reuses. Create one environment per switch (or per site) with variables such as host, username, password and rest_version, then reference them everywhere as {{host}}. Two refinements pay for themselves immediately:

  • Test scripts on the login request. Add a simple assertion so a failed login fails loudly in the runner rather than silently poisoning the next ten requests: pm.test("login ok", () => pm.response.to.have.status(200));
  • A pre-request login. For long-running collections, a pre-request script that re-authenticates when the session cookie is missing turns intermittent 401 errors into a non-issue.

Never commit a Postman environment that contains a real password. Use a placeholder in the shared file and let each engineer fill in their own values, or switch to certificate-based authentication if your firmware supports it.

Running the Collection Headlessly with Newman

Postman's own runner is fine for learning, but automation needs a CLI. Export the collection and environment to JSON and run:

npm install -g newman
newman run AOS-CX.postman_collection.json \
  -e aos-cx-lab.postman_environment.json \
  --reporters cli,json --reporter-json-export result.json

Newman exits non-zero when an assertion fails, which means the collection can be dropped straight into a CI pipeline or a cron job as a post-change verification suite. A realistic use is a nightly "config drift" check: log in, GET the running config, diff it against the golden copy in git, and alert on any difference.

The Same Thing from curl and Python

Postman is a learning tool; production automation usually ends up in a script. The cookie-based flow is easy to reproduce:

curl -k -c cookies.txt -X POST https://192.168.121.2/rest/v10.04/login \
  -H "Content-Type: application/json" \
  -d '{"username":"apiadmin","password":"Aruba123"}'

curl -k -b cookies.txt https://192.168.121.2/rest/v10.04/system/vlans

In Python, a requests.Session() object keeps the cookie automatically, so the whole collection becomes a few dozen lines of code. From there the natural progression is Ansible — see Ansible Jinja2 templates for network device configs for the templating side, and Junos PyEZ: automate Junos switches with Python for a vendor-SDK approach to the same problem.

Error Handling and Troubleshooting

Symptom Likely cause Fix
SSL certificate error Self-signed switch certificate Disable SSL verification in Postman or trust the CA
401 on every request Session expired or never established Re-run login; check cookie jar
400 on interface PUT Interface object not yet created or locked by a LAG Remove from LAG first, or create the interface
Connection refused REST server disabled or wrong access-mode rest access-mode read-write enabled
404 on a valid-looking URL API version mismatch with firmware Query /rest/{version} and adjust

Log every request and response during development. AOS-CX emits useful error text in the response body; capturing it turns a mystery 400 into a one-line fix.

Security and Operational Best Practices

  • Create a dedicated API user with a strong password, and restrict management access to a dedicated management VLAN or out-of-band network.
  • Prefer HTTPS with a proper certificate. If you must use self-signed, understand that any client will accept any switch.
  • Log out explicitly. Idle sessions consume a session slot on the switch.
  • Test every write request in a lab first — a full-config PUT can take a production switch off the network.
  • Keep a copy of the previous running config before any bulk change so rollback is a single PUT.
  • Use read-only mode (rest access-mode read-only enabled) for monitoring users who only need to collect facts.

Where to Go Next

Once the 13-request collection feels routine, the natural next steps are templating and event-driven automation. ArubaOS-CX NAE: scripts, agents and alerting covers the on-switch event engine that can trigger actions when a condition is met, and HPE Aruba AOS-CX Central onboarding guide explains how the same API surface is used by the cloud management platform. Arista CloudVision and AVD containerlab lab is worth reading for the multi-vendor view, since the design patterns transfer directly.

原文链接:https://community.arubanetworks.com/discussion/tutorial-aos-cx-restful-api-and-postman