Month: October 2016

Creating a VM from an Azure Image | Azure – Existing Network

I recently created a script to create a VM from an existing disk in Azure, using the v2 or ARM model.

This script created a new network but in most instances a network will already exist and although you will create a new NIC you will want to place this VM into an existing subnet.

The extract below can be used to create a new NIC but add this to a named vNet and Subnet.
When you define the VM configuration you would use this to be the NIC.
Finally make sure this (if the first NIC) is set as -Primary


#Networking
$NicName = $vmName + "NIC-Prod"
$Vnet = Get-AzureRmVirtualNetwork -Name "hubsydvnet" -ResourceGroupName $RGName
$SubnetProduction = Get-AzureRmVirtualNetworkSubnetConfig -Name "Sub-1" -VirtualNetwork $Vnet
$Nic = New-AzureRmNetworkInterface -ResourceGroupName $RGName -Name $NicName -Subnet $SubnetProduction -Location $Location

#Define VM Configuration
$VMConfig = New-AzureRmVMConfig -VMName $vmName -VMSize "Standard_DS2_v2" |
Set-AzureRmVMOperatingSystem -Windows -ComputerName $vmName -Credential $Cred -ProvisionVMAgent -EnableAutoUpdate |
Set-AzureRmVMOSDisk -Name $OSDiskName -VhdUri $OSDiskUri -CreateOption FromImage -SourceImageUri $URIofuploadedImage -Windows |
Add-AzureRmVMNetworkInterface -Id $Nic.ID -Primary

Disclaimer:  Please note although I work for Microsoft the information provided here does not represent an official Microsoft position and is provided as is.

Tag Azure VMs and Resources

Tagging in Azure is a massively useful feature.  I have customers who are interested in identifying resources for billing but they are also a very useful tool for control.  Resources can be grouped by tag and then a script can be used to apply a function to all machines or services with the same tag.

In the example below I call a variable that looks for Azure resources where the type is identified as a Microsoft virtual machine.  Calling this function enables me to extract a range of information. (I fact this script then goes on and uses the ResourceId too)

As referenced in Using tags to organize your Azure resources tags are updated as a whole so if you want to add additional tags you first have to call the existing tags.  In the example below I am adding the new tag to my existing tags.

Finally we are looping this for each vm and applying via a set command.

Hope this is of use to you, happy tagging :-)!


$FindVMs = Find-AzureRmResource | where {$_.ResourceType -like "Microsoft.Compute/virtualMachines"}
$Tags = (Get-AzureRmResource -ResourceId $ResourceId).Tags
$Tags += @{ Owner = "wade" }

Foreach ($vm in $Findvms)
{
$ResourceId = $VM.ResourceId
Set-AzureRmResource -Tag $Tags -ResourceId $ResourceId -Force
}

Disclaimer:  Please note although I work for Microsoft the information provided here does not represent an official Microsoft position and is provided as is.