MigrationProfile/HyperVMigrationProfile.psm1

Import-Module -Name @(Join-Path $PSScriptRoot .. | Join-Path -ChildPath Util | Join-Path -ChildPath Util)

function New-RMHyperVMigrationProfile {
    param(
        [Parameter(Mandatory)]
        [System.Object] $CloudAccount,

        [Parameter(Mandatory)]
        [System.Object] $Entitlement,

        [Parameter(Mandatory)]
        [System.Object] $Source,

        [Parameter(Mandatory)]
        [System.Object] $ScheduledAt,

        [string] $TransferMethod,

        [Parameter(Mandatory)]
        [string] $TargetVMName,

        [string] $DiskType,

        [string] $Cluster,

        [string] $HostName,

        [int] $RAM,

        [int] $CPU,

        [Parameter(Mandatory)]
        [System.Object[]] $DestinationNICConfig,

        [string] $DefaultGateway,

        [string] $PrimaryDNS,

        [string] $SecondaryDNS,

        [System.Object] $ResizeMountPoint,

        [string] $NetBIOSName,

        [bool] $Sysprep,

        [hashtable] $ConvertFileSystem,

        [string] $MigrationExtension,

        [string] $MigrationExtensionId,

        [string] $MigrationExtensionOSM,

        [string] $MigrationExtensionIdOSM,

        [string] $UpgradeOSVersion,

        [bool] $InPlaceUpgrade,

        [hashtable] $OSHardening,

        [bool] $InstallAzureARC,

        [bool] $ConnectARCAgent,

        [System.Object] $InstallAzureARCParameter,

        [bool] $RemoveRMSAgent,

        [bool] $IgnoreValidationError,

        [bool] $InstallAWSSSMAgent,

        [bool] $InstallAWSCloudWatchAgent,

        [bool] $DisableTargetDNSRegistration,

        [bool] $ShutdownSource,

        [bool] $ShutdownTarget,

        [hashtable] $MigrationInstruction,

        [bool] $EnableCloudFilesMigration,

        [Parameter(Mandatory)]
        [System.Object[]] $SelectedMount,

        [Parameter(Mandatory)]
        [System.Object] $TargetInventory
    )

    $MigrationExtensionIdArray = @()
    if (![string]::IsNullOrEmpty($MigrationExtensionId)) {
        $MigrationExtensionIdArray += $MigrationExtensionId
    }

    $MigrationExtensionArray = @()
    if (![string]::IsNullOrEmpty($MigrationExtension)) {
        $MigrationExtensionArray += $MigrationExtension
    }

    $MigrationExtensionIdOSMArray = @()
    if (![string]::IsNullOrEmpty($MigrationExtensionIdOSM)) {
        $MigrationExtensionIdOSMArray += $MigrationExtensionIdOSM
    }

    $MigrationExtensionOSMArray = @()
    if (![string]::IsNullOrEmpty($MigrationExtensionOSM)) {
        $MigrationExtensionOSMArray += $MigrationExtensionOSM
    }

    $InstallApplication = @()
    if ($InstallAzureARC) {
        $InstallApplication += @{
            "name"       = "AZURE_ARC"
            "parameters" = $InstallAzureARCParameter
        }
    }

    if ($InstallAWSCloudWatchAgent) {
        $InstallApplication += @{
            "name"       = "AWS_CLOUDWATCH"
            "parameters" = $null
        }
    }

    $SelectedCluster = $null
    $SelectedHost = $null
    if (![string]::IsNullOrEmpty($Cluster)) {
        $SelectedCluster = $TargetInventory.attributes.hyperv.clusters | Where-Object { $_.name -eq $Cluster }
        $SelectedHost = $SelectedCluster.hosts | Where-Object { $_.name -eq $HostName }
    }

    $NetworkInterfaces = Get-RMHyperVNetworkInterfaces -DestinationNICConfig $DestinationNICConfig `
        -SelectedHost $SelectedHost

    $CurrentTime = Get-Date -Format "yyyy/MM/dd HH:mm:ss"
    $MigrationProfile = @{
        "name"          = "powershell-" + $Source.host + "-" + $CurrentTime
        "tags"          = @()
        "entitlement"   = $Entitlement.id
        "cloud_account" = $CloudAccount.id
        "is_data_only"  = $false
        "is_vdi"        = $false
        "appliance_id"  = $CloudAccount.appliance.id
        "schedule"      = if ("" -eq $ScheduledAt) { $null } else { $ScheduledAt }
        "transfer_mode" = "run-once"
        "sources"       = @(
            @{
                "desc"               = "Basic Migration"
                "source"             = $Source.id
                "boot_mode_conversion" = $null
                "generalize_system"  = $Sysprep
                "transfer_type"      = $TransferMethod
                "target_config"      = @{
                    "vm_details"  = @{
                        "vm_name"              = $TargetVMName
                        "flavor"               = @{
                            "cpu"       = $CPU
                            "ram_kb"    = $RAM * 1024 * 1024
                        }
                        "cluster_name" = if ($SelectedCluster) { $SelectedCluster.name } else { "" }
                        "disk_types"           = @($DiskType)
                        "target_ip"            = $null
                        "default_vm_location"  =  $SelectedHost.default_vm_path  
                        "default_disks_location" = $SelectedHost.default_disk_path
                        "disk_dir"  = $DiskLocation
                        "vm_dir" = $VMLocation
                        "high_availability_enabled"  = $false
                        "host_name"    = if ($SelectedHost) { $SelectedHost.name } else { "" }
                        "install_ssm_agent"    = $InstallAWSSSMAgent
                        "install_cloudwatch_agent" = $InstallAWSCloudWatchAgent
                    }
                    "options"     = @{}
                    "properties"  = @{
                        "network"               = @{
                            "dns"                        = @{
                                "primary"   = $PrimaryDNS
                                "secondary" = $SecondaryDNS
                            }
                            "interfaces"                 = $NetworkInterfaces
                            "routes"                     = @{
                                "default_gateway" = $DefaultGateway
                            }
                            "automatic_dns_registration" = !$DisableTargetDNSRegistration
                        }
                        "mounts_new_size"       = $ResizeMountPoint
                        "selected_mounts"       = $SelectedMount
                        "convert_filesystems"   = $ConvertFileSystem
                        "name"                  = $TargetVMName
                        "connect_azure_arc_agent" = $ConnectARCAgent
                        "install_applications"  = $InstallApplication
                        "hostname"              = $TargetVMName
                    }
                }
                "harden_os"          = if ($null -ieq $OSHardening) { $false } else { $true }
                "os_hardening"       = $OSHardening
                "os_type"            = $Source.os_type
                "name"               = $TargetVMName
                "collection_type"    = $null
                "shutdown_target"    = $ShutdownTarget
                "in_place_upgrade"   = $InPlaceUpgrade
                "upgrade_os_version" = if ("" -ieq $UpgradeOSVersion) { $null } else { $UpgradeOSVersion }
                "remove_target_agent" = $RemoveRMSAgent
                "migration_instructions" = $MigrationInstruction
                "ignore_validation_errors" = $IgnoreValidationError
                "preflight_warning"  = $false
                "binary_asset_groups" = @(
                    @{
                        "binary_assets" = $MigrationExtensionIdArray
                    }
                    @{
                        "binary_asset_names" = $MigrationExtensionArray
                    }
                )
                "binary_asset_groups_osm" = @(
                    @{
                        "osm_assets" = $MigrationExtensionIdOSMArray
                    }
                    @{
                        "osm_asset_names" = $MigrationExtensionOSMArray
                    }
                )
            }
        )
    }

    $MigrationProfileJson = $MigrationProfile | ConvertTo-Json -Depth 100

    $RMLoginResult = Get-Variable -Name "RMContext-UserLogin" -ValueOnly
    $Uri = Get-Variable -Name "RMContext-ReactorURI" -ValueOnly

    $Headers = @{
        Accept = "application/json"
        Cookie = $RMLoginResult
    }

    $Params = @{
        Method      = "Post"
        Uri         = $Uri + "/migrationprofiles"
        Body        = $MigrationProfileJson
        ContentType = "application/json"
        Headers     = $Headers
    }

    return Invoke-RMRestMethod -Params $Params
}

function Get-RMHyperVNetworkInterfaces {
    param(
        [Parameter(Mandatory)]
        [System.Object[]] $DestinationNICConfig,
        [Parameter(Mandatory)]
        [System.Object] $SelectedHost
    )
    $NetworkInterfaces = @{}
    for ($i = 0; $i -lt $DestinationNICConfig.Count; $i++) {
        $interfaceName = "eth$i"
        $config = $DestinationNICConfig[$i]
        $IpType = $config.IPType.ToLower()
        $NetworkInterfaces[$interfaceName] = @{
            "dv_switch_name"      =  ""
            "ip_type"             = $IpType
            "type"                = "Ethernet"
            "network_name" = $config.VirtualSwitchName
        }
        if ($IpType -eq "static") {
            if (![string]::IsNullOrEmpty($config.IPAddress)) {
                $NetworkInterfaces[$interfaceName]["ip_addr"] = $config.IPAddress
            }
            if (![string]::IsNullOrEmpty($config.Netmask)) {
                $NetworkInterfaces[$interfaceName]["netmask"] = $config.Netmask
            }
            if (![string]::IsNullOrEmpty($config.VirtualLANIdentification)) {
                $NetworkInterfaces[$interfaceName]["vlan_id"] = $config.VirtualLANIdentification
            }
        }
    }
    return $NetworkInterfaces
}