One thing I’ve always been passionate about is writing scripts that are easy to read and consume. By showing you how to directly interact with REST APIs this enables you to do anything, and not be limited to the PowerShell functions provided by the vendor.
When it comes to working with REST APIs and PowerShell this starts to pay dividends when you want to take all the knowledge you’ve learned from working with 1 platform then use the same skills to connect and leverage another.
My first example of porting skills between platforms follows my recent journey of switching from working for Zerto to Rubrik. In this post I will give you all the information needed to connect and leverage Rubrik REST APIs using PowerShell.
Your first option could be to simply download the excellent work of Chris Wahl from GitHub, as he has created an extensive PS module with everything pre-built. Or, you could roll your own scripts to directly work with the REST API. If you want to go down this route, how do you authenticate and run a simple query?
As a base template, I’m going to the use the PowerShell code required to authenticate with the Zerto REST API shown below:
######################################## # Configure the variables below for Zerto ######################################## $ZertoServer = "192.168.0.31" # Prompting for username and password to authenicate $Credentials = Get-Credential -Credential $null $ZertoUser = $Credentials.UserName $Credentials.Password | ConvertFrom-SecureString $ZertoPassword = $Credentials.GetNetworkCredential().password ######################################## # Adding certificate exception to prevent API errors ######################################## add-type @" using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } "@ [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12' ######################################## # Building ZVR API string & invoking REST API ###################################### $baseURL = "https://" + $ZertoServer + ":9669/v1/" $xZertoSessionURL = $baseURL + "session/add" $authInfo = ("{0}:{1}" -f $ZertoUser,$ZertoPassword) $authInfo = [System.Text.Encoding]::UTF8.GetBytes($authInfo) $authInfo = [System.Convert]::ToBase64String($authInfo) $headers = @{Authorization=("Basic {0}" -f $authInfo)} $sessionBody = '{"AuthenticationMethod": "1"}' $TypeJSON = "application/json" # Authentication with API Try { $xZertoSessionResponse = Invoke-WebRequest -Uri $xZertoSessionURL -Headers $headers -Method POST -Body $sessionBody -ContentType $TypeJSON } Catch { Write-Host $_.Exception.ToString() $error[0] | Format-List -Force } # Extracting x-zerto-session from the response $xZertoSession = $xZertoSessionResponse.headers.get_item("x-zerto-session") $zertosessionHeader = @{"x-zerto-session"=$xZertoSession}
Now the equivalent code slightly modified to connect to the Rubrik REST API:
######################################## # Configure the variables below for the Rubrik Cluster ######################################## $RubrikCluster = "192.168.0.200" # Prompting for username and password to authenicate $Credentials = Get-Credential -Credential $null $RubrikUser = $Credentials.UserName $Credentials.Password | ConvertFrom-SecureString $RubrikPassword = $Credentials.GetNetworkCredential().password ######################################## # Adding certificate exception to prevent API errors ######################################## add-type @" using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } "@ [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12' ######################################## # Building Rubrik API string & invoking REST API ################################################ $BaseURL = "https://" + $RubrikCluster + "/api/v1/" $InternalURL = "https://" + $RubrikCluster + "/api/internal/" $RubrikSessionURL = $BaseURL + "session" $Header = @{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($RubrikUser+":"+$RubrikPassword))} $Type = "application/json" # Authenticating with API Try { $RubrikSessionResponse = Invoke-RestMethod -Method POST -Uri $RubrikSessionURL -Headers $Header -ContentType $Type } Catch { $_.Exception.ToString() $error[0] | Format-List -Force } # Extracting the token from the JSON response $RubrikSessionHeader = @{'Authorization' = "Bearer $($RubrikSessionResponse.token)"}
Notice how they are very similar? The only major differences are the variable names, base URL, session URL, and handling of the authentication session response to make subsequent requests.
Now that we have authenticated we can query a list on unprotected VMs on both platforms, starting with Rubrik. With each you will notice the same pattern of building the URL, invoking the REST method against the URL with the authentication header, wrapping the request in a Try for error handling, assigning the invoke response to a variable, then using the variable to get the data required:
####################################### # Getting list of Unprotected VMs in Rubrik ####################################### $VMListURL = $BaseURL+"vmware/vm" Try { $VMListJSON = Invoke-RestMethod -Method GET -Uri $VMListURL -TimeoutSec 100 -Headers $RubrikSessionHeader -ContentType $TypeJSON $VMList = $VMListJSON.data } Catch { Write-Host $_.Exception.ToString() $error[0] | Format-List -Force } # Building list of unprotected VMs and displaying a table $UnprotectedVMs = $VMList | Where-Object {($_.effectiveSlaDomainName -eq "UNPROTECTED") -and ($_.PowerStatus -eq "poweredOn")} | select name,moid,clusterName,ipAddress,vmwareToolsInstalled $UnprotectedVMs | Format-Table -AutoSize
Here is the same query with Zerto:
######################################### # Getting list of Unprotected VMs in Zerto ######################################### # Get SiteIdentifier $SiteInfoURL = $BaseURL+"localsite" Try { $SiteInfoCMD = Invoke-RestMethod -Method GET -Uri $SiteInfoURL -TimeoutSec 100 -Headers $ZertosessionHeader -ContentType $TypeJSON $LocalSiteIdentifier = $SiteInfoCMD | Select SiteIdentifier -ExpandProperty SiteIdentifier } Catch { Write-Host $_.Exception.ToString() $error[0] | Format-List -Force } # Using SiteIdentifier to get a list on unprotected VMs $UnprotectedVMListURL = $BaseURL+"virtualizationsites/"+$LocalSiteIdentifier+"/vms" Try { $UnprotectedVMList = Invoke-RestMethod -Uri $UnprotectedVMListURL -TimeoutSec 100 -Headers $ZertosessionHeader -ContentType $TypeJSON } Catch { Write-Host $_.Exception.ToString() $error[0] | Format-List -Force } # Building a list of unprotected VMs and displaying a table $UnprotectedVMListTable = $UnprotectedVMList | select VmIdentifier, VmName $UnprotectedVMListTable | Format-Table -AutoSize
Pretty simple huh? So now you’ve successfully authenticated and run your first query, what can you do next? This is where you can leverage one of the coolest features of Rubrik and that is built in swagger.
You might be thinking “isn’t swagger an overly confident walk?”. I’ll be honest in that I thought the same until about 1 year ago. Swagger is essentially an interactive REST API document/framework accessible via a specific URL from your platform of choice (if the vendor built it into their product) and it makes your life so much easier. With Rubrik it can be accessed by using the following URLs to connect to your Rubrik cluster:
Swagger UI:
https://rubrik-cluster-fqdn-or-ip/docs/v1/playground
Documentation:
https://rubrik-cluster-fqdn-or-ip/docs/v1/
Using the swagger UI we can easily start to consume the APIs available:
You now have the perfect starting point to do absolutely anything and everything in Rubrik! Also, with the ability to interact with multiple platforms from the same script you can start to look at really cool use cases such as integrating Zerto and Rubrik for protection, reporting, and recovery. All of which I will be building and sharing over the coming months and if you have any specific requests let me know. If you’d like to download a sample script to authenticate with Rubrik you can grab it here:
RubrikRESTAPIAuthenticationV1.zip
If you found this useful please like and share. Happy scripting,
Joshua
P.S If you found this really interesting, but it would be more useful to see these examples in Python then check out my colleague Aaron Lewis’s excellent blog: https://virtualaaron.com/2017/05/15/a-rubrik-python-primer/
[…] hot on the heels of my first post on an “Introduction to Rubrik REST APIs using PowerShell & Swagger” I’d now like to show you how to easily automate the recovery and boot ordering of VMs as a […]
[…] With that in mind, my esteemed colleague @LordMiddlewick has written some PowerShell scripts with the help of @joshuastenhouse previous blog posts about using Rubrik RestAPIs . […]
[…] @joshuastenhouse has a great blog post covering an Introduction to Rubrik REST APIs using PowerShell & Swagger. […]