Script Sample - Azure Automation - Get VM Information from actual Azure Virtual Machine

@20aman    Sep 24, 2018

Many times, when automating your infrastructure, you will need to work with Azure Virtual Machines. Based on just the name of the VM and it's Resource Group, you will need to know about it's Network Interfaces and it's IP address.

This Runbook sample connects to Azure using Service Principal and fetches various VM properties. The Runbook can be tweaked to fetch more or less information as per the requirements.

Script Input and Requirements

The script takes the below inputs:

  1. VM Name - name of the VM
  2. ResourceGroupNameofVM - name fo the Resource Group in which the VM exists
  3. Azure Tenant Id - Id of the Tenant. This is the Azure Active Directory's Id which can be found in Azure AD properties in the portal
  4. Subscription Id - Id of the Subscription in which the VM exists

The VM also requires a credential Object i.e. a Service Pricipal, which will have access to the Virtual machine.

Working of the Script

The script uses the below command to log into the Azure using the Service Principal.

$AzureRMConn = Login-AzureRmAccount -ServicePrincipal -Credential $Cred -TenantId $AzureTenantId -ErrorAction SilentlyContinue -ErrorVariable LoginError

If the connection is successful then the Subscription is selected using below cmdlet.

$ConnSubs = Select-AzureRmSubscription -SubscriptionId $SubscriptionID

Then the actual VM information is fetched using below cmdlet.

$VM = Get-AzureRmVM -ResourceGroupName $VMResourceGroup -Name $VMName

This fetches basic VM information. To fetch detailed information regarding the network interface of the VM, below cmdlets are used.

$nicId = $VM.NetworkProfile.NetworkInterfaces[0].Id
$VMNetowrkInterface = Get-AzureRmNetworkInterface -ResourceGroupName $VMResourceGroup -Name $nicId.Split('/')[8]
$VMMainIPConfig = $VMNetowrkInterface | Get-AzureRmNetworkInterfaceIpConfig
$strVMMainNicName = $VMMainIPConfig.Name
$strVMMainNicIPAddress = $VMMainIPConfig.PrivateIpAddress

The first cmdlet above fetches the Id of the first Network Interface on the VM. Then the second cmdlet uses this Id to fetch the actual network interface. The third cmdlet uses Get-AzureRmNetwrokInterfaceIpConfig to fetch the IP configuration on this network interface. Then last two lines use this Ip configuration to fetch the Private IP address on the VM.

Location of the Script

You can find this script in GitHub at this location: Get-VMInfoFromAzure.ps1

Comments powered by Disqus