# MAC based IP assignment via rc.local ###### tags: `dhcp` `mac` `rc.local` `network` I build virtual machine in home lab environment and configure IP addresses in VMs cost some time especially there are many machines and clusters. Use dhcp is simply but have to config to manage IP assignment. Also I want to config IP address staticly to let machine get IP ASAP when booting and especially if dhcp is disabled in the connected virtual network. To solve this problem, and because this is a virtual environment, I write a bash script to be included in "rc.local", which configure IP address base on MAC address when boot machine. As result, when I create virtual mahcine, By specify specific MAC address to virtual NIC, the script parsers the MAC address to get IP address and configure interface with the IP. > *This should work in ubuntu 16.04, 18.04, 20.04* #### 1. Create ubuntu virtual machine. #### 2. Add following script in /etc/rc.local file. ``` #!/usr/bin/bash def_mac="AA:DD" def_mask="24" interfaces=($(ip -br l | grep -v "^lo" | awk '{print $1,$3}' | sed 's/ /,/g')) for interface in ${interfaces[@]}; do interface_name=$(echo ${interface} | cut -d',' -f1) interface_mac=$(echo ${interface} | cut -d',' -f2) #echo [debug] ${interface_name} - ${interface_mac} if [[ "${interface_mac}" =~ ^"${def_mac}"* ]]; then #echo [debug] "${interface_name} - ${interface_mac}" | tee -a /var/log/interfaces.log # set static IP mac_p3=$(echo ${interface_mac} | cut -d':' -f3) mac_p4=$(echo ${interface_mac} | cut -d':' -f4) mac_p5=$(echo ${interface_mac} | cut -d':' -f5) mac_p6=$(echo ${interface_mac} | cut -d':' -f6) #echo [debug] "${mac_p3} ${mac_p4} ${mac_p5} ${mac_p6}" #echo [debug] "$((16#${mac_p3})).$((16#${mac_p4})).$((16#${mac_p5})).$((16#${mac_p6}))" interface_ip="$((16#${mac_p3})).$((16#${mac_p4})).$((16#${mac_p5})).$((16#${mac_p6}))" echo "set ${interface_name} to ${interface_ip}" | tee -a /var/log/interfaces.log # add ip to interface ip addr add ${interface_ip}/${def_mask} dev ${interface_name} ip link set ${interface_name} up fi done ``` The first two MAC octets I used to identify whether to configure IP base on the following MAC octets or not. I simply define "aa:dd" which means the script use the MAC address to configure IP address of the interface. If it matched, the whole IP address is retrieved from last four octets in MAC address. Each octet represent an decimal in IP. For example. MAC "01" => 1 MAC "ff" => 255 MAC "0a" => 10 MAC "0f" => 15 MAC "10" => 16 MAC "1a" => 26 #### 3. Configure key-based ssh login (optional) #### 4. Shutoff the VM and dump VM image as an image template > Todo: update the IP to netplan config.