Easy Automation with Zerto REST APIs

ZertoCOn 2018 Logo

Zerto Virtual Replication has a pretty easy to use GUI, with a few clicks you are able to do everything from restore a file to move an entire datacenter. But even a few clicks can be a real pain in a large scale operation. To get around some of this issues you may want to consider the Zerto REST API or the Zerto PowerShell cmdlets. Both offer great solutions for a variety of issues you may run into once you take your data center migration or disaster recovery plan to the next level!

Some other uses for ZVR’s automation methods include:

  • VRA, VPG, site, and failover automation
  • Metrics and Analytics extraction
  • Export / Import Data with 3rd party tools

 
 
 


This material was presented at my ZertoCON 2018 “REST Easy: Fear APIs and Scripting no more” session. This article is meant to compliment that session by providing a recap as well as links to examples.

When to use REST API vs PowerShell Cmdlets

Both the REST API and PowerShell cmdlets can be used to get information from Zerto as well as change some settings. So when choosing which one to use the first thing to ask yourself is where will I run this script? If the answer is on a Windows system that has PowerShell

PowerShell cmdlets Rest API
 Pros

  • Most IT Admins have already used PowerShell
  • Simple to get started
  • Can run on ZVM (or your desktop) with minimal new components
  • HUGE PowerShell Community
Pros

  • Many programming language choices (FLEXIBILITY!)
  • Native scripts for Linux (Bash, Python, etc)
  • Deeper automation capabilities with Zerto
  • Can be used in PowerShell with Zerto PowerShell cmdlets
  • No API software to install
 Cons

  • Windows-based (at least for now)
  • Must have Zerto PowerShell Cmdlets installed
  • Not all Zerto functions are available via PowerShell cmdlets
Cons

  • More complex than PowerShell Cmdlets
  • Can take more time / longer scripts

No Experience with PowerShell or REST APIs?

No worries, a quick google search will turn up more information than you could ever want. Wired has a great explanation of REST APIs, and if you haven’t heard of the Microsoft Virtual Academy then you should check it out for PowerShell. MVA has a free getting started with PowerShell course.

Those links are to help you get familiar with how each of the interfaces work, but if you are just interested in getting started with scripts for Zerto, we can start by talking about some simple example scripts which you can then build off of later on.

PowerShell Examples

Before I get into the PowerShell example, I want to remind you that by default the Zerto PowerShell cmdlet interface is protected with a very basic password. You should change it ASAP, to learn how to do that check out my how-to post.

 

OK, now that the public service announcement is out of the way, let’s look at a basic PowerShell script that gets a list of your sites from the Zerto PowerShell interface.

You can get this example script from my teams Github page. (BTW I work for Zerto Tech Alliances group) I’ve tried to keep this script as simple as possible, it’s task is simply to get the names of the sites paired to your ZVM.

Let’s break down the script and explain what it does.

#################################################################
# Template-PowerShell-cmdlets.ps1
# 
# By Justin Paul, Zerto Technical Alliances Architect
# Contact info: jp@zerto.com
# Repo: https://www.github.com/Zerto-ta-public/Script-Templates
#
#################################################################

################ Variables for your script ######################
#Zerto Info
$ZVMServer = "172.16.1.20"
$ZVMPort = 9080
$ZVMUser = "administrator"
$ZVMPass = "password"

################ Load Zerto PowerShell SnapIn ###################
Add-PSSnapin Zerto.PS.Commands
################ Your Code Below Here ###########################

# example command to check commectivity to ZVM
Get-Sites -zvmip $ZVMServer -zvmport $ZVMPort -username $ZVMUser -password $ZVMPass

Lines 1-8 – These are documentation lines that explain what the script does and who it was written by etc. These lines will obviously change for the scripts you write.

Lines 12-15 – System variables, these variables define how to connect to ZVM, if you write a script and use variables it is always good to define them at the top of the script so others know what their values are.

Line 18 – This line loads the Zerto PowerShell SnapIn. Without this line, PowerShell will not know any of the Zerto related commands.

Line 22 – This is the Get Sites command. This command takes the ZVM login information and then asks ZVM for the sites that are connected to it.

If you were to eliminate all of the documentation from this script and enter your login information directly, this entire script could be condensed to two lines.

Add-PSSnapin Zerto.PS.Commands
Get-Sites -zvmip 172.16.1.20 -zvmport 9080 -username administrator -password password

Bottom line: PowerShell scripting can be super simple and effective. If PowerShell is able to accomplish your goal, then I highly recommend it.

REST API Examples

If we wanted to achieve the same results with the REST API we can do that, however as you will see it takes many more lines of code and is not as trivial.

#################################################################
# Template-REST-From-PoSH.ps1
# 
# By Justin Paul, Zerto Technical Alliances Architect
# Contact info: jp@zerto.com
# Repo: https://www.github.com/Zerto-ta-public/Script-Templates
#
#################################################################

################ Variables for your script ######################

$strZVMIP = "172.16.1.20"
$strZVMPort = "9669"
$strZVMUser = "administrator@vsphere.local"
$strZVMPwd = "password"

############### ignore self signed SSL ##########################
if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
{
$certCallback = @"
    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()
#################################################################

## Perform authentication so that Zerto APIs can run. Return a session identifier that needs tobe inserted in the header for subsequent requests.
function getxZertoSession ($userName, $password){
    $baseURL = "https://" + $strZVMIP + ":" + $strZVMPort
    $xZertoSessionURL = $baseURL +"/v1/session/add"
    $authInfo = ("{0}:{1}" -f $userName,$password)
    $authInfo = [System.Text.Encoding]::UTF8.GetBytes($authInfo)
    $authInfo = [System.Convert]::ToBase64String($authInfo)
    $headers = @{Authorization=("Basic {0}" -f $authInfo)}
    $contentType = "application/json"
    $xZertoSessionResponse = Invoke-WebRequest -Uri $xZertoSessionURL -Headers $headers -Method POST -Body $body -ContentType $contentType
    #$xZertoSessionResponse = Invoke-WebRequest -Uri $xZertoSessionURL -Headers $headers -Body $body -Method POST
    return $xZertoSessionResponse.headers.get_item("x-zerto-session")
}

#Extract x-zerto-session from the response, and add it to the actual API:
$xZertoSession = getxZertoSession $strZVMUser $strZVMPwd
$zertoSessionHeader = @{"x-zerto-session"=$xZertoSession}
$zertoSessionHeader_xml = @{"Accept"="application/xml"
"x-zerto-session"=$xZertoSession}

################ Your Script starts here #######################
#Invoke the Zerto API:
$peerListApiUrl = "https://" + $strZVMIP + ":"+$strZVMPort+"/v1/peersites"

#Iterate with JSON:
$peerListJSON = Invoke-RestMethod -Uri $peerListApiUrl -Headers $zertoSessionHeader
foreach ($peer in $peerListJSON){
    Write-Host $peer.HostName  $peer.PeerSiteName
}

##End of script
  • Lines 1-8 – Again these are documentation about the script. They are the same as the Powershell cmdlet script.
  • Line 12-15 – Just like the Zerto PowerShell cmdlet script we have variables to connect to ZVM
  • Line 17-49 – These lines tell PowerShell to ignore the self-signed SSL certificate on our ZVM server. If you were using BaSH these lines can be replaced by a single cURL switch. So certainly Scripting language dependent
  • Line 51-69 – this section gets a Zerto REST API session. A session is only given to scripts that successfully authenticate to the REST API. Unlike PowerShell cmdlets who send a username and password with each command, REST APIs do not. They expect the client and server to have already authenticated via a session.
  • Line 71-79 – these lines are all used to replace the Zerto cmdlet “Get-Sites”.
    • Line 73 – Format the REST command url
    • Line 76 – This line takes the REST URL, calls it, then saves the response into a variable
    • Line 77-79 Loop to print each of the sites in the variable to screen.

Scripting with REST APIs is clearly much more involved. However, in many cases, it is the only way to go, depending on what operating system you want to run the script from, or what the goal of the script is… sometimes REST is the only option. Some use cases for REST only include:

  • Native scripts for Linux
  • Update detailed VPG info

Will Zerto Support help with my script?

Simply put no.

Zerto encourages partners and end users to leverage the interfaces available, however, it would be impossible to troubleshoot every script that everyone writes. In most cases, the actual cmdlet or REST API is working fine, but the logic before and after those calls is causing issues. Posting on the myZerto Forum is probably the best course of action as it is monitored by SE’s and other technical people at Zerto who are willing to help point you in the right direction.

If you believe that there is an issue with the ZVM (which serves the REST API as well as answers PowerShell cmdlet requests), Zerto support can be contacted for that.

Troubleshooting steps I use

Even though I work for Zerto I always try a few things before asking for help. Mainly so I don’t look dumb 🙂

  1. Is the ZVM service operating properly (can you login and use the GUI)?
  2. Are there any firewalls blocking port 9669 (REST) or 9080 (PowerShell) from where you are?
  3. Are you using the proper credentials for the interface you are using? (remember PowerShell uses administrator/password unless you changed it)
  4. Can you run the “template” scripts I showed you earlier in this post? These scripts are as basic as it gets. If they don’t run the issue may be ZVM… if they do run chances are your script has some errors that are preventing it from ever talking to ZVM.

Share This Post

Leave a Reply