Skip to content

Instantly share code, notes, and snippets.

@kevinhillinger
Created August 9, 2017 18:39
Show Gist options
  • Save kevinhillinger/b6b9818970825df711d13c512573d7e6 to your computer and use it in GitHub Desktop.
Save kevinhillinger/b6b9818970825df711d13c512573d7e6 to your computer and use it in GitHub Desktop.
Provision VM from existing OS disk and data disks
function New-ProvisionVirtualMachineCommand() {
$command = (New-Object -TypeName PSObject -Prop (@{
Name = $null;
Size = $null;
DnsLabel = $null;
Location = $null;
Credentials = $null
ResourceGroup = @{ Name = $null; Location = $null };
VirtualNetwork = @{ Name = $null; ResourceGroupName = $null; Location = $null; SubnetName = $null; };
OS = @{ Windows = $true; Linux = $false };
OsDisk = @{ VhdUri = $null; Caching = $null; Size = $null; };
DataDisks = New-Object System.Collections.ArrayList
}))
return $command
}
function Provision-VirtualMachine($Command) {
$vmName = $Command.Name.ToLower()
Write-Output "`n"
Ensure-ResourceGroup -Name $Command.ResourceGroup.Name -Location $Command.ResourceGroup.Location
Write-LogEntry "`nCreating NIC for VM '$vmName' in '$($Command.VirtualNetwork.Name)/$($Command.VirtualNetwork.SubnetName)'"
$nic = getNic -vmName $vmName -location $Command.Location -vnetInfo $Command.VirtualNetwork
Write-LogEntry "Initializing VM '$vmName'."
$vm = New-AzureRmVMConfig -VMName $vmName -VMSize $Command.Size
$vm = Add-AzureRmVMNetworkInterface -VM $vm -Id $nic.Id -Primary
Write-LogEntry "Attaching OS Disk."
if ($Command.OS.Windows) {
$vm = Set-AzureRmVMOSDisk -VM $vm -Name $Command.OsDisk.Name -VhdUri $Command.OsDisk.VhdUri -CreateOption Attach -Windows
#$vm = Set-AzureRmVMOSDisk -VM $vm -Name $Command.OsDisk.Name -VhdUri $Command.OsDisk.VhdUri -CreateOption Attach `
#-Caching $Command.OsDisk.Caching -Windows -DiskSizeInGB $Command.OsDisk.Size
}
else {
$vm = Set-AzureRmVMOSDisk -VM $vm -Name $Command.OsDisk.Name -VhdUri $Command.OsDisk.VhdUri -CreateOption Attach -Linux
#$vm = Set-AzureRmVMOSDisk -VM $vm -Name $Command.OsDisk.Name -VhdUri $Command.OsDisk.VhdUri -CreateOption Attach `
# -Caching $Command.OsDisk.Caching -Linux -DiskSizeInGB $Command.OsDisk.Size
}
if ($Command.DataDisks.Count -gt 0) {
Write-LogEntry "Attaching Data Disk(s)."
$dataDisks = $Command.DataDisks
for ($i=0; $i -lt $dataDisks.Count; $i++) {
$diskInfo = $dataDisks[$i]
$vm = Add-AzureRmVMDataDisk -VM $vm -Name $diskInfo.Name -VhdUri $diskInfo.VhdUri -LUN $i -Caching $diskInfo.Caching -DiskSizeinGB $diskInfo.Size -CreateOption Attach
}
}
Write-LogEntry "Provisioning VM '$vmName'..."
New-AzureRmVM -ResourceGroupName $Command.ResourceGroup.Name -Location $Command.Location -VM $vm | Out-Log
Write-LogEntry "VM '$vmName' provisioning completed successfully."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment