Skip to content

Instantly share code, notes, and snippets.

@rca
Last active Jul 13, 2018
Embed
What would you like to do?
Lists all docker networks sorted by their subnet address
#!/usr/bin/env xonsh
import json
import re
import sys
from tabulate import tabulate
# https://arcpy.wordpress.com/2012/05/11/sorting-alphanumeric-strings-in-python/
# https://stackoverflow.com/questions/2669059/how-to-sort-alpha-numeric-set-in-python
def sorted_alnum(l, key=None):
"""
Sorts the given iterable in the way that is expected.
Args:
l: The iterable to be sorted.
"""
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
return sorted(l, key=lambda x: alphanum_key(key(x) if key else x))
# ((for i in $(docker network ls | grep overlay | awk '{print $2}'); do echo $(docker network inspect $i | grep 'Subnet.*192.*' | awk '{print $2}') $i; done;) | grep -v 'ingress$' | sed -e 's/"//g' -e 's/,//g' -e 's/\(.*\.\([^/]*\).*\)/\2 \1/' | sort -n | cut -d ' ' -f '2-') | sort -n -k1
networks = []
for line in $(docker network ls).splitlines()[1:]:
line_split = line.strip().split()
if line_split[2] != 'overlay':
continue
network_name = line_split[1]
subnet = $(
docker inspect @(network_name) | \
jq -r '.[0]["IPAM"]["Config"][0]["Subnet"]'
).strip()
networks.append([subnet, network_name])
print(tabulate(
sorted_alnum(networks, key=lambda x: x[0]),
headers=['Subnet', 'Network']
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment