Start-IpsAwsPrepareJob.ps1

<#
.SYNOPSIS
Start an Image Portability Service job to prepare an AWS image.

.DESCRIPTION
Starts an Image Portability Service job to prepare an AWS image.

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

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

.PARAMETER AwsCwSecretId
Specifies the credential wallet id for the credentials used to access AWS.

.PARAMETER XdReconfigure
Specifies options for reconfiguring the VDA during prepare. If provided, 'XenDesktopVdaSetup.exe /reconfigure' will be run with the specified options. Acceptable options are /controllers, /portnumber, and /enable_hdx_ports.

.PARAMETER AwsTargetSnapshotId
Specifies the id of the snapshot containing the image to be prepared.

.PARAMETER AwsRegion
Specifies the AWS region where the prepare will take place.

.PARAMETER AwsSubnetId
Specifies the subnet id in AWS where the prepare appliance will be created.

.PARAMETER AwsSecurityGroupIds
Specifies an array of security groups to attach to the network interface of the prepare appliance VM.

.PARAMETER CreateAMI
If specified, the job output will be an AMI created by importing the prepared image, otherwise the job output will be an EC2 EBS volume containing the prepared image.

.PARAMETER LicenseType
If specified and 'CreateAMI' is specified, the type of license to use for the AMI. Must be one of 'BYOL' or 'AMI'. If unspecified and 'CreateAMI' is specified, then AWS import will deduce the license type.

.PARAMETER RoleName
If specified and 'CreateAMI' is specified, the role to use for VM import. If unspecified and 'CreateAMI' is specified, then AWS import will use the role 'vmimport'.

.PARAMETER Md5Hash
If specified, validate the target disk MD5 hash against the one specified, before preparing it.

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

.PARAMETER InstallMisa
If specified, and the ProvisioningType 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 ProvisioningType is Mcs, the latest version of MCS security agent will be installed during prepare.

.PARAMETER InstallMcsio
If specified, the version of the MCS IO driver that matches the VDA installed on the image, will be installed during prepare.

.PARAMETER ForceMcsio
If specified, the latest version of the MCS IO driver will be installed during prepare.

.PARAMETER UpdateLayerRepo
If specified, the AppLayering layer repository URL in the image will be updated.

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

.PARAMETER RunCitrixOptimizer
If specified, run Citrix Optimizer with the default template for the image on the image during prepare.

.PARAMETER Chkdsk
If specified, the Windows chkdsk utility will be run against the image during prepare.

.PARAMETER Defrag
If specified, the Windows defrag utility will be run against 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 prepare 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.

.NOTES
Before using this cmdlet to create an AMI, see the Amazon Web Services VM Import/Export User Guide [https://docs.aws.amazon.com/vm-import/latest/userguide] for
information about image import and its requirements.

.INPUTS
None.

.OUTPUTS
PSCustomObject. A job description which can be consumed by the Wait-IpsJob cmdlet.

.EXAMPLE
PS> $PrepareParams = @{
        CustomerId = 'a7f4wb1example'
        SecureClientId = '7fed2a1e-1495-46b7-8fd3-5644764af395'
        SecureSecret = '9T.3Q~MGlnB6NNgpNUUWrcquVzODrdGK~eXampLe'
        ResourceLocationId = '47251663-6710-4f76-854a-2385e3fe002d'
        ProvisioningType = 'Mcs'
        XdReconfigure = @(
            @{
                ParameterName = "controllers"
                ParameterValue = "cloudy-cc1.wse2edev.cloudy cloudy-cc2.wse2edev.cloudy"
            },
            @{
                ParameterName = "portnumber"
                ParameterValue = "80"
            }
        )
        Tags = @{
            MyTagName = "MyTagValue"
        }
        AwsCwSecretId = 'aws-creds'
        AwsRegion = 'us-east-2'
        AwsSubnetId = 'subnet-d7880448508711ed0'
        AwsTargetSnapshotId = 'snap-087af7cd8fdfa545f'
        DomainUnjoin = $True
        InstallMisa = $True
        InstallMcsio = $True
        UpdateLayerRepo = '\\layer-server\LayerShare'
        InstallUpl = $True
        Chkdsk = $True
        Prefix = 'acme'
        Timeout = 7200
    }
PS> Start-IpsAwsPrepareJob @PrepareParams -Force -OverwriteLog -Verbose | Wait-IpsJob

.EXAMPLE
PS> $PrepareParams = @{
        CustomerId = 'a7f4wb1example'
        SecureClientId = '7fed2a1e-1495-46b7-8fd3-5644764af395'
        SecureSecret = '9T.3Q~MGlnB6NNgpNUUWrcquVzODrdGK~eXampLe'
        ResourceLocationId = '47251663-6710-4f76-854a-2385e3fe002d'
        ProvisioningType = 'Pvs'
        InstallPvs = '2308'
        XdReconfigure = @(
            @{
                ParameterName = "controllers"
                ParameterValue": "cloudy-cc1.wse2edev.cloudy"
            },
            @{
                ParameterName = "portnumber"
                ParameterValue = "80"
            }
        )
        Tags = @{
            MyTagName = "MyTagValue"
        }
        AwsCwSecretId = 'aws-creds'
        AwsRegion = 'us-east-2'
        AwsSubnetId = 'subnet-d7880448508711ed0'
        AwsTargetSnapshotId = 'snap-087af7cd8fdfa545f'
        CreateAMI = $True
        Defrag = $True
        Prefix = 'acme'
        Timeout = 7200
        LogFileName = 'PrepareAwsExample.log'
    }
PS> Start-IpsAwsPrepareJob @PrepareParams -Force -OverwriteLog -Verbose | Wait-IpsJob
#>


Function Start-IpsAwsPrepareJob
{
    [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')]
        [Alias("CloudProvisioningType")]
        [string]$ProvisioningType,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [Alias("CloudCwSecretId")]
        [string]$AwsCwSecretId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [psobject[]]$XdReconfigure,
        [Parameter(Mandatory = $false)]
        [string]$Md5Hash,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$Deployment,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$ResourceLocationId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$AssetsId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [HashTable]$Tags = @{},
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [int]$Timeout,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$Prefix,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$AwsRegion,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$AwsSubnetId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string[]]$AwsSecurityGroupIds,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$AwsTargetSnapshotId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$CreateAMI = $false,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [ValidateSet("AWS", "BYOL", IgnoreCase = $false)]
        [string]$LicenseType,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$RoleName,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [HashTable]$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')]
        [bool]$InstallMcsio = $false,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$ForceMcsio = $false,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$UsePublicIP = $false,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$InstallPvs,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$UpdateLayerRepo,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$InstallUpl,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$Chkdsk,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$Defrag,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$EnableRdp,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$DryRun = $false,
        [Parameter(Mandatory = $false)]
        [string]$SecureClientId,
        [Parameter(Mandatory = $false)]
        [string]$SecureSecret,
        [Parameter(Mandatory = $false)]
        [string]$LogFileName = 'PrepareAws.log',
        [Parameter(Mandatory = $false)]
        [string]$LogFileDir,
        [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
        $Verbose = $VerbosePreference -eq 'Continue'
        LogInit $MyInvocation $LogFileDir $LogFileName $OverwriteLog $Verbose

        VersionCheck $Deployment $CustomerId

        # 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
            $Deployment = $configData.Deployment
            $DryRun = if ($null -ne $configData.DryRun) { $configData.DryRun } else { $False }
        }
        else
        {
            $configData = $Null
        }

        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 *****"
            $parameters = GetVariablesAsHash
            $platformData = Format-AwsData -ConfigData $configData -Parameters $parameters -Verbose $Verbose
            $prepareData = Format-PrepareData -Platform "Aws" -ConfigData $configData -Parameters $parameters -Verbose $Verbose

            # Convert the object to JSON to use in the POST body (Note: Default depth is 2 when serializing)
            $json = ($prepareData + $platformData) | ConvertTo-Json -Depth 10
            LogIt "Prepare $($prepareData["provisioningType"]) POST body $json" $Verbose

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

            # Send the POST
            try
            {
                $response = Invoke-CCRestMethod -method 'Post' -deployment $Deployment -serviceRoute "images/`$prepare" -customerId $CustomerId -secureClientId $SecureClientId -secureSecret $SecureSecret -query $query -json $json
                $JobId = $response.id
                LogIt "Image Prepare started with id $JobId"
            }
            catch
            {
                $JobId = "Job failed to start"
                LogFatal "Failed to start prepare: $_"
            }
        }
        catch
        {
            LogFatalException -Message "Workflow failed" -Exception $_.Exception
        }
        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
            }
        }
    }
}