Start-IpsAhvExportJob.ps1

<#

.SYNOPSIS
Implement an Ahv image export job.

.DESCRIPTION
Implement an Ahv image export job. This function supports exporting an image from an Ahv platform
to a virtual disk file on SMB file share server.

.PARAMETER CustomerId
Specifies the Citrix customer id to run the command as.

.PARAMETER SecureClientId
Specifies the id of the access client for the Citrix customer that the export will be performed as.

.PARAMETER SecureSecret
Specifies the secret for the access client for the Citrix customer that the export will be performed as.

.PARAMETER SmbHost
Specifies the host name or IP address of the SMB server to export to.

.PARAMETER SmbShare
Specifies the share on the SMB server to export to.

.PARAMETER SmbPath
Specifies the path on the share of the SMB server to export to.

.PARAMETER SmbDiskName
Specifies the file name of the disk file that will be exported to the SMB server.

.PARAMETER SmbDiskFormat
Specifies the file format of the disk file that will be exported to the SMB server. Possible values are VhdDiskFormat and VhdxDiskFormat. The default value is VhdxDiskFormat.

.PARAMETER SmbCwId
Specifies the credential wallet id for the credentials used to access the SMB server.

.PARAMETER ResourceLocationId
Specifies the UUID of the resource location of the AHV system.

.PARAMETER CwSecretId
Specifies the credential wallet id for the credentials used to access the AHV server.

.PARAMETER PrismHost
Specifies the host name or IP address of the Prism server.

.PARAMETER PrismPort
Specifies the network port number of the Prism server. The default value is 9440.

.PARAMETER PrismSslCaCertificateFilePath
Specifies the path to the file containing the Prism SSL certificate.

.PARAMETER PrismSslCaCertificate
Specifies the Prism SSL certificate as a single string.

.PARAMETER PrismSslFingerprint
Specifies the fingerprint of the Prism SSL certificate. Specified as an alternative to the SSL certificate.

.PARAMETER PrismSslNoCheckHostname
If specified, do not to check the host name (default $false).

.PARAMETER SourceImageUuid
Specifies the UUID of the image on the Prism server that will be exported. Either SourceImageUuid or SourceVmUuid must be specified.

.PARAMETER SourceVmUuid
Specifies the UUID of the virtual machine on the Prism server that will be exported. Either SourceImageUuid or SourceVmUuid must be specified.

.PARAMETER ClusterUuid
Specifies the UUID of cluster of the Nutanix system where the source image or virtual machine resides.

.PARAMETER SubnetUuid
Specifies the UUID of subnet of the Nutanix system to use for the export.

.PARAMETER Timeout
Specifies an optional time limit for the export operation. If the export does not complete in less than this time it will fail with a timeout error. The default value is 7200.

.PARAMETER Prefix
Specifies an optional prefix which will be prepended to the name of assets created by the export operation. The default value is 'ce'.

.PARAMETER DryRun
If specified, a test run is performed and any problems with the paramters specified are reported. No actual changes are made.

.PARAMETER LogFileDir
Specifies the path to the file to log to. The local directory is the default.

.PARAMETER LogFileName
Specifies the name of the file to log to. 'ExportAhvToSmb.log' is the default.

.PARAMETER OverwriteLog
If specified the log file is overwritten otherwise it is appended to.

.PARAMETER Force
If specified then any existing export file is overwritten otherwise the operation will fail if the file specified to export to exists.

.INPUTS
None.

.OUTPUTS
PSCustomObject. Consumed by the Wait-IpsJob commandlet.

.EXAMPLE
PS> $ExportParams = @{
        CustomerId = 'your Citrix customer ID'
        SecureClientId = '7fed2a1e-1495-46b7-8fd3-5644764af395'
        SecureSecret = 'your Citrix secure secret'
        SmbHost = 'smbserver.example.com'
        SmbShare = 'disks'
        SmbPath = 'ips'
        SmbDiskName = 'marketing-image'
        SmbDiskFormat = 'VhdDiskFormat'
        SmbCwId = 'smbserver-creds'
        ResourceLocationId = '47251663-6710-4f76-854a-2385e3fe002d'
        CwSecretId = 'prism-creds'
        PrismHost = 'hostname.example.com'
        PrismPort = 9440
        PrismSslCaCertificate = "-----BEGIN CERTIFICATE-----\nMIIEETCCAvFgAwIBAgIJAPlOYwwTfEIXMA0GCSqGSIb3DQEBCwUAMIGTMQswCQYD\nVQQDDAJDQTEXMBUGCgmSJomT8ixkARkWB3ZzcGhlcmUxFTBTBgoJkiaJk/IsZAEZ\nFgVsb2NhbDELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFTATBgNV\nBAoMDGR5LXZjZW50ZXItMTEbMBkGA1UECwwSVk13YXJlIEVuZ2luZWVyaW5nMB4X\nDTIwMDcxNDIyNTUwOVoXDTMwMDcxMjIyNTUwOVowgZMxCzAJBgNVBAMMAkNBMRcw\nFQYKCZImiZ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2DoLkmdqwtzBgPDnqpXsf2bwA==\n-----END CERTIFICATE-----\n"
        PrismSslNoCheckHostname = $False
        SourceImageUuid = '123e4567-e89b-12d3-a456-426655440000'
        ClusterUuid = 'd0659a72-5087-11ed-bdc3-0242ac120002'
        SubnetUuid = 'd7880448-5087-11ed-bdc3-0242ac120002'
        Prefix = 'acme'
        DryRun = $False
        Timeout = 7200
        LogFileName = '.\PrismExport.log'
    }
PS> Start-IpsAhvExportJob @ExportParams -Force -OverwriteLog -Verbose | Wait-IpsJob

.EXAMPLE
PS> $ExportParams = @{
        CustomerId = 'your Citrix customer ID'
        SecureClientId = '7fed2a1e-1495-46b7-8fd3-5644764af395'
        SecureSecret = 'your Citrix secure secret'
        SmbHost = 'smbserver.example.com'
        SmbShare = 'disks'
        SmbPath = 'ips'
        SmbDiskName = 'marketing-image'
        SmbDiskFormat = 'VhdxDiskFormat'
        SmbCwId = 'smbserver-creds'
        ResourceLocationId = '47251663-6710-4f76-854a-2385e3fe002d'
        CwSecretId = 'prism-creds'
        PrismHost = 'hostname.example.com'
        PrismPort = 9440
        PrismSslFingerprint = 'db767676e22cefdf4112fc9e6ede9fc879627273'
        PrismSslNoCheckHostname = $False
        SourceVmUuid = '123e4567-e89b-12d3-a456-426655440000'
        ClusterUuid = 'd0659a72-5087-11ed-bdc3-0242ac120002'
        SubnetUuid = 'd7880448-5087-11ed-bdc3-0242ac120002'
        Prefix = 'acme'
        DryRun = $False
        Timeout = 7200
        LogFileName = '.\PrismExport.log'
    }
PS> Start-IpsAhvExportJob @ExportParams -Force -OverwriteLog -Verbose | Wait-IpsJob

#>

Function Start-IpsAhvExportJob
{
    [CmdletBinding(DefaultParameterSetName = 'cmd')]
    Param(
        [Parameter(Mandatory = $true, ParameterSetName = 'file')]
        [Obsolete("Use command-line arguments as input of configuration data.")]
        [string]$ConfigJsonFile,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$CustomerId,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$SmbHost,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [Obsolete("Specifying an alternate SMB port is not supported and this parameter will be ignored.")]
        [string]$SmbPort = $null,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$SmbShare,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$SmbPath,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$SmbDiskName,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$SmbDiskFormat = "VhdxDiskFormat",
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$SmbCwId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$Deployment,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$ResourceLocationId,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$CwSecretId,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$PrismHost,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [int]$PrismPort = 9440,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$PrismSslCaCertificateFilePath,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$PrismSslCaCertificate,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$PrismSslFingerprint,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$PrismSslNoCheckHostname,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$SourceImageUuid,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$SourceVmUuid,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$ClusterUuid,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$SubnetUuid,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$AssetsId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [int]$Timeout = 7200,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$Prefix = "ce",
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$JobDebug,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string[]]$Flags,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$DryRun = $false,
        [Parameter(Mandatory = $false)]
        [string]$SecureClientId = '',
        [Parameter(Mandatory = $false)]
        [string]$SecureSecret = '',
        [Parameter(Mandatory = $false)]
        [string]$LogFileDir = "",
        [Parameter(Mandatory = $false)]
        [string]$LogFileName = 'ExportAhvToSmb.log',
        [Parameter(Mandatory = $false)]
        [switch]$OverwriteLog,
        [Parameter(Mandatory = $false)]
        [switch]$Force
    )

    Begin
    {
        Add-PSSnapin Citrix.*
    }
    Process
    {
        # Initialize Logger
        # Set parameter 'Verbose' by internal parameter 'VerbosePreference', since the option -Verbose is occupied by powershell cmdlet
        if($VerbosePreference -eq 'Continue')
        {
            $Verbose = $True
        } else {
            $Verbose = $False
        }
        LogInit $LogFileDir $LogFileName $OverwriteLog $Verbose
        # Initialize config data
        if ($PSCmdlet.ParameterSetName -eq 'file') {
            LogIt "Loading config from $ConfigJsonFile"
            $configData = Get-Content -Raw -Path $ConfigJsonFile | ConvertFrom-Json
            LogIt "Config: $configData" $False
            $CustomerId = $configData.CustomerId
            $SmbHost = $configData.ExportSmb.Host
            $SmbShare = $configData.ExportSmb.Share
            $SmbPath = $configData.ExportSmb.Path
            $SmbDiskName = $configData.ExportSmb.DiskName
            $SmbDiskFormat = $configData.ExportSmb.DiskFormat
            if([String]::IsNullOrWhiteSpace($SmbDiskFormat)) { $SmbDiskFormat = "VhdDiskFormat" }
            $SmbCwId = $configData.ExportSmb.CwId
            $Deployment = $configData.Deployment
            if($configData.psobject.Properties.name -contains "ExportResourceLocationId") { $ResourceLocationId = $configData.ExportResourceLocationId }
            else { $ResourceLocationId = $configData.ResourceLocationId }
            $cwSecretId = $configData.cwSecretId
            $PrismHost = $configData.prismHost
            if([String]::IsNullOrWhiteSpace($configData.prismPort)) {
                $PrismPort = 9440
            } else {
                $PrismPort = [int]$configData.port
            }
            $PrismSslCaCertificate = $configData.PrismSslCaCertificate
            $PrismSslFingerprint = $configData.PrismSslFingerprint
            $PrismSslNoCheckHostname = $configData.PrismSslNoCheckHostname
            $SourceImageUuid = $configData.SourceImageUuid
            $SourceVmUuid = $configData.SourceVmUuid
            $ClusterUuid = $configData.ClusterUuid
            $SubnetUuid = $configData.SubnetUuid
            $AssetsId = $configData.AssetsId
            if([String]::IsNullOrWhiteSpace($configData.Timeout)) {
                $Timeout = 7200
            } else {
                $Timeout = [int]$configData.Timeout
            }
            if([String]::IsNullOrWhiteSpace($configData.Prefix)) {
                $Prefix = "ce"
            } else {
                $Prefix = $configData.Prefix
            }
            $JobDebug = $configData.Debug
            $Flags = $configData.Flags
        }

        try {
            # Authenticate to Citrix Cloud
            $parameters = AuthToCitrixCloud $CustomerId $SecureClientId $SecureSecret
            if ([string]::IsNullOrWhiteSpace($SecureClientId) -Or [string]::IsNullOrWhiteSpace($SecureSecret)) {
                $SecureClientId = $parameters.ApiKey
                $SecureSecret = $parameters.SecretKey
            }
        }
        catch {
            LogFatal "Failed to authenticate to Citrix Cloud"
        }

        # Export
        try {
            LogIt "Starting export workflow"
            #
            # Run the export workflow
            #
            Write-Host "***** Call Method: ExportImageJob overwrite: $($Force.IsPresent) *****"
            $platformExportData = @{
                platformCredentialId = $cwSecretId
                host = $PrismHost
                port = $PrismPort
                clusterUuid = $ClusterUuid
                subnetUuid = $SubnetUuid
                sourceImageUuid = $SourceImageUuid
            }
            if ($PrismSslCaCertificateFilePath -And (Test-Path -Path $PrismSslCaCertificateFilePath -PathType "Leaf"))
            {
                $platformExportData['sslCaCertificate'] = ((Get-Content $PrismSslCaCertificateFilePath) -join "`n") + "`n"
            }
            elseif ($prismSslCaCertificate)
            {
                # Replace raw string \n -> PowerShell-readable `n
                $PrismSslCaCertificate = $PrismSslCaCertificate.replace("\n", "`n")
                $platformExportData['sslCaCertificate'] = $PrismSslCaCertificate
            }
            if ($PrismSslFingerprint)
            {
                $platformExportData['sslFingerprint'] = $PrismSslFingerprint
            }
            if ($PrismSslNoCheckHostname)
            {
                $platformExportData['sslNoCheckHostname'] = $PrismSslNoCheckHostname
            }
            if ($SourceImageUuid)
            {
                $platformExportData['sourceImageUuid'] = $SourceImageUuid
            }
            if ($SourceVmUuid)
            {
                $platformExportData['sourceVmUuid'] = $SourceVmUuid
            }
            if ($SmbPath) {
                $smbDiskPath = "$SmbShare\$SmbPath"
            } else {
                $smbDiskPath = $SmbShare
            }

            $exportData = @{
                platform = "Ahv"
                prefix = $Prefix
                ResourceLocationId = $ResourceLocationId
                timeoutInSeconds = $Timeout
                outputStorageLocation = @{
                    type = "SMB"
                    credentialId = $SmbCwId
                    host = $SmbHost
                    sharePath = $smbDiskPath
                }
                outputImageFilename = $SmbDiskName
                outputImageFormat = $SmbDiskFormat
                provisionType = "Thin"
                overwriteTargetFile = $Force.IsPresent
            }
            if ($AssetsId)
            {
                $exportData['assetsId'] = $AssetsId
            }
            if ($JobDebug)
            {
                $exportData['debug'] = $JobDebug
            }
            if ($Flags)
            {
                $exportData['flags'] = $Flags
            }
            # Convert the object to JSON to use in the POST body (Note: Default depth is 2 when serializing)
            $json = ($exportData + $platformExportData) | ConvertTo-Json -Depth 10
            LogIt "$($exportData["provisionType"]) Export POST body $json" $False

            $query = @{
                "async" = $true
                "dryRun" = $DryRun
            }

            try {
                $response = Invoke-CCRestMethod 'Post' $Deployment "images/`$export" $CustomerId $SecureClientId $SecureSecret $query $json
                $JobId = $response.id
                LogIt "Image Export started with id $JobId"
            } catch {
                $JobId = "Job failed to start"
                throw "Failed to start export: $_"
            }
        }
        catch {
            LogFatal "Workflow failed: $_"
        }
        finally {
            $output = [PSCustomObject]@{
                CustomerId = $CustomerId
                Deployment = $Deployment
                JobId = $JobId
                LogFileDir = $LogFileDir
                LogFileName = $LogFileName
                SmbHost = $SmbHost
                SmbShare = $SmbShare
                SmbPath = $SmbPath
                SmbDiskName = $SmbDiskName
                SmbDiskFormat = $SmbDiskFormat
                SmbCwId = $SmbCwId
            }
            Write-Output $output

            # Clear credentials at end of pipeline
            if ($PSCmdlet.MyInvocation.PipelinePosition -eq $PSCmdlet.MyInvocation.PipelineLength) {
                Clear-XDCredentials
            }
        }
    }
}