Using REST API calls to vCSA with PowerShell

I was reading through the CIS ESXi 6.7 hardening benchmark and trying to turn the process of checking and, if necessary, making configuration changes to align with the benchmark a fully automated script. The last thing I want is for my global deployment team to have to hand jam something if that something can be fully scripted. I ran into challenge when I got to 3.1 – Ensure a centralized location is configured to collect ESXi host core dumps. The easiest way to manage this is to have the VCSA run the dump collector service (netdumper). Unfortunately there’s no PowerCLI cmdlet to manage and monitor vCSA services and the netdumper service is disabled by default.

Fortunately there are RESTful API’s for interacting with vCenter services and so I began my journey of discovery on using Invoke-RestMethod in PowerShell.

I’ll spare the long, drawn out version of how I, through trial and error figured out how to authenticate a session and use that session to get the netdumper service so I can evaluate it’s status and force it to startup and simply drop a couple of functions here. I will make a couple of quick points:

  1. The hardest thing to get write on any of these requests was the formatting of the header and body parameters
    1. For headers, all calls except the the session initiation require ” ‘vmware-api-session-id’ = $Session.ID” in the hash table
    2. While headers are a hash table, bodies need to be sent as a json. Building the json as a hashtable then piping to ConvertTo-Json works nicely for this as you’ll see below.
  2. I’m not usually a fan of variable splatting as I’m lazy and it breaks intellisense in vsCode, but for Invoke-RestMethod I will make an exception
  3. VMware’s API documentation is pretty good once you figure out the header/body formatting. Nobody seems to want to write a post about the fundamentals of REST API calls in PowerShell only examples that are usually incomplete.
  4. ConvertTo-Json is your friend

First we have New-RestViSession(). This take the vCenter’s FQDN (or IP address) SSO administrator or appliance root user and secure string password and return an object with the session ID and input parameters.

Having a session object allows us to call additional functions to get the services from the vCSA, set their properties (mostly startup mode) and start/stop them.

Now will a full set of cmdlets I can call into vCenter and get the status of netdumper, which I expect to be stopped and disabled then enable it.

I’ll finish by saying that I’m still reletively new to use RESTful methods to do anything especially in PowerShell, as such I’ll accept that there are probably better ways to pull this off, but in translating these REST methods into PowerShell cmdlets I’m trying to build a way to translate my teams PowerShell expertise into a broader set of APIs that can both do more in vCenter and eventually do more with the hardware it’s running on via Redfish.