Start-IpsAzurePrepareJob.ps1

<#

.SYNOPSIS
  Implement an Azure image prepare job.

.DESCRIPTION
  Implement an image prepare job. This function supports preparing image on Azure platform.


.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 ResourceLocationId
Specifies the UUID of the resource location of the Citrix Connector Appliance in Azure.

.PARAMETER CloudProvisioningType
Specifies the Citrix provisioning type that will be used in the cloud. Possible values are Mcs and Pvs.

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

.PARAMETER XdReconfigure
Specifies options to run XenDesktopVdaSetup.exe with during prepare.

.PARAMETER CloudDiskName
Specifies the name of the managed disk that will be prepared.

.PARAMETER CloudSnapshotName
Specifies the name of the snapshot that will be prepared.

.PARAMETER OutputDiskName
If specified, the output of the prepare will be a managed disk with the supplied name.

.PARAMETER OutputSnapshotName
If specified, the output of the prepare will be a snapshot with the supplied name.

.PARAMETER AzureSubscriptionId
Specifies the id of the Azure subscription where the prepare will take place.

.PARAMETER AzureLocation
Specifies the Azure location name where the prepare appliance will be created.

.PARAMETER AzureVirtualNetworkResourceGroupName
Specifies the resource group of the vnet that the prepare appliance VM's network interface will be connected to.

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

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

.PARAMETER AzureVmResourceGroup
If specified, the prepare appliance VM's will be created in the supplied resource group. Otherwise a resource group will be created for the prepare appliance VM and deleted when the preapre operation is complete.

.PARAMETER TargetResourceGroup
Specifies the Azure resource group name where the disk that will be prepared is located.

.PARAMETER DomainUnjoin
If specified, the image will be unjoined from the domain during prepare.

.PARAMETER InstallMisa
If specified, and the CloudProvisioningType is Mcs, the version of MCS security agent that matches the VDA installed on the image, will be installed during prepare.

.PARAMETER ForceMisa
If specified, and the CloudProvisioningType is Mcs, the latest version of MCS security agent will be installed during prepare.

.PARAMETER InstallPvs
If specified, and the CloudProvisioningType is Pvs, the specified version of the PVS driver will be installed on the image during preapre. The version specified should be the version of the PVS server in AWS.

.PARAMETER InstallUpl
If specified, the Citrix User Personaliztion Layer will be installed in the image during prepare.

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

.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> $PrepareParams = @{
        CustomerId = 'your Citrix customer ID'
        SecureClientId = '7fed2a1e-1495-46b7-8fd3-5644764af395'
        SecureSecret = 'your Citrix secure secret'
        ResourceLocationId = '47251663-6710-4f76-854a-2385e3fe002d'
        CloudProvisioningType = 'Mcs'
        CloudCwSecretId = 'azure-creds'
        XdReconfigure = (
            @{
                ParameterName = "controllers"
                ParameterValue = "cloudy-cc1.wse2edev.cloudy"
            },
            @{
                ParameterName = "portnumber"
                ParameterValue = "80"
            }
        )
        CloudDiskName = 'ManagedDiskToPrepare'
        OutputDiskName = 'MyPreparedDisk'
        Tags = @{
            MyTagName = "MyTagValue"
        }
        AzureSubscriptionId = 'd7880448-5087-11ed-bdc3-0242ac120002'
        AzureLocation = 'eastus'
        AzureVirtualNetworkResourceGroupName = 'ips-vnet-rg'
        AzureVirtualNetworkName = 'ips-vnet'
        AzureVirtualNetworkSubnetName = 'ips-vnet-subnet'
        TargetResourceGroup = 'MyDisksResourceGroup'
        DomainUnjoin = $True
        InstallMisa = $True
        InstallUpl = $True
        Prefix = 'acme'
        DryRun = $False
        Timeout = 7200
        LogFileName = '.\PrepareAzure.log'
    }
PS> Start-IpsAzurePrepareJob @PrepareParams -Force -OverwriteLog -Verbose | Wait-IpsJob

.EXAMPLE
PS> $PrepareParams = @{
        CustomerId = 'your Citrix customer ID'
        SecureClientId = '7fed2a1e-1495-46b7-8fd3-5644764af395'
        SecureSecret = 'your Citrix secure secret'
        ResourceLocationId = '47251663-6710-4f76-854a-2385e3fe002d'
        CloudProvisioningType = 'Pvs'
        CloudCwSecretId = 'azure-creds'
        XdReconfigure = (
            @{
                ParameterName = "controllers"
                ParameterValue = "cloudy-cc1.wse2edev.cloudy"
            },
            @{
                ParameterName = "portnumber"
                ParameterValue = "80"
            }
        )
        CloudSnapshotName = 'SnapshotToPrepare'
        OutputSnapshotName = 'MyPreparedSnapshot'
        Tags = @{
            MyTagName = "MyTagValue"
        }
        AzureSubscriptionId = 'd7880448-5087-11ed-bdc3-0242ac120002'
        AzureLocation = 'eastus'
        AzureVirtualNetworkResourceGroupName = 'ips-vnet-rg'
        AzureVirtualNetworkName = 'ips-vnet'
        AzureVirtualNetworkSubnetName = 'ips-vnet-subnet'
        AzureVmResourceGroup = 'ips-appliances-rg'
        TargetResourceGroup = 'MyDisksResourceGroup'
        InstallPvs = '2209'
        Prefix = 'acme'
        DryRun = $False
        Timeout = 7200
        LogFileName = '.\PrepareAzure.log'
    }
PS> Start-IpsAzurePrepareJob @PrepareParams -Force -OverwriteLog -Verbose | Wait-IpsJob

#>

Function Start-IpsAzurePrepareJob
{
    [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]$CloudProvisioningType,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$CloudCwSecretId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$CloudDiskName,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$CloudSnapshotName,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [psobject[]]$XdReconfigure,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$OutputDiskName,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$OutputSnapshotName,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$Deployment,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$ResourceLocationId,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$AzureSubscriptionId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$AzureLocation = "eastus",
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$TargetResourceGroup,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$AzureVirtualNetworkResourceGroupName,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$AzureVirtualNetworkName,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$AzureVirtualNetworkSubnetName,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$UsePublicIP = $false,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$AzureVmResourceGroup,
        [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 = "Standard_D2s_v3",
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$JobDebug,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$DomainUnjoin = $false,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$InstallMisa = $true,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$ForceMisa = $false,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$InstallPvs,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$InstallUpl,
        [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 = 'PrepareAzure.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
            $CloudProvisioningType = $configData.CloudProvisioningType
            $CloudCwSecretId = $configData.CloudCwSecretId
            $CloudDiskName = $configData.CloudDiskName
            $CloudSnapshotName = $configData.CloudSnapshotName
            $XdReconfigure = $configData.XdReconfigure
            $OutputDiskName = $configData.OutputDiskName
            $OutputSnapshotName = $configData.OutputSnapshotName
            $Deployment = $configData.Deployment
            if($configData.psobject.Properties.name -contains "PrepareResourceLocationId") { $ResourceLocationId = $configData.PrepareResourceLocationId }
            else { $ResourceLocationId = $configData.ResourceLocationId }
            $AzureSubscriptionId = $configData.AzureSubscriptionId
            if([String]::IsNullOrWhiteSpace($configData.AzureLocation)) { $AzureLocation = 'eastus' }
            else { $AzureLocation = $configData.AzureLocation }
            $AzureVirtualNetworkResourceGroupName = $configData.AzureVirtualNetworkResourceGroupName
            $AzureVirtualNetworkName = $configData.AzureVirtualNetworkName
            $AzureVirtualNetworkSubnetName = $configData.AzureVirtualNetworkSubnetName
            $UsePublicIP = $configData.UsePublicIP
            $TargetResourceGroup = $configData.TargetResourceGroup
            $AzureVmResourceGroup = $configData.AzureVmResourceGroup
            $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
            $DomainUnjoin = $configData.DomainUnjoin
            $InstallMisa = $configData.InstallMisa
            $ForceMisa = $configData.ForceMisa
            $InstallPvs = $configData.InstallPvs
            $InstallUpl = $configData.InstallUpl
            $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"
        }

        # Prepare
        try {
            LogIt "Starting prepare workflow"
            #
            # Run the prepare workflow
            #
            Write-Host "***** Call Method: PrepareImageJob *****"
            $platformPrepareData = @{
                subscriptionId = $AzureSubscriptionId
                azureRegion = $AzureLocation
                targetDiskResourceGroupName = $TargetResourceGroup
                VirtualNetworkResourceGroupName = $AzureVirtualNetworkResourceGroupName
                VirtualNetworkName = $AzureVirtualNetworkName
                VirtualNetworkSubnetName = $AzureVirtualNetworkSubnetName
                UsePublicIP = $UsePublicIP
                resourceGroup = $AzureVmResourceGroup
            }
            #Add default tags
            $Tags['ctx-user'] = ($env:UserName).ToLower()
            $prepareData = @{
                platform = "Azure"
                provisioningType = $CloudProvisioningType
                platformCredentialId = $CloudCwSecretId
                resourceLocationId = $ResourceLocationId
                XdReconfigure = $XdReconfigure
                tags = $Tags
                timeoutInSeconds = $Timeout
                prefix = $Prefix
                ceVmSku = $CeVmSku
                overwriteTargetFile = $Force.IsPresent
            }
            if ($CloudDiskName)
            {
                $platformPrepareData['targetDiskName'] = $CloudDiskName
            }
            elseif ($CloudSnapshotName)
            {
                $platformPrepareData['targetSnapshotName'] = $CloudSnapshotName
            }
            else
            {
                throw "One of the parameters CloudDiskName or CloudSnapshotName are required."
            }
            if ($AssetsId)
            {
                $prepareData['assetsId'] = $AssetsId
            }
            if ($DomainUnjoin)
            {
                $prepareData['domainUnjoin'] = $DomainUnjoin
            }
            if ($OutputDiskName)
            {
                $prepareData['outputDiskName'] = $OutputDiskName
            }
            elseif ($OutputSnapshotName)
            {
                $prepareData['outputSnapshotName'] = $OutputSnapshotName
            }
            if ($InstallUpl)
            {
                $prepareData['installUpl'] = $InstallUpl
            }
            if ($CloudProvisioningType -eq "Pvs")
            {
                if ($InstallPvs)
                {
                    $prepareData['installPvs'] = $InstallPvs
                }
                $prepareData['installMisa'] = $false
                $prepareData['forceMisa'] = $false
            }
            elseif ($CloudProvisioningType -eq "Mcs")
            {
                $prepareData['installMisa'] = $InstallMisa
                $prepareData['forceMisa'] = $ForceMisa
            }
            if ($JobDebug)
            {
                $prepareData['debug'] = $JobDebug
            }
            if ($Flags)
            {
                $prepareData['flags'] = $Flags
            }
            # Convert the object to JSON to use in the POST body (Note: Default depth is 2 when serializing)
            $json = ($prepareData + $platformPrepareData) | ConvertTo-Json -Depth 10
            LogIt "$($prepareData["CloudProvisioningType"]) Prepare POST body $json" $False

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

            # Send the POST
            try {
                $response = Invoke-CCRestMethod 'Post' $Deployment "images/`$prepare" $CustomerId $SecureClientId $SecureSecret $query $json
                $JobId = $response.id
                LogIt "Image Prepare started with id $JobId"
            } catch {
                $JobId = "Job failed to start"
                throw "Failed to start prepare: $_"
            }
        }
        catch {
            LogFatal "Workflow failed: $_"
        }
        finally {
            $output = [PSCustomObject]@{
                CustomerId = $CustomerId
                Deployment = $Deployment
                JobId = $JobId
                LogFileDir = $LogFileDir
                LogFileName = $LogFileName
            }
            Write-Output $output

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