Deallocated Azure VM Loses IPv4 DNS Address

I deallocate my development Azure VMs every night to conserve my credits. My VMs are all on one vnet using a domain controller. Since it is on the subnet, the domain controllers address never changes.

Every day when I start up my VM I have to configure my network adapter to "Use the following DNS server addresses" for my IPv4 DNS preferred address. I would like to automate this with a script that runs at startup.

I am able to set this property using:

netsh interface ipv4 set dns "Local Area Connection 138" static 10.0.0.4

However, this wont work because the Local Area Connection number increments every startup. I have gotten close to getting the Local Area Connection Name by using:

wmic.exe nic where "NetConnectionStatus=2" get NetConnectionID

But this returns the column header and cannot be used. Value returned looks like this:

NetConnectionID
Local Area Connection 138

So my question is how can I set the preferred DNS address of a dynamic Local Area Connection at startup?


Solution 1:

You should never configure your VM to Static Ip addresses inside the operating system, use azure portal or powershell instead.

Configure a Static Internal IP Address for a VM:

https://azure.microsoft.com/documentation/articles/virtual-networks-reserved-private-ip/

Basically you are telling the DHCP server to always give the same ip to your VM.

If you don't want to use powershell, you can use the preview portal which will give you this functionality. Just navigate to your VM >> Configure >> Network Settings >> IP Address >> Set Private Ip Address to Static >> Type desired IP.

About Virtual Network Settings in the Management Portal:

https://msdn.microsoft.com/library/azure/jj156074.aspx/#BKMK_VNETDNS

Navigate to Networks >> Select your VNET >> Select Configure Tab >> Set your prefered DNS Servers in order of priority.

Solution 2:

Manual Configuration of network settings is not supported on Azure, which explicitly requires virtual network adapters to use DHCP, and resets this setting when an adapter is replaced (which usually happens each time the VM is shut down and deallocated).

However, you can control which private IP address a VM gets by reserving a static IP, and which DNS servers are offered by DHCP by configuring them in the virtual network settings.