Skip to content

Instantly share code, notes, and snippets.

@bk2zsto
Created October 19, 2020 12:36
Show Gist options
  • Save bk2zsto/9b96c4367dd1541fb0be9dfe93fde99f to your computer and use it in GitHub Desktop.
Save bk2zsto/9b96c4367dd1541fb0be9dfe93fde99f to your computer and use it in GitHub Desktop.
expand IOS-style vlan strings
def vlan_unparser(vlan_list_string):
"""
Input: string in IOS-compressed VLAN syntax
Output: list with ranges expanded
"""
vlan_min = 1
vlan_max = 4094
result = []
if re.match(r"^\d[\d\-,\s]+\d$", vlan_list_string):
for num in re.findall(r"\D*(\d+)\D*", vlan_list_string):
if int(num) not in range(vlan_min, vlan_max + 1):
raise AnsibleFilterError(
"Invalid VLAN value found: {}".format(num)
)
elems = re.split(r"\s*,\s*", vlan_list_string)
for elem in elems:
if "-" in elem:
pair = re.match(r"^\s*(\d+)\s*-\s*(\d+)\s*$", elem)
if pair is not None:
start = int(pair.groups(0)[0])
end = int(pair.groups(0)[1])
result.extend(list(range(start, end + 1)))
else:
raise AnsibleFilterError(
"Invalid VLAN range: {}".format(elem)
)
else:
result.append(int(elem))
else:
raise AnsibleFilterError(
"Invalid VLAN range string: {}".format(vlan_list_string)
)
return sorted(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment