I've posted in the forum but thought I would ask here also. So, I am new to Ubuntu Server 18.04, netplan and .yaml. In the past using Ubuntu Server 16.04 I was able to create a pretty decent shell script to setup a static IP on a server in a post-installation setup. Is it not possible to script out the network configuration now that Ubuntu Server 18.04 is using netplan? I was trying to tweak my shell script to configure the writing to the .yaml file but it seems formatting is crucial when editing a .yaml file and I was not having much luck. It seems Ansible may possibly be a solution for this, possibly? But I've yet to master Ansible. Anyone else have any luck writing a script to configure a static IP using netplan and updating the .yaml file?
@TygerTy Thanks for that. I forgot to post a follow up a few weeks ago. This is what I came up with that worked for me:
This works for me, although I'm generating a static from the current config (don't ask why).
Just substitute the IP address for your static IP and netmask instead of dynamically looking for it like I do.
You could also change the network manager as well.
createStaticConnection.sh
------
END_CONFIG=/etc/netplan/01-network-card.yaml
generateAndApply() { sudo netplan generate sudo netplan apply }
getInternetInfo() { local INTERNET_INFO=$( ip r | grep default ) printf "%s" "$( echo $INTERNET_INFO | cut -f$1 -d' ' )" }
#static information NAMESERVERS=("1.1.1.1" "1.0.0.1") NETWORK_MANAGER="NetworkManager"
# information that varies IP="$( ip r | grep kernel | cut -f9 -d' ' )" GATEWAY="$( getInternetInfo 3 )" DEVICE_NAME="$( getInternetInfo 5 )" METHOD="$( getInternetInfo 7 )" PREFIX="$( ip r | grep kernel | cut -f1 -d' ' | cut -f2 -d'/' )"
createStaticYAML() { local YAML="network:\n" YAML+=" version: 2\n" YAML+=" renderer: $NETWORK_MANAGER\n" YAML+=" ethernets:\n" YAML+=" $DEVICE_NAME:\n" YAML+=" dhcp4: no\n" YAML+=" addresses: [$IP/$PREFIX]\n" YAML+=" gateway4: $GATEWAY\n" YAML+=" nameservers:\n" YAML+=" addresses: [${NAMESERVERS[0]},${NAMESERVERS[1]}]" printf "%s" "$YAML" }
clearConfigs() { [ -f $END_CONFIG ] && sudo rm $END_CONFIG }
setYAML() { sudo echo -e "$(createStaticYAML)" > $END_CONFIG }
clearConfigs setYAML generateAndApply restartNetwork