Workspace Environment Management

Automatically back up configuration sets using WEM APIs and Windows PowerShell

As a Workspace Environment Management (WEM) administrator, you might need to back up your configuration sets regularly to prevent settings from getting lost. You might want to trigger the backup, for example, every 12 hours, and manage the backup files locally and automatically. Using WEM public APIs and Windows PowerShell, you can accomplish that goal.

A general workflow is as follows:

  1. Apply for a Citrix Cloud API client
  2. Write a PowerShell script to back up your configuration sets
  3. Configure a scheduled task to run the script

Prerequisites

Before you start, make sure that you know your Citrix customer ID and the related API-base URLs.

Sign in to Citrix Cloud, navigate to Identity and Access Management > API Access, and find your Citrix customer ID.

Citrix Customer ID

The API-base URLs, including Citrix Auth API base URL and WEM API base URL, are related to the region of Citrix Cloud you’re connecting to. The region is determined when you onboard to Citrix Cloud. You can also query your region in Account Settings.

Region

You can find the API-base URLs by checking the following table.

Region Citrix Auth API base URL WEM API base URL
United States (US) api-us.cloud.com api.wem.cloud.com
European Union (EU) api-eu.cloud.com eu-api.wem.cloud.com
Asia Pacific South (AP-S) api-ap-s.cloud.com aps-api.wem.cloud.com
Japan (JP) api.citrixcloud.jp jp-api.wem.citrixcloud.jp

For more information about the API base URLs, see Get Started With Citrix Cloud APIs and WEM API overview.

Apply for a Citrix Cloud API client

Navigate to Identity and Access Management > API Access. Type the name of your secure client, click Create Client, and save the secure client ID and client secret locally.

API secure client

Write a PowerShell script to back up your configuration sets

Use the following PowerShell script and save it as Invoke-WEMConfigSetBackupAPI.ps1. Be sure to replace the variables at the beginning of the script.


# replace the variables before running the script

$CitrixCustomerId = 'your-citrix-customer-id'
$CitrixAuthAPIBaseURL = 'api-us.cloud.com'
$CitrixWEMAPIBaseURL = 'api.wem.cloud.com'
$ClientId = 'your-api-client-id'
$ClientSecret = 'your-api-client-secret'

$ConfigSetsToBackUp = @('Default Site', 'MyConfigSet') # leave it empty if you want to back up all configuration sets
$FolderToSaveBackup = 'C:\ProgramData'

# get bearer token

$ErrorActionPreference = 'Stop'

$URL = "https://${CitrixAuthAPIBaseURL}/cctrustoauth2/${CitrixCustomerId}/tokens/clients"
$Body = "grant_type=client_credentials&client_id=${ClientId}&client_secret=${ClientSecret}"
$Response = Invoke-RestMethod -Method 'Post' -Uri $URL -Body $Body -ContentType 'application/x-www-form-urlencoded'

$BearerToken = $Response.access_token

if ([string]::IsNullOrEmpty($BearerToken))
{
    throw 'Cannot retrieve bearer token.'
}

Write-Host "Retrieved bearer token successfully."

# back up WEM configuration sets

if (-not (Test-Path -Path $FolderToSaveBackup -PathType 'Container'))
{
    throw 'The folder to save backup not exists.'
}

$Headers = @{
    'Citrix-CustomerId' = $CitrixCustomerId
    'Accept' = 'application/json'
    'Authorization' = "CWSAUTH bearer=${BearerToken}"
}

if ($ConfigSetsToBackUp.Count -eq 0 -or $ConfigSetsToBackUp -eq $null)
{
    $URL = "https://${CitrixWEMAPIBaseURL}/services/wem/sites"
    $Response = Invoke-RestMethod -Method 'Get' -Uri $URL -Headers $Headers
    $ConfigSetsToBackUp = $Response.items |% { $_.name }
}

$ConfigSetsToBackUp | ForEach-Object {
    Write-Host "Backing up configuration set ""$_"""
    $URL = "https://${CitrixWEMAPIBaseURL}/services/wem/sites/%24export?name=$_"
    Write-Host "GET $URL"
    $Response = Invoke-RestMethod -Method 'Get' -Uri $URL -Headers $Headers
    $Timestamp = Get-Date -Format "yyyyMMddHHmmss"
    $Response | ConvertTo-Json -Depth 10 | Out-File (Join-Path $FolderToSaveBackup "${_}-${Timestamp}.json")
}

<!--NeedCopy-->

For more information about bearer tokens, see Get Started With Citrix Cloud APIs.

For more information about using the WEM API to back up configuration set, see Exporting WEM configuration set API.

Note:

Each bearer token expires after an hour. To avoid frequently invoking the Citrix Cloud auth APIs and WEM APIs, cache the bearer token and reuse it if the backup duration takes less than an hour.

If you encounter the error 504 Gateway Time-out, it likely means that your configuration set is too large, causing the backup time to exceed the 1-minute API timeout. In such cases, try using the following PowerShell script instead. Note that this script uses APIs that are not currently public, and these APIs may change in the future.


# replace the variables before running the script

$CitrixCustomerId = 'your-citrix-customer-id'
$CitrixAuthAPIBaseURL = 'api-us.cloud.com'
$CitrixWEMAPIBaseURL = 'api.wem.cloud.com'
$ClientId = 'your-api-client-id'
$ClientSecret = 'your-api-client-secret'

$ConfigSetsToBackUp = @('Default Site', 'MyConfigSet') # leave it empty if you want to back up all configuration sets
$FolderToSaveBackup = 'C:\ProgramData'

# get bearer token

$ErrorActionPreference = 'Stop'

$URL = "https://${CitrixAuthAPIBaseURL}/cctrustoauth2/${CitrixCustomerId}/tokens/clients"
$Body = "grant_type=client_credentials&client_id=${ClientId}&client_secret=${ClientSecret}"
$Response = Invoke-RestMethod -Method 'Post' -Uri $URL -Body $Body -ContentType 'application/x-www-form-urlencoded'

$BearerToken = $Response.access_token

if ([string]::IsNullOrEmpty($BearerToken))
{
    throw 'Cannot retrieve bearer token.'
}

Write-Host "Retrieved bearer token successfully."

# back up WEM configuration sets

if (-not (Test-Path -Path $FolderToSaveBackup -PathType 'Container'))
{
    throw 'The folder to save backup not exists.'
}

$Headers = @{
    'Citrix-CustomerId' = $CitrixCustomerId
    'Accept' = 'application/json'
    'Authorization' = "CWSAUTH bearer=${BearerToken}"
}

$URL = "https://${CitrixWEMAPIBaseURL}/services/wem/sites"
$Response = Invoke-RestMethod -Method 'Get' -Uri $URL -Headers $Headers
$Sites = $Response.items

if ($ConfigSetsToBackUp -ne $null -and $ConfigSetsToBackUp.Count -gt 0)
{
    $Sites = $Sites | Where-Object { $_.name -in $ConfigSetsToBackUp }
}

$Sites | ForEach-Object {
    $Name = $_.name
    Write-Host "Backing up configuration set `"$Name`""
    $URL = "https://${CitrixWEMAPIBaseURL}/services/wem/export/site?async=true"
    $FolderName = "BACKUPFOLDER-" + [Guid]::NewGuid().ToString()
    $Body = @{
        folderName = $FolderName
        id = $_.id
        name = $_.name
        type = 'Configuration set'
    } | ConvertTo-Json
    $Response = Invoke-RestMethod -Method 'Post' -Uri $URL -Headers $Headers -Body $Body -ContentType 'application/json; charset=utf-8'

    Write-Host "Waiting for the backup job to complete..."
    $URL = "https://${CitrixWEMAPIBaseURL}/services/wem/export/site/recentJobs"
    do
    {
        Start-Sleep -Seconds 5
        $Response = Invoke-RestMethod -Method 'Get' -Uri $URL -Headers $Headers
        $BackupJob = $Response.backup[0]
        $IsOnGoing = $BackupJob.id -eq $_.id -and $BackupJob.status -eq 'Running'
    } while ($IsOnGoing)

    $URL = "https://${CitrixWEMAPIBaseURL}/services/wem/export/site/contentView?name=${FolderName}"
    $Response = Invoke-RestMethod -Method 'Get' -Uri $URL -Headers $Headers

    $Timestamp = Get-Date -Format "yyyyMMddHHmmss"
    $Response | ConvertTo-Json -Depth 10 | Out-File (Join-Path $FolderToSaveBackup "${Name}-${Timestamp}.json") -Encoding utf8

    $URL = "https://${CitrixWEMAPIBaseURL}/services/wem/export?prefix=site%2F${FolderName}%2F"
    $Response = Invoke-RestMethod -Method 'Delete' -Uri $URL -Headers $Headers
}

<!--NeedCopy-->

Configure a scheduled task to run the script

On a machine with access to Citrix Cloud, start Task Scheduler from the Windows Start menu or start taskschd.msc from the Windows command prompt.

You can create a folder named WEM scheduled task.

In the folder, create a task named launch Invoke-WEMConfigSetBackupAPI.ps1. Add a new trigger repeat every 12 hours for a duration of 1 day and add a new action of starting script Invoke-WEMConfigSetBackupAPI.ps1.

Task Scheduler

Automatically back up configuration sets using WEM APIs and Windows PowerShell