Start-IpsAwsPrepareJob.ps1

<#
 .Synopsis
  Implement an image prepare job.

 .Description
  Implement an image prepare job. This function supports preparing image on Aws platform.
#>

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')]
        [string]$CloudProvisioningType,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$CloudCwSecretId,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [psobject[]]$XdReconfigure,
        [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')]
        [psobject]$Tags = [PSCustomObject]@{},
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [int]$Timeout = 7200,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$Prefix = "ce",
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$AwsRegion,
        [Parameter(Mandatory = $true, ParameterSetName = 'cmd')]
        [string]$AwsSubnetId,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string[]]$AwsSecurityGroupIds,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [bool]$CeDebug,
        [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]$UsePublicIP = $false,
        [Parameter(Mandatory = $false, ParameterSetName = 'cmd')]
        [string]$InstallPvs,
        [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]$LogFileName = 'PrepareAws.log',
        [Parameter(Mandatory = $false)]
        [string]$LogFileDir = "",
        [Parameter(Mandatory = $false)]
        [switch]$OverwriteLog,
        [Parameter(Mandatory = $false)]
        [switch]$Force,
        [Parameter(Mandatory = $false)]
        [string]$AwsTargetSnapshotId = ""
    )

    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
            $XdReconfigure = $configData.XdReconfigure
            $Deployment = $configData.Deployment
            if($configData.psobject.Properties.name -contains "PrepareResourceLocationId") { $ResourceLocationId = $configData.PrepareResourceLocationId }
            else { $ResourceLocationId = $configData.ResourceLocationId }
            $AssetsId = $configData.AssetsId
            if($configData.psobject.Properties.name -contains "Tags") { $Tags = $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 }
            $CeDebug = $configData.CeDebug
            $DomainUnjoin = $configData.DomainUnjoin
            $InstallMisa = $configData.InstallMisa
            $ForceMisa = $configData.ForceMisa
            $InstallPvs = $configData.InstallPvs
            $Flags = $configData.Flags
            $AwsRegion = $configData.AwsRegion
            $AwsSecurityGroupIds = $configData.AwsSecurityGroupIds
            $AwsSubnetId = $configData.AwsSubnetId
            $UsePublicIP = $configData.UsePublicIP
            if([String]::IsNullOrWhiteSpace($configData.AwsTargetSnapshotId)) { 
                LogIt "Command Line snapshot value = $AwsTargetSnapshotId"
            } else {
                $AwsTargetSnapshotId = $configData.AwsTargetSnapshotId
                LogIt "Config File snapshot value = $AwsTargetSnapshotId"
           }
        }

        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 = @{
                region = $AwsRegion
                targetSnapshotId = $AwsTargetSnapshotId
                subnetId = $AwsSubnetId
                securityGroupIds = $AwsSecurityGroupIds
                usePublicIP = $UsePublicIP
            }
            #Add default tags
            $Tags = Convert-ObjectToHashtable $Tags
            $Tags['ctx-user'] = ($env:UserName).ToLower()
            $prepareData = @{
                platform = "Aws"
                provisioningType = $CloudProvisioningType
                platformCredentialId = $CloudCwSecretId
                resourceLocationId = $ResourceLocationId
                XdReconfigure = $XdReconfigure
                tags = $Tags
                timeoutInSeconds = $Timeout
                prefix = $Prefix
                ceDebug = $CeDebug
            }
            if ($AssetsId)
            {
                $prepareData['assetsId'] = $AssetsId
            }
            if ($DomainUnjoin)
            {
                $prepareData['domainUnjoin'] = $DomainUnjoin
            }
            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 ($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 {
            #Check if it comes to the end of pipeline
            if ($PSCmdlet.MyInvocation.PipelinePosition  -lt $PSCmdlet.MyInvocation.PipelineLength) {
                $output = [PSCustomObject]@{
                    CustomerId = $CustomerId
                    Deployment = $Deployment
                    JobId = $JobId
                    LogFileDir = $LogFileDir
                    LogFileName = $LogFileName
                }
                Write-Output $output
            } else{
                Clear-XDCredentials
            }
        }
    }
}