Start-IpsGcpExportJob.ps1

<#
.SYNOPSIS
Start an Image Portability Service job to export an image from Google Cloud.

.DESCRIPTION
Starts an Image Portability Service job to export an image from Google Cloud to a virtual disk file on a SMB fileshare.
Start-IpsGcpPublishJob is an alias for this cmdlet.

.PARAMETER CustomerId
Specifies the customer id of the Citrix customer running this command.

.PARAMETER SecureClientId
Specifies the client id of the Citrix customer's API client.

.PARAMETER SecureSecret
Specifies the client secret of the Citrix customer's API client.

.PARAMETER ResourceLocationId
Specifies the UUID of the resource location of the Citrix Connector Appliance in GCP.

.PARAMETER CloudCwSecretId
Specifies the credential wallet id for the credentials used to access GCP.

.PARAMETER PrepareDiskName
Specifies the name of the disk that will be exported.

.PARAMETER GcpZone
Specifies the GCP zone name where the prepare appliance will be created.

.PARAMETER VpcNetworkName
Specifies the name of the VPC that the prepare appliance VM's network interface will be connected to.

.PARAMETER VpcNetworkSubnetName
Specifies the name of the VPC subnet that the prepare appliance VM's network interface will be connected to.

.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 UsePublicIP
If specified, the prepare appliance VM will be given a public IP.

.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 Tags
Specifies a hash table of string values to apply as labels to resources created by the export operation.

.PARAMETER NetworkTags
Specifies a hash table of string tag values to apply to the export appliance VM's network interface. The tags should be existing firewall tags.

.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 parameters specified are reported. No actual changes are made.

.PARAMETER Deployment
Specifies the service address to send the job request to. It defaults to api.layering.cloud.com. This can be used if necessary to send the request to a geo specific deployment such as api.eu.layering.cloud.com.

.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.

.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. A job description which can be consumed by the Wait-IpsJob cmdlet.

.EXAMPLE
PS> $ExportParams = @{
        CustomerId = 'a7f4wb1example'
        SecureClientId = '7fed2a1e-1495-46b7-8fd3-5644764af395'
        SecureSecret = '9T.3Q~MGlnB6NNgpNUUWrcquVzODrdGK~eXampLe'
        ResourceLocationId = '47251663-6710-4f76-854a-2385e3fe002d'
        CloudCwSecretId = 'gcp-creds'
        PrepareDiskName = 'marketing-gold'
        Tags = @{
            MyTagName = "MyTagValue"
        }
        GcpZone = 'us-east4-a'
        VpcNetworkName = 'ips-vnet'
        VpcNetworkSubnetName = 'ips-vnet-subnet'
        SmbHost = 'smbserver.example.com'
        SmbShare = 'disks'
        SmbPath = 'ips'
        SmbDiskName = 'marketing'
        SmbDiskFormat = 'VhdxDiskFormat'
        Prefix = 'acme'
        Timeout = 7200
        LogFileName = 'export.log'
    }
PS> Start-IpsGcpExportJob @ExportParams -Force -OverwriteLog -Verbose | Wait-IpsJob
#>


Function Start-IpsGcpExportJob
{
    [CmdletBinding(DefaultParameterSetName = 'cmd')]
    [Alias("Start-IpsGcpPublishJob")]
    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]$GcpZone = "us-east4-a",
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$VpcNetworkName,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$VpcNetworkSubnetName,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$UsePublicIP = $false,
        [Parameter(Mandatory = $true)]
        [string]$PrepareDiskName,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$CloudCwSecretId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string[]]$NetworkTags,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$AssetsId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [HashTable]$Tags = @{},
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [int]$Timeout = 7200,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$Prefix = "ce",
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$CeVmSku = "n1-standard-1",
        [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 = 'ExportGcpToSmb.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.PublishSmb.Host
            $SmbShare = $configData.PublishSmb.Share
            $SmbPath = $configData.PublishSmb.Path
            $SmbDiskName = $configData.PublishSmb.DiskName
            $SmbDiskFormat = $configData.PublishSmb.DiskFormat
            if([String]::IsNullOrWhiteSpace($SmbDiskFormat)) { $SmbDiskFormat = "VhdxDiskFormat" }
            $SmbCwId = $configData.PublishSmb.CwId
            if([String]::IsNullOrWhiteSpace($PrepareDiskName)) { $PrepareDiskName = $configData.PublishSmb.DiskName }
            $Deployment = $configData.Deployment
            if($configData.psobject.Properties.name -contains "ExportResourceLocationId") { $ResourceLocationId = $configData.ExportResourceLocationId }
            else { $ResourceLocationId = $configData.ResourceLocationId }
            if([String]::IsNullOrWhiteSpace($configData.GcpZone)) { $GcpZone = "us-east4-a" }
            else { $GcpZone = $configData.GcpZone }
            $VpcNetworkName = $configData.VpcNetworkName
            $VpcNetworkSubnetName = $configData.VpcNetworkSubnetName
            $UsePublicIP = $configData.UsePublicIP
            $NetworkTags = $configData.NetworkTags
            $CloudCwSecretId = $configData.CloudCwSecretId
            $AssetsId = $configData.AssetsId
            if($configData.psobject.Properties.name -contains "Tags") { $Tags = Convert-ObjectToHashtable $$configData.Tags }
            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 = $CloudCwSecretId
                targetDiskName = $PrepareDiskName
                zone = $GcpZone
                VpcNetworkName = $VpcNetworkName
                UsePublicIP = $UsePublicIP
            }
            if ($VpcNetworkSubnetName) {
                $platformExportData["VpcNetworkSubnetName"] = $VpcNetworkSubnetName
            }
            if ($NetworkTags) {
                $platformExportData["NetworkTags"] = $NetworkTags
            }
            if ($SmbPath) {
                $smbDiskPath = "$SmbShare\$SmbPath"
            } else {
                $smbDiskPath = $SmbShare
            }
            #Add default tags
            $Tags['ctx-user'] = ($env:UserName).ToLower()
            $exportData = @{
                platform = "Gcp"
                prefix = $Prefix
                ceVmSku = $CeVmSku
                ResourceLocationId = $ResourceLocationId
                timeoutInSeconds = $Timeout
                outputStorageLocation = @{
                    type = "SMB"
                    credentialId = $SmbCwId
                    host = $SmbHost
                    sharePath = $smbDiskPath
                }
                provisionType = "Thin"
                outputImageFilename = $SmbDiskName
                outputImageFormat = $SmbDiskFormat
                overwriteTargetFile = $Force.IsPresent
                tags = $Tags
            }
            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
            }

            # Send the POST
            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
            }
        }
    }
}