Start-IpsAzureDiagnosticsJob.ps1

<#
.SYNOPSIS
Start an Image Portability Service job to extract diagnostics from an Azure image.

.DESCRIPTION
Start an Image Portability Service job to extract diagnostics from an Azure 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 Azure.

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

.PARAMETER TargetDiskName
Specifies the name of the managed disk that diagnostics will be extracted from.

.PARAMETER TargetSnapshotName
Specifies the name of the snapshot that diagnostics will be extracted from.

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

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

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

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

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

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

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

.PARAMETER SmbLocation
Specifies the SMB share folder where the diagnostics output will be put.

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

.PARAMETER CeLogs
If specified, logs will be collected from the compositing engine.

.PARAMETER WindowsEventLogs
If specified, Windows event logs will be colected from the image.

.PARAMETER IpsData
If specified, Image Portability Service specific data will collected from the image.

.PARAMETER Timeout
Specifies an optional time limit for the operation. If the job 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 diagnostics operation.

.PARAMETER Prefix
Specifies an optional prefix which will be prepended to the name of assets created by the diagnostics 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 diagnostics file is overwritten otherwise the operation will fail if the output file exists.

.INPUTS
None.

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

.EXAMPLE
PS> $DiagsParams = @{
        CustomerId = 'a7f4wb1example'
        SecureClientId = '7fed2a1e-1495-46b7-8fd3-5644764af395'
        SecureSecret = '9T.3Q~MGlnB6NNgpNUUWrcquVzODrdGK~eXampLe'
        ResourceLocationId = '47251663-6710-4f76-854a-2385e3fe002d'
        AzureCwSecretId = 'azure-creds'
        Tags = @{
            MyTagName = "MyTagValue"
        }
        AzureSubscriptionId = 'd7880448-5087-11ed-bdc3-0242ac120002'
        AzureLocation = 'eastus'
        AzureVirtualNetworkResourceGroupName = 'ips-vnet-rg'
        AzureVirtualNetworkName = 'ips-vnet'
        AzureVirtualNetworkSubnetName = 'ips-vnet-subnet'
        TargetDiskName = 'ManagedDiskForDiags'
        TargetResourceGroup = 'MyDisksResourceGroup'
        SmbLocation = "smb://example.com/share/folder"
        SmbCwId = "smb-credential-wallet-id"
        CeLogs = $True
        WindowsEventLogs = $True
        IpsData = $True
        Prefix = 'acme'
        DryRun = $False
        Timeout = 7200
        LogFileName = '.\DiagsAzure.log'
    }
PS> Start-IpsAzureDiagnosticsJob @DiagsParams -Force -OverwriteLog -Verbose | Wait-IpsJob

.EXAMPLE
PS> $DiagsParams = @{
        CustomerId = 'a7f4wb1example'
        SecureClientId = '7fed2a1e-1495-46b7-8fd3-5644764af395'
        SecureSecret = '9T.3Q~MGlnB6NNgpNUUWrcquVzODrdGK~eXampLe'
        ResourceLocationId = '47251663-6710-4f76-854a-2385e3fe002d'
        AzureCwSecretId = 'azure-creds'
        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'
        SmbLocation = "smb://example.com/share/folder"
        SmbCwId = "smb-credential-wallet-id"
        TargetResourceGroup = 'MyDisksResourceGroup'
        TargetSnapshotName = 'SnapshotToPrepare'
        CeLogs = $False
        Prefix = 'acme'
        DryRun = $False
        Timeout = 7200
        LogFileName = '.\DiagsAzure.log'
    }
PS> Start-IpsAzureDiagnosticsJob @DiagsParams -Force -OverwriteLog -Verbose | Wait-IpsJob
#>


Function Start-IpsAzureDiagnosticsJob
{
    Param(
        [Parameter(Mandatory = $true)]
        [string]$CustomerId,
        [Parameter(Mandatory = $true)]
        [string]$AzureCwSecretId,
        [Parameter(Mandatory = $false)]
        [string]$Deployment,
        [Parameter(Mandatory = $true)]
        [string]$ResourceLocationId,
        [Parameter(Mandatory = $true)]
        [string]$AzureSubscriptionId,
        [Parameter(Mandatory = $false)]
        [string]$AzureLocation = "eastus",
        [Parameter(Mandatory = $true)]
        [string]$TargetResourceGroup,
        [Parameter(Mandatory = $false)]
        [string]$TargetDiskName,
        [Parameter(Mandatory = $false)]
        [string]$TargetSnapshotName,
        [Parameter(Mandatory = $true)]
        [Uri]$SmbLocation,
        [Parameter(Mandatory = $true)]
        [string]$SmbCwId,
        [Parameter(Mandatory = $true)]
        [string]$AzureVirtualNetworkResourceGroupName,
        [Parameter(Mandatory = $true)]
        [string]$AzureVirtualNetworkName,
        [Parameter(Mandatory = $true)]
        [string]$AzureVirtualNetworkSubnetName,
        [Parameter(Mandatory = $false)]
        [bool]$UsePublicIP = $false,
        [Parameter(Mandatory = $false)]
        [string]$AzureVmResourceGroup,
        [Parameter(Mandatory = $false)]
        [string]$AssetsId,
        [Parameter(Mandatory = $false)]
        [HashTable]$Tags = @{},
        [Parameter(Mandatory = $false)]
        [int]$Timeout = 7200,
        [Parameter(Mandatory = $false)]
        [string]$Prefix,
        [Parameter(Mandatory = $false)]
        [string]$CeVmSku = "Standard_D2s_v3",
        [Parameter(Mandatory = $false)]
        [bool]$CeLogs = $true,
        [Parameter(Mandatory = $false)]
        [bool]$WindowsEventLogs = $true,
        [Parameter(Mandatory = $false)]
        [bool]$IpsData = $true,
        [Parameter(Mandatory = $false)]
        [bool]$DryRun = $false,
        [Parameter(Mandatory = $false)]
        [string]$SecureClientId,
        [Parameter(Mandatory = $false)]
        [string]$SecureSecret,
        [Parameter(Mandatory = $false)]
        [string]$LogFileDir,
        [Parameter(Mandatory = $false)]
        [string]$LogFileName = 'DiagsAzure.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
        $Verbose = $VerbosePreference -eq 'Continue'
        LogInit $MyInvocation $LogFileDir $LogFileName $OverwriteLog $Verbose

        VersionCheck $Deployment $CustomerId

        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"
        }

        try {
            Write-Host "***** Call Method: ImageDiagnosticsJob *****"
            $parameters = GetVariablesAsHash
            $platformData = Format-AzureData -Parameters $parameters -Verbose $Verbose
            $diagsData = Format-DiagsData -Platform "Azure" -Parameters $parameters -Verbose $Verbose

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

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

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