Created
October 19, 2020 12:36
-
-
Save bk2zsto/9b96c4367dd1541fb0be9dfe93fde99f to your computer and use it in GitHub Desktop.
expand IOS-style vlan strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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