NSX automation
Every VCF workload domain has NSX, and most VMs you build sooner or later need something from it: a network to sit on, a tag that puts them in the right security group, a firewall rule. Orchestrator 9.x doesn’t ship an NSX plug-in. It doesn’t need one. NSX Manager has a complete REST API, the Policy API, and the HTTP-REST plug-in from recipe 5.2 is all it takes to call it.
In this recipe you register NSX Manager as a REST host and write a small set of actions on top of it: one helper that every call goes through, one that creates a segment and waits until NSX has actually built it, one that tags a VM, and one that makes a group whose members are all VMs with that tag. Together they cover the pattern of almost every NSX job you’ll automate: describe what you want, send it with PATCH, and check that NSX realized it.
Getting ready
- NSX Manager for the workload domain that holds
vc01.vmw.lab. In this book it’snsx01.vmw.lab. - An NSX account for Orchestrator, here
svc-vcfguide-nsx@vsphere.local, with a role that can create segments and groups and tag VMs. In a lab, the Network Admin and Security Admin roles together are enough. - A Tier-1 gateway connected to your Tier-0, for the new segment to attach to. This recipe uses one with the ID
vcfguide-t1. Create it in the NSX Manager UI if you don’t have one. - The HTTP-REST plug-in and REST hosts from recipe 5.2.
- The VM
vcfguide-web-01from recipe 8.2, and the actionfindVmByNamefrom recipe 8.1.
svc-vcfguide-nsx create a segment, create a group, and tag a VM. Replace “Network Admin and Security Admin” with what you find.How to do it
Register NSX Manager
-
Run Add a REST host as in recipe 5.2, with Name
nsx01-rest, URLhttps://nsx01.vmw.lab, Connection timeout30, and Operation timeout60. Accept the certificate. -
On Host Authentication, choose Basic, then Shared Session, and enter
svc-vcfguide-nsx@vsphere.localand its password. NSX accepts Basic authentication on every call, so there’s no login step to script, unlike vCenter in recipe 5.2. -
Check the address and the account before Orchestrator is involved. Log in to the NSX Manager UI as
svc-vcfguide-nsx@vsphere.local, then open this address in another tab of the same browser:https://nsx01.vmw.lab/policy/api/v1/infra/tier-1s/vcfguide-t1NSX shows the gateway as JSON, with
"display_name" : "vcfguide-t1"and"path" : "/infra/tier-1s/vcfguide-t1". If you get a login page or a 403 instead, fix the account’s role in NSX first.
GET on the Policy API opens in a browser tab of a logged-in NSX Manager session, without a separate login.Administration > Inventory > HTTP-REST with nsx01-rest selected, showing URL https://nsx01.vmw.lab and Basic / Shared Session; inset: terminal with the curl … /infra/tier-1s/vcfguide-t1 | jq output.
One helper for every call
- Create the action
nsxCallincom.vcfguide.chapter8, with the inputsrestHost(REST:RESTHost),method(string),path(string), andbody(Any), and the return typeAny:
// Calls the NSX API and returns the parsed JSON body, or null for an empty one.// body is an object to send as JSON, or null. Throws on any status above 299.var content = (body === null || body === undefined) ? null : JSON.stringify(body);var request = restHost.createRequest(method, path, content);request.setHeader("Accept", "application/json");if (content !== null) { request.contentType = "application/json";}var response = request.execute();var text = response.contentAsString;System.debug(method + " " + path + " returned " + response.statusCode);
if (response.statusCode < 200 || response.statusCode > 299) { var detail = text; try { var error = JSON.parse(text); if (error.error_message) { detail = error.error_message + " (error " + error.error_code + ")"; } } catch (e) { // not JSON: keep the raw text } throw "NSX " + method + " " + path + " failed with HTTP " + response.statusCode + ": " + detail;}return text ? JSON.parse(text) : null;- Run it with
nsx01-rest,GET,/policy/api/v1/infra/tier-1s/vcfguide-t1, and an empty body. The result is the gateway, the same objectcurlprinted.
Create a segment and wait for it
- Create the action
nsxWaitForRealizationincom.vcfguide.chapter8, with the inputsrestHost(REST:RESTHost),intentPath(string), andtimeoutSeconds(number), and no return value:
// Waits until NSX reports that the object at intentPath is realized.var nsx = System.getModule("com.vcfguide.chapter8");var path = "/policy/api/v1/infra/realized-state/status?intent_path=" + encodeURIComponent(intentPath);var deadline = new Date().getTime() + timeoutSeconds * 1000;
while (true) { var status = nsx.nsxCall(restHost, "GET", path, null); var state = status.consolidated_status ? status.consolidated_status.consolidated_status : "UNKNOWN"; if (state === "SUCCESS") { System.log(intentPath + " is realized"); return; } if (state === "ERROR" || state === "FAILED") { throw intentPath + " failed to realize: " + JSON.stringify(status); } if (new Date().getTime() > deadline) { throw intentPath + " not realized after " + timeoutSeconds + " seconds (state " + state + ")"; } System.sleep(3000);}- Create the action
nsxCreateSegmentincom.vcfguide.chapter8, with the inputsrestHost(REST:RESTHost),segmentId(string),tier1Id(string), andgatewayCidr(string), and the return typestring. It returns the segment’s policy path:
// Creates or updates an overlay segment on a Tier-1 gateway, then waits for it.// gatewayCidr is the gateway address and prefix, for example "10.80.1.1/24".var nsx = System.getModule("com.vcfguide.chapter8");var segmentPath = "/infra/segments/" + segmentId;
var segment = { display_name: segmentId, connectivity_path: "/infra/tier-1s/" + tier1Id, subnets: [ { gateway_address: gatewayCidr } ], tags: [ { scope: "vcfguide", tag: "chapter8" } ]};nsx.nsxCall(restHost, "PATCH", "/policy/api/v1" + segmentPath, segment);System.log("Asked NSX for segment " + segmentId + " (" + gatewayCidr + ") on " + tier1Id);
nsx.nsxWaitForRealization(restHost, segmentPath, 120);return segmentPath;- Create the workflow Create an NSX segment in VCF Orchestrator Guide/Chapter 8. Drag nsxCreateSegment onto the schema and promote its inputs, except
restHost. Make that one a variable,nsx, of typeREST:RESTHost, with the valuensx01-rest, so nobody has to pick the host on every run. Promote the result as the outputsegmentPath. - Run it with
segmentIdvcfguide-seg-01,tier1Idvcfguide-t1, andgatewayCidr10.80.1.1/24. Use a subnet that’s free in your lab. The run logs the request, then … is realized, and returns/infra/segments/vcfguide-seg-01. - Run it again with the same values. It succeeds again and changes nothing. That’s what
PATCHon the Policy API means: here is the object I want, make it so. - In NSX Manager, go to Networking > Segments.
vcfguide-seg-01is there, connected tovcfguide-t1, with status Success. In the vSphere Client it appears as a network you can connect a VM to.
Completed run of Create an NSX segment, Logs tab: Asked NSX for segment vcfguide-seg-01 (10.80.1.1/24) on vcfguide-t1 and /infra/segments/vcfguide-seg-01 is realized; output segmentPath. Beside it, NSX Manager Networking > Segments with vcfguide-seg-01, connected gateway vcfguide-t1, subnet, status Success, tag vcfguide | chapter8.
/infra can be created on vcfguide-t1 with only connectivity_path and subnets (the overlay transport zone is filled in when there’s only one), the JSON shape of /realized-state/status and its values (SUCCESS, IN_PROGRESS, ERROR, others), and roughly how long realization takes. Note what the vSphere Client shows the segment as.Tag a VM without losing its other tags
- NSX knows a VM by its external ID, which is the VM’s instance UUID in vCenter. The call that sets tags replaces every tag the VM has with the ones you send, so read the current tags first and add yours to them. Create the action
nsxTagVmincom.vcfguide.chapter8, with the inputsrestHost(REST:RESTHost),vm(VC:VirtualMachine),scope(string), andtag(string), and the return typeArray/string:
// Sets scope|tag on a VM in NSX, keeping its other tags.// A tag with the same scope is replaced. Returns the VM's tags as "scope|tag".var nsx = System.getModule("com.vcfguide.chapter8");var externalId = vm.config.instanceUuid;
var search = nsx.nsxCall(restHost, "GET", "/policy/api/v1/search/query?query=" + encodeURIComponent("resource_type:VirtualMachine AND external_id:" + externalId), null);if (!search.results || search.results.length === 0) { throw "nsxTagVm: NSX doesn't know " + vm.name + " (" + externalId + ") yet";}
var current = search.results[0].tags || [];var tags = [];for (var i = 0; i < current.length; i++) { if (current[i].scope !== scope) { tags.push({ scope: current[i].scope, tag: current[i].tag }); }}tags.push({ scope: scope, tag: tag });
nsx.nsxCall(restHost, "POST", "/policy/api/v1/infra/realized-state/virtual-machines/" + externalId + "/tags", { tags: tags });
var result = [];for (var j = 0; j < tags.length; j++) { result.push(tags[j].scope + "|" + tags[j].tag);}System.log(vm.name + " now has the NSX tags " + result.join(", "));return result;- Run it with
nsx01-rest, the VMvcfguide-web-01,scopevcfguide-role, andtagweb. The log lists the VM’s tags, ending withvcfguide-role|web. Run it again withtagapp, andwebis replaced byapp, because there’s one tag per scope. Run it a third time withwebto put it back.
/infra/realized-state/virtual-machines/<id>/tags is the VM’s external ID, that the external ID equals vm.config.instanceUuid from the vCenter plug-in, that the search query by external_id returns the VM with its tags, and that the POST returns 204. Also check how soon a VM built in recipe 8.2 is known to NSX after it powers on.Group VMs by tag
- Create the action
nsxEnsureTagGroupincom.vcfguide.chapter8, with the inputsrestHost(REST:RESTHost),groupId,scope, andtag(allstring), and the return typeArray/string. It creates or updates a group in the default domain whose members are every VM with that tag, then returns the members’ names:
var nsx = System.getModule("com.vcfguide.chapter8");var groupPath = "/infra/domains/default/groups/" + groupId;
nsx.nsxCall(restHost, "PATCH", "/policy/api/v1" + groupPath, { display_name: groupId, description: "VMs tagged " + scope + "|" + tag, expression: [ { resource_type: "Condition", member_type: "VirtualMachine", key: "Tag", operator: "EQUALS", value: scope + "|" + tag } ]});nsx.nsxWaitForRealization(restHost, groupPath, 60);
var members = nsx.nsxCall(restHost, "GET", "/policy/api/v1" + groupPath + "/members/virtual-machines", null);var names = [];var list = members.results || [];for (var i = 0; i < list.length; i++) { names.push(list[i].display_name);}System.log("Group " + groupId + " has " + names.length + " VMs: " + names.join(", "));return names;- Run it with
nsx01-rest,groupIdvcfguide-web,scopevcfguide-role, andtagweb. The log listsvcfguide-web-01. In NSX Manager, Inventory > Groups showsvcfguide-web. Click View Members to see the same VM. - Tag a second VM with
vcfguide-role|weband run step 15 again. Both VMs are members now, and you didn’t touch the group’s definition. Membership follows the tag.
Run of action nsxTagVm for vcfguide-web-01, Logs tab: vcfguide-web-01 now has the NSX tags …, vcfguide-role|web. Beside it, NSX Manager Inventory > Groups, vcfguide-web with the criterion Virtual Machine Tag Equals web Scope vcfguide-role, View Members open listing the tagged VMs.
Clean up
- When you’re done, delete the segment with
nsxCallandDELETEon/policy/api/v1/infra/segments/vcfguide-seg-01. NSX refuses while a VM is still connected to it. Keep the group and the tag: recipe 8.5 uses them.
How it works
Intent, then realization. The Policy API is declarative. A PATCH stores what you want, the intent, and returns at once, usually with 200. NSX then builds it on the edges and hosts in the background, which is realization. A 200 means NSX accepted the request, not that the network works yet, so a workflow that connects a VM straight after creating a segment can race ahead of NSX. nsxWaitForRealization asks the realized-state API about one intent path until NSX says it’s done, failed, or the deadline passes, the same idea as waitForTask in recipe 8.1 for vCenter.
IDs you choose. On the Policy API, the client picks the ID and puts it in the path: /infra/segments/vcfguide-seg-01. That’s what makes PATCH safe to repeat. A workflow that fails after creating the segment can be run again without making a second one, and you never have to search for the object you just created.
Paths link objects. Objects refer to each other by policy path, not by name or UUID. The segment names its gateway with connectivity_path, and the realization check takes intent_path. Paths are readable and predictable, so you can build them in a script without looking anything up.
Tags are the glue. Groups with tag criteria are how NSX lets security follow workloads. The workflow that builds a VM only has to set the right tag. Which group the VM joins, and which firewall rules apply to it, is decided in NSX, by whoever owns security. The tag call replaces all tags on the VM, which is why nsxTagVm reads them first. Without that, tagging a VM for one purpose would silently remove tags another team set for another.
One helper, one error message. Every call goes through nsxCall, so every failure reads the same way, with NSX’s own error_message, and every call is in the debug log. The HTTP-REST plug-in doesn’t fail on a 400 or a 500 by itself, as recipe 5.2 explains, and NSX’s error body is usually the fastest way to the cause.
There's more
VPCs in VCF 9. VCF 9 adds NSX VPCs: self-contained networks inside an NSX project, which VCF Automation and the vSphere Client use for self-service. The same Policy API covers them, under a longer path, for example /policy/api/v1/orgs/default/projects/<project>/vpcs/<vpc>/subnets/<subnet>. The tag call also has a project form, /policy/api/v1/orgs/<org>/projects/<project>/infra/realized-state/virtual-machines/<id>/tags. If your workloads live in VPCs, keep nsxCall as it is and change only the paths.
Firewall rules. A distributed firewall policy is one more PATCH, to /policy/api/v1/infra/domains/default/security-policies/<id>, with rules that name groups by path in source_groups and destination_groups. Because the group follows the tag, the workflow that builds a VM never has to touch a rule.
See the API from the UI. NSX Manager’s UI is built on the same API. To find the body for something, create it once in the UI, then GET it with curl or nsxCall and copy the fields you need. Leave out read-only ones such as _revision, _create_time, and realization_id.
Concurrent edits. If two runs change the same object, the second write wins. For whole-object updates, NSX supports a revision check: send back the _revision you read, and NSX rejects the write with 412 if someone changed the object in between. Read again and retry. For many runs that change the same group or policy, a lock (recipe 7.5) is simpler.
Rate limits. NSX Manager limits how many API calls each client can make per second and at once, and answers 429 above that. Workflows that loop over hundreds of VMs should pace themselves, for example with a short System.sleep between calls, rather than retrying as fast as they can.
Connect the VM to the segment. Changing a VM’s network is a vCenter job, not an NSX one. Use the vCenter plug-in’s library workflows for network adapters, or a reconfigure spec as in recipe 8.2, and pick the segment as the network.
See also
- 5.2 REST hosts and operations, for REST hosts,
createRequest, and status codes. - 7.5 Locks, for runs that change the same NSX object.
- 8.1 Workflows against vCenter, for
findVmByNameand the polling pattern. - 8.5 Extensibility subscriptions, which tags every VM VCF Automation builds with
nsxTagVm. - Broadcom TechDocs (VCF 9.0): Plug-ins installed with the VCF Operations orchestrator server.
- Broadcom developer portal, NSX REST API: Create or update a segment (9.1.0), Virtual machine inventory methods (9.1.0), Apply tags on a virtual machine, List virtual machines (9.0.0), Condition, for group expressions (9.0.0), and Read the realization status of an intent.
- CloudBlogger, the author’s blog: Generate NSX ALB CSRFToken in Orchestrator.
