GcpCreateVmClient.ps1
Class GcpCreateVmClient : CreateVmClient { # properties [string]$GcpServiceAccountKeyFile [string]$GcpZone [string]$PrepareDiskName [string]$InstanceName [string]$MachineType [hashtable]$Tags [bool]$Debug # Default constructor GcpCreateVmClient([hashtable]$values) : base ($values) { $this.CopyValues(@{ GcpServiceAccountKeyFile = @{ required = $True } GcpZone = @{ required = $False default = "us-east4-a" } PrepareDiskName = @{ required = $True } InstanceName = @{ required = $True } MachineType = @{ required = $False default = "n1-standard-4" } Tags = @{ required = $False default = @{} } Debug = @{ required = $False default = $false } }, $values) } Cleanup() {} # Upload exported image from a share to Gcp. [psobject]CreateVm() { $this.AddDefaultTags($this.Tags) $diskString = "--disk=name=" + $this.PrepareDiskName + ",boot=yes,auto-delete=no" $zoneString = "--zone=" + $this.GcpZone $machineString = "--machine-type=" + $this.MachineType if ($this.Debug) { $displayEnableString = "--enable-display-device" } else { $displayEnableString = "" } $tagsString = $this.Tags.keys.foreach({ "$_=$($this.Tags[$_])" }) -join ',' try { gcloud compute instances create $this.InstanceName $zoneString $machineString $diskString $displayEnableString --labels=$tagsString --description="Created with a Citrix migrated disk" if ($LastExitCode -ne 0) { throw "Failed to create VM. Failed with error code $LastExitCode" } Write-Host "Created VM $($this.InstanceName) from disk $($this.PrepareDiskName) in zone $($this.GcpZone)" gcloud compute instances stop $this.InstanceName if ($LastExitCode -ne 0) { throw "Failed to stop VM. Failed with error code $LastExitCode" } } catch { Write-Host "Failed to create VM $($this.InstanceName) from disk $($this.PrepareDiskName) in zone $($this.GcpZone)" throw "Failed to create VM: $_" } return @{ vm = $this.InstanceName } } } |