2021-01-28

Create Linux VM From Image

# Define a credential object
$securePassword = ConvertTo-SecureString 'P@$$w0rd' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ('superman', $securePassword)

# Create some variables for the new VM 
$ResourceGroupName = 'ResourceGroup'
$AzureRegion = 'East Asia'
$NewVMName = 'NewVM'
$vNet = 'vNet'
$SubNet = 'Subnet'
$NSG_Head = 'NSG'
$OSDiskType = 'Standard_LRS' # 'Standard_LRS' | 'StandardSSD_LRS' | 'Premium_LRS'
$VMSize = 'Standard_B2s';

# Get the image. Replace the name of your resource group, gallery, and image definition. This will create the VM from the latest image version available.

$imageDefinition = Get-AzImage `
-ResourceGroupName 'WVD_Template_Image' `
-ImageName 'ACSClone1604-Prepare-image-20210128141610'

$SubnetID = (Get-AzVirtualNetworkSubnetConfig -VirtualNetwork (Get-AzVirtualNetwork -Name $vNet) -Name $SubNet).Id
$NSGID = $(Get-AzNetworkSecurityGroup | Where {$_.Name -like ($NSG_Head + '_*')}).Id

$NIC = New-AzNetworkInterface `
-Name ($NewVMName) `
-ResourceGroupName $ResourceGroupName `
-Location $AzureRegion `
-SubnetId $SubnetID `
-NetworkSecurityGroupId $NSGID

# Create a virtual machine configuration using $imageDefinition.Id to use the latest image version.
$VMConfig = New-AzVMConfig `
-VMName $NewVMName `
-VMSize $VMSize | `
Set-AzVMOperatingSystem `
-Linux `
-ComputerName $NewVMName `
-Credential $cred | `
Set-AzVMSourceImage -Id $imageDefinition.Id | `
Add-AzVMNetworkInterface -Id $NIC.Id

Set-AzVMOSDisk -CreateOption fromImage `
-VM $VMConfig `
-Name $NewVMName `
-StorageAccountType $OSDiskType `
-Linux

# Create a virtual machine
New-AzVM `
-ResourceGroupName $ResourceGroupName `
-Location $AzureRegion `
-VM $vmConfig
   
$StopHostResult = Get-AzResource -ResourceID (Get-AzVM -ResourceGroupName $ResourceGroupName -Name $NewVMName).Id | Stop-AzVM -Force;

沒有留言:

張貼留言