Skip to content

Instantly share code, notes, and snippets.

@ThinGuy
Last active February 5, 2018 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ThinGuy/cc4e7de5fc7ee0dd8ccc2e10b59ffe4c to your computer and use it in GitHub Desktop.
Save ThinGuy/cc4e7de5fc7ee0dd8ccc2e10b59ffe4c to your computer and use it in GitHub Desktop.
Force delete a subnet in maas
#Workaround for 'Subnet matching query does not exist' error trying to delete a subnet in MaaS
#See bug https://bugs.launchpad.net/maas/+bug/1702527
#Usage force-del-maas-subnet <maas subnet name>
#ex force-del-maas-subnet '192.168.122.0/24'
force-del-maas-subnet() {
unset SN_NAME MAAS_SN_ID MAAS_STATICIP_ID MAAS_INTIP_ID MATCH CONT
export MATCH=false
command -v ipcalc > /dev/null 2>&1 || sudo apt install -yq ipcalc
command -v ipcalc > /dev/null 2>&1 || { printf "This function requires ipcalc. Please install it via \"apt install ipcalc -y\"\n";return; }
[[ -z ${1} || ! ${1} =~ ${IPV4CIDRREGEX} ]] && { printf "Please provide network in CIDR format (e.g. 192.168.8.0/24)\n";return; } || export SN_NAME="${1}"
export MAAS_SN_ID=$(sudo -u postgres psql -P pager=off --no-align -t maasdb -c "SELECT id from maasserver_subnet WHERE name = '${SN_NAME}'")
[[ -n ${MAAS_SN_ID} ]] && export MAAS_STATICIP_ID=$(sudo -u postgres psql -P pager=off --no-align -t maasdb -c "SELECT id from maasserver_staticipaddress WHERE subnet_id = '${MAAS_SN_ID}'") || { printf "No MaaS subnet found with name ${SN_NAME}\n";return; }
for i in $(ip -4 a|awk '/^[0-9][^ ]+/&&!/lo:/{gsub(/:/,"");print $2}');do
[[ $(ipcalc $(ip -4 a show dev $i|grep -oP '(?<=inet )[^ ]+')|awk '/^Network:/{print $2}') = ${SN_NAME} ]] && { export MATCH=true;printf "Maas subnet ${SN_NAME} is associated with active interface ${i}\n"; }
done
[[ ${MATCH} = true ]] && read -rp "Continue to delete [y/n]: " CONT
[[ ${CONT} = [Nn] ]] && { printf "Quitting without making changes to MaaS subnet ${SN_NAME}\n"; return 0; }
[[ -n ${MAAS_STATICIP_ID} ]] && export MAAS_INTIP_ID=$(sudo -u postgres psql -P pager=off --no-align -t maasdb -c "SELECT id from maasserver_interface_ip_addresses WHERE staticipaddress_id = ${MAAS_STATICIP_ID}")
[[ -n ${MAAS_INTIP_ID} ]] && sudo -u postgres psql -P pager=off --no-align -t maasdb -c "DELETE from maasserver_interface_ip_addresses where id = ${MAAS_INTIP_ID}"
[[ -n ${MAAS_STATICIP_ID} ]] && sudo -u postgres psql -P pager=off --no-align -t maasdb -c "DELETE from maasserver_staticipaddress where id = ${MAAS_STATICIP_ID}"
[[ -n ${MAAS_SN_ID} ]] && sudo -u postgres psql -P pager=off --no-align -t maasdb -c "DELETE from maasserver_subnet where id = ${MAAS_SN_ID}"
unset SN_NAME MAAS_SN_ID MAAS_STATICIP_ID MAAS_INTIP_ID MATCH CONT
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment