GcpFunctions.ps1

Function CleanUpGcpDisk([string]$gcpServiceAccountKeyFile, [string]$cloudDiskName)
{
    $gcpServiceAccountKey = Get-Content -Raw -Path $gcpServiceAccountKeyFile | ConvertFrom-Json
    try
    {
        $disk = Get-GceImage -Name $cloudDiskName -Project $gcpServiceAccountKey.project_id
    }
    catch
    {
        if ($_.exception.Message -like '*The resource *was not found*')
        {
            return
        }
        ThrowError ([UploaderException]::new("Error finding disk image $($cloudDiskName)", $_.Exception))
    }
    Log "Deleting existing disk image '$cloudDiskName'"
    Remove-GceImage -Name $cloudDiskName -Project $gcpServiceAccountKey.project_id
}

Function DeriveBucketName([string]$cloudDiskName)
{
    $bucketName = $cloudDiskName.Split('.')[0]
    if (-not (($bucketName.Length -le 63) -and ($bucketName -cmatch '^[a-z]([-a-z0-9]*[a-z0-9])?$')))
    {
        $msg = "Invalid CloudDiskName '$cloudDiskName'. The stem must meet the requirements for Google Cloud image names. " +
               "See https://cloud.google.com/compute/docs/reference/rest/v1/images"
        ThrowError ([UploaderException]::new($msg))
    }
    return $bucketName
}

Function UploadToGcp([string]$cloudDiskName, [string]$path, [string]$gcpServiceAccountKeyFile, [string]$logFileName)
{
    $bucketName = DeriveBucketName $cloudDiskName
    Log "Copying disk '$path' to bucket '$bucketName'"
    Copy-ToGcpDisk -File $path -BucketName $bucketName -ServiceAccountKeyFile $gcpServiceAccountKeyFile -LogFileName $logFileName
    Log "Copied disk to image '$cloudDiskName' via bucket '$bucketName'"
}