Tag Archives: RESTAPI

Rubrik Build Workshop

Last week (end of May 2019) I was lucky enough to secure a place at the Rubrik Build Workshop in London. This event, which has been touring round the world, is a day of technical learning focussed on API, SDK, and version control.

Roxie at RubrikThe first thing to acknowledge here is even though Rubrik was hosting the event and the presenters  (the awesome pairing of Chris Wahl and Rebecca Fitzhugh) work for the company there was absolutely no sales push. Whilst they used their own APIs and SDKs as examples the majority of the content was very much platform agnostic. Kudos is due here for running this kind of free-of-charge educational event for the tech community without filling it with sales and marketing slides.

The morning started with a session on version control- looking at how git and in particular GitHub – can be used to track and share code. The “RoxieAtRubrik” GitHub account was used in some hands-on demos -we all forked a public project, made changes,  and submitted a pull request. The course material used in the workshops is publicly available via this account- check here: https://github.com/RoxieAtRubrik

There were some insights into how GitHub is used at Rubrik- there’s unit tests for every single function and in the background they have a CI (Continuous Integration) pipeline at work to make sure releases are up to scratch. Quality control can be tricky on community fed projects where developers may not be subject to traditional corporate control and it’s interesting to see how different teams handle this input.

Our dive into version control was followed by a look at how REST APIs work, using the Rubrik APIs as an example. There was plenty of hands-on activity here, with an online lab provided to simulate communicating with a real world device but in a safe environment.

Rubrik Hands on Lab Environment

The schedule of this event was flexible and after a show of hands amongst the 15 delegates we moved on to look at PowerShell, both in general terms for those new to the scripting language but also seeing how the SDK layer of the Rubrik PowerShell module made the API calls we’d looked at previously more user-friendly.

This PowerShell module is open source and available on GitHub- https://github.com/rubrikinc/rubrik-sdk-for-powershell – and as with all these projects contributions are welcome from the community. There was lots of encouragement from the presenters for customers/users to try these SDKs out and feed back any improvements that could be made, either by submitting an feature request or bug report, or by writing some or all of the addition yourself.

The European leg of the Rubrik Build tour has finished, but they’re off to Australia and New Zealand in June if that’s local to you. Check out https://build.rubrik.com/ for details.

Using PowerShell and REST-API to create a VM in vCenter

VMware vSphere 6.5 comes with a RESTful API implementation and there’s some great documentation out there- starting with the API Explorer (http://my.vcenter.name/apiexplorer ). Here’s a quick piece on how to use this API to create a VM from the PowerShell command line. This is intentionally not using PowerCLI,  just the native PowerShell cmdlets- partly as a REST learning experience for me, and partly so the API code can be transferred to another language at a later date.

Step 1- Authenticate with the Server.

This step is well documented by Chris Wahl. I’ve borrowed some of his code here, and accompanied it with a section to get around the lack of trusted certificates on my homelab. 192.168.0.240 is the IP of my VCSA, so if you’re reusing this anywhere remember to replace that hard coded value where it appears.

#----------------------------------------------------------------------------------------------
#Step 1- Authenticate with the Server
#Ignore Server Certs- This is on my not-very-well-certified home lab.
if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
{
$certCallback[email protected]"
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public class ServerCertificateValidationCallback
{
public static void Ignore()
{
if(ServicePointManager.ServerCertificateValidationCallback ==null)
{
ServicePointManager.ServerCertificateValidationCallback +=
delegate
(
Object obj,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors errors
)
{
return true;
};
}
}
}
"
@
Add-Type $certCallback
}
[ServerCertificateValidationCallback]::Ignore();

#Get Some Credentials and Determine Authorisation Methods
$Credential = Get-Credential
$auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Credential.UserName+':'+$Credential.GetNetworkCredential().Password))
$head = @{
'Authorization' = "Basic $auth"
}

#Authenticate against vCenter
$r = Invoke-WebRequest -Uri https://192.168.0.240/rest/com/vmware/cis/session -Method Post -Headers $head
$token = (ConvertFrom-Json $r.Content).value
$session = @{'vmware-api-session-id' = $token}

Now we have the Session ($session) we can test this by retrieving a list of VMs.

#----------------------------------------------------------------------------------------------
#Get a List of VMs
$r1 = Invoke-WebRequest -Uri https://192.168.0.240/rest/vcenter/vm -Method Get -Headers $session
$vms = (ConvertFrom-Json $r1.Content).value
$vms

Step 2- Construct the JSON specification

To create a new VM we need to provide a minimal spec for the machine, in JSON format. We need to tell it the intended Guest OS, what datastore is going to hold the VM, and where the VM will be placed in the resource/folder structure. To complete this we need to establish what options are available- just sticking in the display names of a datastore or folder from the Web Client will not work and will likely generate 404 responses to the API call.

To find these names we can use the API, API explorer gives us the following urls

Datastore:       /rest/vcenter/datastore
Folder:              /rest/vcenter/folder
Resource Pool: /rest/vcenter/resource-pool

So we can use PowerShell to retrieve a list of Datastores using this line of code

(Invoke-RestMethod -Uri https://192.168.0.240/rest/vcenter/datastore -Method Get -Headers $session ).value

which will produce a list of datastores, each looking something like this:

datastore  : datastore-11
name       : Datastore2
type       : VMFS
free_space : 100553195520
capacity   : 249913409536

From this example we want the value of the “datastore” field, e.g “datastore-11”.

Once we have this information we can combine it all to create a JSON spec file. My example looks like this:

{
"spec": {
"guest_OS": "RHEL_7_64",
"placement" : {
"datastore": "datastore-11",
"folder": "group-v224",
"resource_pool": "resgroup-182"
}
}
}

Step 3- Create the Virtual Machine.

Now we’ve done all this prep work, creating a Virtual Machine comes down to a single line of PowerShell pointing at the data.txt file containing the JSON code from Step 2.

Invoke-WebRequest -Uri https://192.168.0.240/rest/vcenter/vm -Method Post -Headers $session -ContentType "application/json" -Body (Get-Content data.txt)

Example Output:

StatusCode        : 200
StatusDescription : OK
Content           : {"value":"vm-462"}
RawContent        : HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/json
Date: Mon, 27 Mar 2017 09:41:34 GMT

{"value":"vm-462"}
Forms             : {}
Headers           : {[Transfer-Encoding, chunked], [Content-Type, application/json], [Date, Mon, 27 Mar 2017 09:41:34 GMT]}
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        : mshtml.HTMLDocumentClass
RawContentLength  : 18

The VM is created and we can check this from the vSphere Client:

2017-03-27 (10)

So, to summarise. Native PowerShell, with a little bit of JSON, can be used to communicate with the vSphere APIs and create new Virtual Machines. Depending on your use case there may be better ways of implementing automation processes through this API (PowerCLI is a good start) but if you want to drop to the raw RESTful API, possibly as a stepping stone to a larger project, PowerShell provides a handy method to get started down that path.