Inject a Static IP Address in Ubuntu 18.04 on Hyper-V

If you didn't already know this, you can use the WMI class Msvm_GuestNetworkAdapterConfiguration and insert a static IP address into a Hyper-V VM. Ravikanth Chaganti provides a PowerShell script capable of setting a static IP on a VM. I slightly modified this to work on a remote Hyper-V host. I will provide a Gist of it at the bottom of this post.

Using this script, you can set assign a IP to a Windows VM with ease:

Get-VMNetworkAdapter -VMName Win2016 | `
     Set-VMNetworkConfiguration.ps1 -IPAddress 192.168.1.2 `
                                    -Subnet 255.255.255.0 `
                                    -DNSServer 192.168.1.1 `
                                    -DefaultGateway 192.168.1.1

If you try the same thing with an Ubuntu VM without any initial setup, it will fail. I will provide the steps necessary to make it work below on Ubuntu 16.04 Server and Ubuntu 18.04 Server. This document gives the steps for Ubuntu 16.04, but doesn't provide the full steps for Ubuntu 18.04.

Ubuntu 16.04

Ubuntu 16.04 is quite simple, just a few lines and a full shutdown:

sudo apt update
sudo apt install linux-azure -y
sudo shutdown now

Its important to note, you have to do a full shutdown, otherwise it will not reflect the changes.

Ubuntu 18.04

Ubuntu 18.04 is slightly more complicated. Ubuntu 18.04 by default ships with netplan.io, which is incompatible with the linux-azure module. It will show the netplan IP address in Hyper-V, but it will not update the IP address. To do so, you will need to reinstall ifupdown, resolvdconf, and then remove netplan.io

# install ifupdown, resolvvond, and linux-azure
sudo apt update
sudo apt install ifupdown resolvconf linux-azure -y

# add a default config
cat <<EOF >/etc/network/interfaces
source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto eth0
iface eth0 inet dhcp
EOF

# remove netplan and shutdown
sudo apt purge netplan.io -y
sudo shutdown now

Modified PowerShell Script Gist

Here is the gist promised from above: