diff options
author | Bradley A. Thornton <bthornto@thethorntons.net> | 2019-08-09 10:48:27 -0700 |
---|---|---|
committer | Bradley A. Thornton <bthornto@thethorntons.net> | 2019-08-09 10:48:27 -0700 |
commit | 5fb9df4e907a6ab2da7a6c2dafdec9c1971e8d44 (patch) | |
tree | 4459ed61d06c8d8caabbcc3ab36d84e27a919ee7 /plugins/module_utils | |
parent | 7b9a33a29007ed302c3001566061e22c514cde64 (diff) | |
download | vyos-ansible-collection-5fb9df4e907a6ab2da7a6c2dafdec9c1971e8d44.tar.gz vyos-ansible-collection-5fb9df4e907a6ab2da7a6c2dafdec9c1971e8d44.zip |
bt_blackked
Diffstat (limited to 'plugins/module_utils')
11 files changed, 418 insertions, 424 deletions
diff --git a/plugins/module_utils/network/vyos/argspec/facts/facts.py b/plugins/module_utils/network/vyos/argspec/facts/facts.py index 84b7135..e660ef2 100644 --- a/plugins/module_utils/network/vyos/argspec/facts/facts.py +++ b/plugins/module_utils/network/vyos/argspec/facts/facts.py @@ -5,21 +5,22 @@ The arg spec for the vyos facts module. """ + from __future__ import absolute_import, division, print_function + __metaclass__ = type class FactsArgs(object): # pylint: disable=R0903 """ The arg spec for the vyos facts module """ + def __init__(self, **kwargs): pass - choices = [ - 'all', 'interfaces', '!interfaces', 'l3_interfaces', '!l3_interfaces' - ] + choices = ["all", "interfaces", "!interfaces", "l3_interfaces", "!l3_interfaces"] argument_spec = { - 'gather_subset': dict(default=['!config'], type='list'), - 'gather_network_resources': dict(choices=choices, type='list'), + "gather_subset": dict(default=["!config"], type="list"), + "gather_network_resources": dict(choices=choices, type="list"), } diff --git a/plugins/module_utils/network/vyos/argspec/interfaces/interfaces.py b/plugins/module_utils/network/vyos/argspec/interfaces/interfaces.py index 40df125..3542cb1 100644 --- a/plugins/module_utils/network/vyos/argspec/interfaces/interfaces.py +++ b/plugins/module_utils/network/vyos/argspec/interfaces/interfaces.py @@ -24,43 +24,46 @@ The arg spec for the vyos_interfaces module """ from __future__ import absolute_import, division, print_function + __metaclass__ = type class InterfacesArgs(object): # pylint: disable=R0903 """The arg spec for the vyos_interfaces module """ + def __init__(self, **kwargs): pass - argument_spec = \ - { - 'config': { - 'elements': 'dict', - 'options': { - 'description': {'type': 'str'}, - 'duplex': {'choices': ['full', 'half', 'auto']}, - 'enabled': {'default': True, 'type': 'bool'}, - 'mtu': {'type': 'int'}, - 'name': {'required': True, 'type': 'str'}, - 'speed': {'choices': ['auto', '10', '100', '1000', '2500', - '10000'], - 'type': 'str'}, - 'vifs': { - 'elements': 'dict', - 'options': { - 'vlan_id': {'type': 'int'}, - 'description': {'type': 'str'}, - 'enabled': {'default': True, 'type': 'bool'}, - 'mtu': {'type': 'int'} - }, - 'type': 'list' + argument_spec = { + "config": { + "elements": "dict", + "options": { + "description": {"type": "str"}, + "duplex": {"choices": ["full", "half", "auto"]}, + "enabled": {"default": True, "type": "bool"}, + "mtu": {"type": "int"}, + "name": {"required": True, "type": "str"}, + "speed": { + "choices": ["auto", "10", "100", "1000", "2500", "10000"], + "type": "str", + }, + "vifs": { + "elements": "dict", + "options": { + "vlan_id": {"type": "int"}, + "description": {"type": "str"}, + "enabled": {"default": True, "type": "bool"}, + "mtu": {"type": "int"}, }, + "type": "list", }, - 'type': 'list' }, - 'state': {'choices': ['merged', 'replaced', - 'overridden', 'deleted'], - 'default': 'merged', - 'type': 'str'} - } # pylint: disable=C0301 + "type": "list", + }, + "state": { + "choices": ["merged", "replaced", "overridden", "deleted"], + "default": "merged", + "type": "str", + }, + } # pylint: disable=C0301 diff --git a/plugins/module_utils/network/vyos/argspec/l3_interfaces/l3_interfaces.py b/plugins/module_utils/network/vyos/argspec/l3_interfaces/l3_interfaces.py index 240f348..91434e4 100644 --- a/plugins/module_utils/network/vyos/argspec/l3_interfaces/l3_interfaces.py +++ b/plugins/module_utils/network/vyos/argspec/l3_interfaces/l3_interfaces.py @@ -25,75 +25,57 @@ The arg spec for the vyos_l3_interfaces module """ + from __future__ import absolute_import, division, print_function + __metaclass__ = type class L3_interfacesArgs(object): # pylint: disable=R0903 """The arg spec for the vyos_l3_interfaces module """ + def __init__(self, **kwargs): pass argument_spec = { - 'config': { - 'elements': 'dict', - 'options': { - 'ipv4': { - 'elements': 'dict', - 'options': { - 'address': { - 'type': 'str' - } - }, - 'type': 'list' + "config": { + "elements": "dict", + "options": { + "ipv4": { + "elements": "dict", + "options": {"address": {"type": "str"}}, + "type": "list", }, - 'ipv6': { - 'elements': 'dict', - 'options': { - 'address': { - 'type': 'str' - } - }, - 'type': 'list' - }, - 'name': { - 'required': True, - 'type': 'str' + "ipv6": { + "elements": "dict", + "options": {"address": {"type": "str"}}, + "type": "list", }, - 'vifs': { - 'elements': 'dict', - 'options': { - 'ipv4': { - 'elements': 'dict', - 'options': { - 'address': { - 'type': 'str' - } - }, - 'type': 'list' + "name": {"required": True, "type": "str"}, + "vifs": { + "elements": "dict", + "options": { + "ipv4": { + "elements": "dict", + "options": {"address": {"type": "str"}}, + "type": "list", }, - 'ipv6': { - 'elements': 'dict', - 'options': { - 'address': { - 'type': 'str' - } - }, - 'type': 'list' + "ipv6": { + "elements": "dict", + "options": {"address": {"type": "str"}}, + "type": "list", }, - 'vlan_id': { - 'type': 'int' - } + "vlan_id": {"type": "int"}, }, - 'type': 'list' - } + "type": "list", + }, }, - 'type': 'list' + "type": "list", + }, + "state": { + "choices": ["merged", "replaced", "overridden", "deleted"], + "default": "merged", + "type": "str", }, - 'state': { - 'choices': ['merged', 'replaced', 'overridden', 'deleted'], - 'default': 'merged', - 'type': 'str' - } } # pylint: disable=C0301 diff --git a/plugins/module_utils/network/vyos/config/interfaces/interfaces.py b/plugins/module_utils/network/vyos/config/interfaces/interfaces.py index c85b865..1b6584b 100644 --- a/plugins/module_utils/network/vyos/config/interfaces/interfaces.py +++ b/plugins/module_utils/network/vyos/config/interfaces/interfaces.py @@ -10,17 +10,23 @@ created """ from __future__ import absolute_import, division, print_function + __metaclass__ = type + from copy import deepcopy from ansible.module_utils.network.common.cfg.base import ConfigBase from ansible.module_utils.network.common.utils import to_list, dict_diff, remove_empties from ansible.module_utils.six import iteritems -from ansible_collections.vyos.vyos.plugins.module_utils.network. \ - vyos.facts.facts import Facts +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.facts import ( + Facts, +) -from ansible_collections.vyos.vyos.plugins.module_utils.network. \ - vyos.utils.utils import search_obj_in_list, get_interface_type, dict_delete +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.utils.utils import ( + search_obj_in_list, + get_interface_type, + dict_delete, +) class Interfaces(ConfigBase): @@ -28,12 +34,9 @@ class Interfaces(ConfigBase): The vyos_interfaces class """ - gather_subset = [ - '!all', - '!min', - ] + gather_subset = ["!all", "!min"] - gather_network_resources = ['interfaces'] + gather_network_resources = ["interfaces"] def __init__(self, module): super(Interfaces, self).__init__(module) @@ -45,8 +48,9 @@ class Interfaces(ConfigBase): :returns: The current configuration as a dictionary """ facts, _warnings = Facts(self._module).get_facts( - self.gather_subset, self.gather_network_resources) - interfaces_facts = facts['ansible_network_resources'].get('interfaces') + self.gather_subset, self.gather_network_resources + ) + interfaces_facts = facts["ansible_network_resources"].get("interfaces") if not interfaces_facts: return [] return interfaces_facts @@ -56,7 +60,7 @@ class Interfaces(ConfigBase): :rtype: A dictionary :returns: The result from module execution """ - result = {'changed': False} + result = {"changed": False} commands = list() warnings = list() @@ -67,20 +71,20 @@ class Interfaces(ConfigBase): resp = self._connection.edit_config(commands, commit=False) else: resp = self._connection.edit_config(commands) - result['changed'] = True + result["changed"] = True - result['commands'] = commands + result["commands"] = commands if self._module._diff: - result['diff'] = resp['diff'] if result['changed'] else None + result["diff"] = resp["diff"] if result["changed"] else None changed_interfaces_facts = self.get_interfaces_facts() - result['before'] = existing_interfaces_facts - if result['changed']: - result['after'] = changed_interfaces_facts + result["before"] = existing_interfaces_facts + if result["changed"]: + result["after"] = changed_interfaces_facts - result['warnings'] = warnings + result["warnings"] = warnings return result def set_config(self, existing_interfaces_facts): @@ -91,7 +95,7 @@ class Interfaces(ConfigBase): :returns: the commands necessary to migrate the current configuration to the desired configuration """ - want = self._module.params['config'] + want = self._module.params["config"] have = existing_interfaces_facts resp = self.set_state(want, have) return to_list(resp) @@ -106,31 +110,30 @@ class Interfaces(ConfigBase): to the desired configuration """ commands = [] - state = self._module.params['state'] - if state == 'overridden': + state = self._module.params["state"] + if state == "overridden": commands.extend(self._state_overridden(want=want, have=have)) - elif state == 'deleted': + elif state == "deleted": if not want: for intf in have: - commands.extend( - self._state_deleted({'name': intf['name']}, intf)) + commands.extend(self._state_deleted({"name": intf["name"]}, intf)) else: for item in want: - obj_in_have = search_obj_in_list(item['name'], have) + obj_in_have = search_obj_in_list(item["name"], have) commands.extend(self._state_deleted(item, obj_in_have)) else: for item in want: - name = item['name'] + name = item["name"] obj_in_have = search_obj_in_list(name, have) if not obj_in_have: - obj_in_have = {'name': item['name']} + obj_in_have = {"name": item["name"]} - elif state == 'merged': + elif state == "merged": commands.extend(self._state_merged(item, obj_in_have)) - elif state == 'replaced': + elif state == "replaced": commands.extend(self._state_replaced(item, obj_in_have)) return commands @@ -160,13 +163,12 @@ class Interfaces(ConfigBase): commands = [] for intf in have: - intf_in_want = search_obj_in_list(intf['name'], want) + intf_in_want = search_obj_in_list(intf["name"], want) if not intf_in_want: - commands.extend( - self._state_deleted({'name': intf['name']}, intf)) + commands.extend(self._state_deleted({"name": intf["name"]}, intf)) for intf in want: - intf_in_have = search_obj_in_list(intf['name'], have) + intf_in_have = search_obj_in_list(intf["name"], have) commands.extend(self._state_replaced(intf, intf_in_have)) return commands @@ -182,37 +184,38 @@ class Interfaces(ConfigBase): want_copy = deepcopy(remove_empties(want)) have_copy = deepcopy(have) - want_vifs = want_copy.pop('vifs', []) - have_vifs = have_copy.pop('vifs', []) + want_vifs = want_copy.pop("vifs", []) + have_vifs = have_copy.pop("vifs", []) updates = dict_diff(have_copy, want_copy) if updates: for key, value in iteritems(updates): commands.append( - self._compute_commands(key=key, - value=value, - interface=want_copy['name'])) + self._compute_commands( + key=key, value=value, interface=want_copy["name"] + ) + ) if want_vifs: for want_vif in want_vifs: - have_vif = search_obj_in_list(want_vif['vlan_id'], - have_vifs, - key='vlan_id') + have_vif = search_obj_in_list( + want_vif["vlan_id"], have_vifs, key="vlan_id" + ) if not have_vif: - have_vif = { - 'vlan_id': want_vif['vlan_id'], - 'enabled': True - } + have_vif = {"vlan_id": want_vif["vlan_id"], "enabled": True} vif_updates = dict_diff(have_vif, want_vif) if vif_updates: for key, value in iteritems(vif_updates): commands.append( - self._compute_commands(key=key, - value=value, - interface=want_copy['name'], - vif=want_vif['vlan_id'])) + self._compute_commands( + key=key, + value=value, + interface=want_copy["name"], + vif=want_vif["vlan_id"], + ) + ) return commands @@ -228,66 +231,67 @@ class Interfaces(ConfigBase): want_copy = deepcopy(remove_empties(want)) have_copy = deepcopy(have) - want_vifs = want_copy.pop('vifs', []) - have_vifs = have_copy.pop('vifs', []) + want_vifs = want_copy.pop("vifs", []) + have_vifs = have_copy.pop("vifs", []) for key in dict_delete(have_copy, want_copy).keys(): - if key == 'enabled': + if key == "enabled": continue commands.append( - self._compute_commands(key=key, - interface=want_copy['name'], - remove=True)) - if have_copy['enabled'] is False: + self._compute_commands( + key=key, interface=want_copy["name"], remove=True + ) + ) + if have_copy["enabled"] is False: commands.append( - self._compute_commands(key='enabled', - value=True, - interface=want_copy['name'])) + self._compute_commands( + key="enabled", value=True, interface=want_copy["name"] + ) + ) if have_vifs: for have_vif in have_vifs: - want_vif = search_obj_in_list(have_vif['vlan_id'], - want_vifs, - key='vlan_id') + want_vif = search_obj_in_list( + have_vif["vlan_id"], want_vifs, key="vlan_id" + ) if not want_vif: - want_vif = { - 'vlan_id': have_vif['vlan_id'], - 'enabled': True - } + want_vif = {"vlan_id": have_vif["vlan_id"], "enabled": True} for key in dict_delete(have_vif, want_vif).keys(): - if key == 'enabled': + if key == "enabled": continue commands.append( - self._compute_commands(key=key, - interface=want_copy['name'], - vif=want_vif['vlan_id'], - remove=True)) - if have_vif['enabled'] is False: + self._compute_commands( + key=key, + interface=want_copy["name"], + vif=want_vif["vlan_id"], + remove=True, + ) + ) + if have_vif["enabled"] is False: commands.append( - self._compute_commands(key='enabled', - value=True, - interface=want_copy['name'], - vif=want_vif['vlan_id'])) + self._compute_commands( + key="enabled", + value=True, + interface=want_copy["name"], + vif=want_vif["vlan_id"], + ) + ) return commands - def _compute_commands(self, - interface, - key, - vif=None, - value=None, - remove=False): - intf_context = 'interfaces {0} {1}'.format( - get_interface_type(interface), interface) - set_cmd = 'set {0}'.format(intf_context) - del_cmd = 'delete {0}'.format(intf_context) + def _compute_commands(self, interface, key, vif=None, value=None, remove=False): + intf_context = "interfaces {0} {1}".format( + get_interface_type(interface), interface + ) + set_cmd = "set {0}".format(intf_context) + del_cmd = "delete {0}".format(intf_context) if vif: - set_cmd = set_cmd + (' vif {0}'.format(vif)) - del_cmd = del_cmd + (' vif {0}'.format(vif)) + set_cmd = set_cmd + (" vif {0}".format(vif)) + del_cmd = del_cmd + (" vif {0}".format(vif)) - if key == 'enabled': + if key == "enabled": if not value: command = "{0} disable".format(set_cmd) else: diff --git a/plugins/module_utils/network/vyos/config/l3_interfaces/l3_interfaces.py b/plugins/module_utils/network/vyos/config/l3_interfaces/l3_interfaces.py index 7cac4ed..4260f35 100644 --- a/plugins/module_utils/network/vyos/config/l3_interfaces/l3_interfaces.py +++ b/plugins/module_utils/network/vyos/config/l3_interfaces/l3_interfaces.py @@ -12,17 +12,23 @@ created """ from __future__ import absolute_import, division, print_function + __metaclass__ = type + from copy import deepcopy from ansible.module_utils.network.common.cfg.base import ConfigBase from ansible.module_utils.network.common.utils import to_list, remove_empties from ansible.module_utils.six import iteritems -from ansible_collections.vyos.vyos.plugins.module_utils.network. \ - vyos.facts.facts import Facts +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.facts import ( + Facts, +) -from ansible_collections.vyos.vyos.plugins.module_utils.network. \ - vyos.utils.utils import search_obj_in_list, get_interface_type, diff_list_of_dicts +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.utils.utils import ( + search_obj_in_list, + get_interface_type, + diff_list_of_dicts, +) class L3_interfaces(ConfigBase): @@ -30,14 +36,9 @@ class L3_interfaces(ConfigBase): The vyos_l3_interfaces class """ - gather_subset = [ - '!all', - '!min', - ] + gather_subset = ["!all", "!min"] - gather_network_resources = [ - 'l3_interfaces', - ] + gather_network_resources = ["l3_interfaces"] def __init__(self, module): super(L3_interfaces, self).__init__(module) @@ -49,9 +50,9 @@ class L3_interfaces(ConfigBase): :returns: The current configuration as a dictionary """ facts, _warnings = Facts(self._module).get_facts( - self.gather_subset, self.gather_network_resources) - l3_interfaces_facts = facts['ansible_network_resources'].get( - 'l3_interfaces') + self.gather_subset, self.gather_network_resources + ) + l3_interfaces_facts = facts["ansible_network_resources"].get("l3_interfaces") if not l3_interfaces_facts: return [] return l3_interfaces_facts @@ -62,7 +63,7 @@ class L3_interfaces(ConfigBase): :rtype: A dictionary :returns: The result from module execution """ - result = {'changed': False} + result = {"changed": False} warnings = list() commands = list() @@ -73,20 +74,20 @@ class L3_interfaces(ConfigBase): resp = self._connection.edit_config(commands, commit=False) else: resp = self._connection.edit_config(commands) - result['changed'] = True + result["changed"] = True - result['commands'] = commands + result["commands"] = commands if self._module._diff: - result['diff'] = resp['diff'] if result['changed'] else None + result["diff"] = resp["diff"] if result["changed"] else None changed_l3_interfaces_facts = self.get_l3_interfaces_facts() - result['before'] = existing_l3_interfaces_facts - if result['changed']: - result['after'] = changed_l3_interfaces_facts + result["before"] = existing_l3_interfaces_facts + if result["changed"]: + result["after"] = changed_l3_interfaces_facts - result['warnings'] = warnings + result["warnings"] = warnings return result def set_config(self, existing_l3_interfaces_facts): @@ -97,7 +98,7 @@ class L3_interfaces(ConfigBase): :returns: the commands necessary to migrate the current configuration to the desired configuration """ - want = self._module.params['config'] + want = self._module.params["config"] have = existing_l3_interfaces_facts resp = self.set_state(want, have) return to_list(resp) @@ -112,31 +113,30 @@ class L3_interfaces(ConfigBase): to the desired configuration """ commands = [] - state = self._module.params['state'] - if state == 'overridden': + state = self._module.params["state"] + if state == "overridden": commands.extend(self._state_overridden(want=want, have=have)) - elif state == 'deleted': + elif state == "deleted": if not want: for intf in have: - commands.extend( - self._state_deleted({'name': intf['name']}, intf)) + commands.extend(self._state_deleted({"name": intf["name"]}, intf)) else: for item in want: - obj_in_have = search_obj_in_list(item['name'], have) + obj_in_have = search_obj_in_list(item["name"], have) commands.extend(self._state_deleted(item, obj_in_have)) else: for item in want: - name = item['name'] + name = item["name"] obj_in_have = search_obj_in_list(name, have) if not obj_in_have: - obj_in_have = {'name': item['name']} + obj_in_have = {"name": item["name"]} - if state == 'merged': + if state == "merged": commands.extend(self._state_merged(item, obj_in_have)) - elif state == 'replaced': + elif state == "replaced": commands.extend(self._state_replaced(item, obj_in_have)) return commands @@ -166,13 +166,12 @@ class L3_interfaces(ConfigBase): commands = [] for intf in have: - intf_in_want = search_obj_in_list(intf['name'], want) + intf_in_want = search_obj_in_list(intf["name"], want) if not intf_in_want: - commands.extend( - self._state_deleted({'name': intf['name']}, intf)) + commands.extend(self._state_deleted({"name": intf["name"]}, intf)) for intf in want: - intf_in_have = search_obj_in_list(intf['name'], have) + intf_in_have = search_obj_in_list(intf["name"], have) commands.extend(self._state_replaced(intf, intf_in_have)) return commands @@ -188,31 +187,35 @@ class L3_interfaces(ConfigBase): want_copy = deepcopy(remove_empties(want)) have_copy = deepcopy(remove_empties(have)) - want_vifs = want_copy.pop('vifs', []) - have_vifs = have_copy.pop('vifs', []) + want_vifs = want_copy.pop("vifs", []) + have_vifs = have_copy.pop("vifs", []) for update in self._get_updates(want_copy, have_copy): for key, value in iteritems(update): commands.append( - self._compute_commands(key=key, - value=value, - interface=want_copy['name'])) + self._compute_commands( + key=key, value=value, interface=want_copy["name"] + ) + ) if want_vifs: for want_vif in want_vifs: - have_vif = search_obj_in_list(want_vif['vlan_id'], - have_vifs, - key='vlan_id') + have_vif = search_obj_in_list( + want_vif["vlan_id"], have_vifs, key="vlan_id" + ) if not have_vif: have_vif = {} for update in self._get_updates(want_vif, have_vif): for key, value in iteritems(update): commands.append( - self._compute_commands(key=key, - value=value, - interface=want_copy['name'], - vif=want_vif['vlan_id'])) + self._compute_commands( + key=key, + value=value, + interface=want_copy["name"], + vif=want_vif["vlan_id"], + ) + ) return commands @@ -227,50 +230,49 @@ class L3_interfaces(ConfigBase): want_copy = deepcopy(remove_empties(want)) have_copy = deepcopy(have) - want_vifs = want_copy.pop('vifs', []) - have_vifs = have_copy.pop('vifs', []) + want_vifs = want_copy.pop("vifs", []) + have_vifs = have_copy.pop("vifs", []) for update in self._get_updates(have_copy, want_copy): for key, value in iteritems(update): commands.append( - self._compute_commands(key=key, - value=value, - interface=want_copy['name'], - remove=True)) + self._compute_commands( + key=key, value=value, interface=want_copy["name"], remove=True + ) + ) if have_vifs: for have_vif in have_vifs: - want_vif = search_obj_in_list(have_vif['vlan_id'], - want_vifs, - key='vlan_id') + want_vif = search_obj_in_list( + have_vif["vlan_id"], want_vifs, key="vlan_id" + ) if not want_vif: - want_vif = {'vlan_id': have_vif['vlan_id']} + want_vif = {"vlan_id": have_vif["vlan_id"]} for update in self._get_updates(have_vif, want_vif): for key, value in iteritems(update): commands.append( - self._compute_commands(key=key, - interface=want_copy['name'], - value=value, - vif=want_vif['vlan_id'], - remove=True)) + self._compute_commands( + key=key, + interface=want_copy["name"], + value=value, + vif=want_vif["vlan_id"], + remove=True, + ) + ) return commands - def _compute_commands(self, - interface, - key, - vif=None, - value=None, - remove=False): - intf_context = 'interfaces {0} {1}'.format( - get_interface_type(interface), interface) - set_cmd = 'set {0}'.format(intf_context) - del_cmd = 'delete {0}'.format(intf_context) + def _compute_commands(self, interface, key, vif=None, value=None, remove=False): + intf_context = "interfaces {0} {1}".format( + get_interface_type(interface), interface + ) + set_cmd = "set {0}".format(intf_context) + del_cmd = "delete {0}".format(intf_context) if vif: - set_cmd = set_cmd + (' vif {0}'.format(vif)) - del_cmd = del_cmd + (' vif {0}'.format(vif)) + set_cmd = set_cmd + (" vif {0}".format(vif)) + del_cmd = del_cmd + (" vif {0}".format(vif)) if remove: command = "{0} {1} '{2}'".format(del_cmd, key, value) @@ -282,9 +284,7 @@ class L3_interfaces(ConfigBase): def _get_updates(self, want, have): updates = [] - updates = diff_list_of_dicts(want.get('ipv4', []), - have.get('ipv4', [])) - updates.extend( - diff_list_of_dicts(want.get('ipv6', []), have.get('ipv6', []))) + updates = diff_list_of_dicts(want.get("ipv4", []), have.get("ipv4", [])) + updates.extend(diff_list_of_dicts(want.get("ipv6", []), have.get("ipv6", []))) return updates diff --git a/plugins/module_utils/network/vyos/facts/facts.py b/plugins/module_utils/network/vyos/facts/facts.py index bcdc54f..f92c761 100644 --- a/plugins/module_utils/network/vyos/facts/facts.py +++ b/plugins/module_utils/network/vyos/facts/facts.py @@ -8,28 +8,36 @@ calls the appropriate facts gathering function """ from __future__ import absolute_import, division, print_function + __metaclass__ = type -from ansible_collections.vyos.vyos.plugins.module_utils.network. \ - vyos.argspec.facts.facts import FactsArgs +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.facts.facts import ( + FactsArgs, +) from ansible.module_utils.network.common.facts.facts import FactsBase -from ansible_collections.vyos.vyos.plugins.module_utils.network. \ - vyos.facts.interfaces.interfaces import InterfacesFacts +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.interfaces.interfaces import ( + InterfacesFacts, +) + +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.l3_interfaces.l3_interfaces import ( + L3_interfacesFacts, +) -from ansible_collections.vyos.vyos.plugins.module_utils.network. \ - vyos.facts.l3_interfaces.l3_interfaces import L3_interfacesFacts +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.legacy.base import ( + Default, + Neighbors, + Config, +) -from ansible_collections.vyos.vyos.plugins.module_utils.network. \ - vyos.facts.legacy.base import Default, Neighbors, Config +from ansible.module_utils.network.vyos.vyos import run_commands, get_capabilities -from ansible.module_utils. \ - network.vyos.vyos import run_commands, get_capabilities FACT_LEGACY_SUBSETS = dict(default=Default, neighbors=Neighbors, config=Config) -FACT_RESOURCE_SUBSETS = dict(interfaces=InterfacesFacts, - l3_interfaces=L3_interfacesFacts) +FACT_RESOURCE_SUBSETS = dict( + interfaces=InterfacesFacts, l3_interfaces=L3_interfacesFacts +) class Facts(FactsBase): @@ -42,10 +50,7 @@ class Facts(FactsBase): def __init__(self, module): super(Facts, self).__init__(module) - def get_facts(self, - legacy_facts_type=None, - resource_facts_type=None, - data=None): + def get_facts(self, legacy_facts_type=None, resource_facts_type=None, data=None): """ Collect the facts for vyos :param legacy_facts_type: List of legacy facts types @@ -54,15 +59,15 @@ class Facts(FactsBase): :rtype: dict :return: the facts gathered """ - netres_choices = FactsArgs.argument_spec[ - 'gather_network_resources'].get('choices', []) + netres_choices = FactsArgs.argument_spec["gather_network_resources"].get( + "choices", [] + ) if self.VALID_RESOURCE_SUBSETS: - self.get_network_resources_facts(netres_choices, - FACT_RESOURCE_SUBSETS, - resource_facts_type, data) + self.get_network_resources_facts( + netres_choices, FACT_RESOURCE_SUBSETS, resource_facts_type, data + ) if self.VALID_LEGACY_GATHER_SUBSETS: - self.get_network_legacy_facts(FACT_LEGACY_SUBSETS, - legacy_facts_type) + self.get_network_legacy_facts(FACT_LEGACY_SUBSETS, legacy_facts_type) return self.ansible_facts, self._warnings diff --git a/plugins/module_utils/network/vyos/facts/interfaces/interfaces.py b/plugins/module_utils/network/vyos/facts/interfaces/interfaces.py index 915abaa..9d8d008 100644 --- a/plugins/module_utils/network/vyos/facts/interfaces/interfaces.py +++ b/plugins/module_utils/network/vyos/facts/interfaces/interfaces.py @@ -11,19 +11,23 @@ based on the configuration. """ from __future__ import absolute_import, division, print_function + __metaclass__ = type + from re import findall, M from copy import deepcopy from ansible.module_utils.network.common import utils -from ansible_collections.vyos.vyos.plugins.module_utils.network. \ - vyos.argspec.interfaces.interfaces import InterfacesArgs +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.interfaces.interfaces import ( + InterfacesArgs, +) class InterfacesFacts(object): """ The vyos interfaces fact class """ - def __init__(self, module, subspec='config', options='options'): + + def __init__(self, module, subspec="config", options="options"): self._module = module self.argument_spec = InterfacesArgs.argument_spec spec = deepcopy(self.argument_spec) @@ -46,29 +50,30 @@ class InterfacesFacts(object): :returns: facts """ if not data: - data = connection.get_config(flags=['| grep interfaces']) + data = connection.get_config(flags=["| grep interfaces"]) objs = [] interface_names = findall( - r'^set interfaces (?:ethernet|bonding|vti|loopback|vxlan) (?:\'*)(\S+)(?:\'*)', - data, M) + r"^set interfaces (?:ethernet|bonding|vti|loopback|vxlan) (?:\'*)(\S+)(?:\'*)", + data, + M, + ) if interface_names: for interface in set(interface_names): - intf_regex = r' %s .+$' % interface.strip("'") + intf_regex = r" %s .+$" % interface.strip("'") cfg = findall(intf_regex, data, M) obj = self.render_config(cfg) - obj['name'] = interface.strip("'") + obj["name"] = interface.strip("'") if obj: objs.append(obj) facts = {} if objs: - facts['interfaces'] = [] - params = utils.validate_config(self.argument_spec, - {'config': objs}) - for cfg in params['config']: - facts['interfaces'].append(utils.remove_empties(cfg)) + facts["interfaces"] = [] + params = utils.validate_config(self.argument_spec, {"config": objs}) + for cfg in params["config"]: + facts["interfaces"].append(utils.remove_empties(cfg)) - ansible_facts['ansible_network_resources'].update(facts) + ansible_facts["ansible_network_resources"].update(facts) return ansible_facts def render_config(self, conf): @@ -81,28 +86,27 @@ class InterfacesFacts(object): :rtype: dictionary :returns: The generated config """ - vif_conf = '\n'.join(filter(lambda x: ('vif' in x), conf)) - eth_conf = '\n'.join(filter(lambda x: ('vif' not in x), conf)) - config = self.parse_attribs(['description', 'speed', 'mtu', 'duplex'], - eth_conf) - config['vifs'] = self.parse_vifs(vif_conf) + vif_conf = "\n".join(filter(lambda x: ("vif" in x), conf)) + eth_conf = "\n".join(filter(lambda x: ("vif" not in x), conf)) + config = self.parse_attribs(["description", "speed", "mtu", "duplex"], eth_conf) + config["vifs"] = self.parse_vifs(vif_conf) return utils.remove_empties(config) def parse_vifs(self, conf): - vif_names = findall(r'vif (?:\'*)(\d+)(?:\'*)', conf, M) + vif_names = findall(r"vif (?:\'*)(\d+)(?:\'*)", conf, M) vifs_list = None if vif_names: vifs_list = [] for vif in set(vif_names): - vif_regex = r' %s .+$' % vif - cfg = '\n'.join(findall(vif_regex, conf, M)) - obj = self.parse_attribs(['description', 'mtu'], cfg) - obj['vlan_id'] = int(vif) + vif_regex = r" %s .+$" % vif + cfg = "\n".join(findall(vif_regex, conf, M)) + obj = self.parse_attribs(["description", "mtu"], cfg) + obj["vlan_id"] = int(vif) if obj: vifs_list.append(obj) - vifs_list = sorted(vifs_list, key=lambda i: i['vlan_id']) + vifs_list = sorted(vifs_list, key=lambda i: i["vlan_id"]) return vifs_list @@ -110,15 +114,15 @@ class InterfacesFacts(object): config = {} for item in attribs: value = utils.parse_conf_arg(conf, item) - if value and item == 'mtu': + if value and item == "mtu": config[item] = int(value.strip("'")) elif value: config[item] = value.strip("'") else: config[item] = None - if 'disable' in conf: - config['enabled'] = False + if "disable" in conf: + config["enabled"] = False else: - config['enabled'] = True + config["enabled"] = True return utils.remove_empties(config) diff --git a/plugins/module_utils/network/vyos/facts/l3_interfaces/l3_interfaces.py b/plugins/module_utils/network/vyos/facts/l3_interfaces/l3_interfaces.py index c082c5b..306a73b 100644 --- a/plugins/module_utils/network/vyos/facts/l3_interfaces/l3_interfaces.py +++ b/plugins/module_utils/network/vyos/facts/l3_interfaces/l3_interfaces.py @@ -11,21 +11,25 @@ based on the configuration. """ from __future__ import absolute_import, division, print_function + __metaclass__ = type + import re from copy import deepcopy from ansible.module_utils.network.common import utils from ansible.module_utils.six import iteritems from ansible.module_utils.compat import ipaddress -from ansible_collections.vyos.vyos.plugins.module_utils.network. \ - vyos.argspec.l3_interfaces.l3_interfaces import L3_interfacesArgs +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.l3_interfaces.l3_interfaces import ( + L3_interfacesArgs, +) class L3_interfacesFacts(object): """ The vyos l3_interfaces fact class """ - def __init__(self, module, subspec='config', options='options'): + + def __init__(self, module, subspec="config", options="options"): self._module = module self.argument_spec = L3_interfacesArgs.argument_spec spec = deepcopy(self.argument_spec) @@ -53,27 +57,28 @@ class L3_interfacesFacts(object): # operate on a collection of resource x objs = [] interface_names = re.findall( - r'set interfaces (?:ethernet|bonding|vti|vxlan) (?:\'*)(\S+)(?:\'*)', - data, re.M) + r"set interfaces (?:ethernet|bonding|vti|vxlan) (?:\'*)(\S+)(?:\'*)", + data, + re.M, + ) if interface_names: for interface in set(interface_names): - intf_regex = r' %s .+$' % interface + intf_regex = r" %s .+$" % interface cfg = re.findall(intf_regex, data, re.M) obj = self.render_config(cfg) - obj['name'] = interface.strip("'") + obj["name"] = interface.strip("'") if obj: objs.append(obj) - ansible_facts['ansible_network_resources'].pop('l3_interfaces', None) + ansible_facts["ansible_network_resources"].pop("l3_interfaces", None) facts = {} if objs: - facts['l3_interfaces'] = [] - params = utils.validate_config(self.argument_spec, - {'config': objs}) - for cfg in params['config']: - facts['l3_interfaces'].append(utils.remove_empties(cfg)) + facts["l3_interfaces"] = [] + params = utils.validate_config(self.argument_spec, {"config": objs}) + for cfg in params["config"]: + facts["l3_interfaces"].append(utils.remove_empties(cfg)) - ansible_facts['ansible_network_resources'].update(facts) + ansible_facts["ansible_network_resources"].update(facts) return ansible_facts def render_config(self, conf): @@ -84,23 +89,23 @@ class L3_interfacesFacts(object): :rtype: dictionary :returns: The generated config """ - vif_conf = '\n'.join(filter(lambda x: ('vif' in x), conf)) - eth_conf = '\n'.join(filter(lambda x: ('vif' not in x), conf)) + vif_conf = "\n".join(filter(lambda x: ("vif" in x), conf)) + eth_conf = "\n".join(filter(lambda x: ("vif" not in x), conf)) config = self.parse_attribs(eth_conf) - config['vifs'] = self.parse_vifs(vif_conf) + config["vifs"] = self.parse_vifs(vif_conf) return utils.remove_empties(config) def parse_vifs(self, conf): - vif_names = re.findall(r'vif (\d+)', conf, re.M) + vif_names = re.findall(r"vif (\d+)", conf, re.M) vifs_list = None if vif_names: vifs_list = [] for vif in set(vif_names): - vif_regex = r' %s .+$' % vif - cfg = '\n'.join(re.findall(vif_regex, conf, re.M)) + vif_regex = r" %s .+$" % vif + cfg = "\n".join(re.findall(vif_regex, conf, re.M)) obj = self.parse_attribs(cfg) - obj['vlan_id'] = vif + obj["vlan_id"] = vif if obj: vifs_list.append(obj) @@ -108,22 +113,22 @@ class L3_interfacesFacts(object): def parse_attribs(self, conf): config = {} - ipaddrs = re.findall(r'address (\S+)', conf, re.M) - config['ipv4'] = [] - config['ipv6'] = [] + ipaddrs = re.findall(r"address (\S+)", conf, re.M) + config["ipv4"] = [] + config["ipv6"] = [] for item in ipaddrs: item = item.strip("'") - if item == 'dhcp': - config['ipv4'].append({'address': item}) - elif item == 'dhcpv6': - config['ipv6'].append({'address': item}) + if item == "dhcp": + config["ipv4"].append({"address": item}) + elif item == "dhcpv6": + config["ipv6"].append({"address": item}) else: ip_version = ipaddress.ip_address(item.split("/")[0]).version if ip_version == 4: - config['ipv4'].append({'address': item}) + config["ipv4"].append({"address": item}) else: - config['ipv6'].append({'address': item}) + config["ipv6"].append({"address": item}) for key, value in iteritems(config): if value == []: diff --git a/plugins/module_utils/network/vyos/facts/legacy/base.py b/plugins/module_utils/network/vyos/facts/legacy/base.py index 33d094b..a05516d 100644 --- a/plugins/module_utils/network/vyos/facts/legacy/base.py +++ b/plugins/module_utils/network/vyos/facts/legacy/base.py @@ -10,12 +10,13 @@ based on the configuration. """ from __future__ import absolute_import, division, print_function + __metaclass__ = type + import platform import re -from ansible.module_utils. \ - network.vyos.vyos import run_commands, get_capabilities +from ansible.module_utils.network.vyos.vyos import run_commands, get_capabilities class LegacyFactsBase(object): @@ -34,18 +35,16 @@ class LegacyFactsBase(object): class Default(LegacyFactsBase): - COMMANDS = [ - 'show version', - ] + COMMANDS = ["show version"] def populate(self): super(Default, self).populate() data = self.responses[0] - self.facts['serialnum'] = self.parse_serialnum(data) + self.facts["serialnum"] = self.parse_serialnum(data) self.facts.update(self.platform_facts()) def parse_serialnum(self, data): - match = re.search(r'HW S/N:\s+(\S+)', data) + match = re.search(r"HW S/N:\s+(\S+)", data) if match: return match.group(1) @@ -53,78 +52,74 @@ class Default(LegacyFactsBase): platform_facts = {} resp = get_capabilities(self.module) - device_info = resp['device_info'] + device_info = resp["device_info"] - platform_facts['system'] = device_info['network_os'] + platform_facts["system"] = device_info["network_os"] - for item in ('model', 'image', 'version', 'platform', 'hostname'): - val = device_info.get('network_os_%s' % item) + for item in ("model", "image", "version", "platform", "hostname"): + val = device_info.get("network_os_%s" % item) if val: platform_facts[item] = val - platform_facts['api'] = resp['network_api'] - platform_facts['python_version'] = platform.python_version() + platform_facts["api"] = resp["network_api"] + platform_facts["python_version"] = platform.python_version() return platform_facts class Config(LegacyFactsBase): - COMMANDS = [ - 'show configuration commands', - 'show system commit', - ] + COMMANDS = ["show configuration commands", "show system commit"] def populate(self): super(Config, self).populate() - self.facts['config'] = self.responses + self.facts["config"] = self.responses commits = self.responses[1] entries = list() entry = None - for line in commits.split('\n'): - match = re.match(r'(\d+)\s+(.+)by(.+)via(.+)', line) + for line in commits.split("\n"): + match = re.match(r"(\d+)\s+(.+)by(.+)via(.+)", line) if match: if entry: entries.append(entry) - entry = dict(revision=match.group(1), - datetime=match.group(2), - by=str(match.group(3)).strip(), - via=str(match.group(4)).strip(), - comment=None) + entry = dict( + revision=match.group(1), + datetime=match.group(2), + by=str(match.group(3)).strip(), + via=str(match.group(4)).strip(), + comment=None, + ) else: - entry['comment'] = line.strip() + entry["comment"] = line.strip() - self.facts['commits'] = entries + self.facts["commits"] = entries class Neighbors(LegacyFactsBase): - COMMANDS = [ - 'show lldp neighbors', - 'show lldp neighbors detail', - ] + COMMANDS = ["show lldp neighbors", "show lldp neighbors detail"] def populate(self): super(Neighbors, self).populate() all_neighbors = self.responses[0] - if 'LLDP not configured' not in all_neighbors: + if "LLDP not configured" not in all_neighbors: neighbors = self.parse(self.responses[1]) - self.facts['neighbors'] = self.parse_neighbors(neighbors) + self.facts["neighbors"] = self.parse_neighbors(neighbors) def parse(self, data): parsed = list() values = None - for line in data.split('\n'): + for line in data.split("\n"): if not line: continue - elif line[0] == ' ': - values += '\n%s' % line - elif line.startswith('Interface'): + elif line[0] == " ": + values += "\n%s" % line + elif line.startswith("Interface"): if values: parsed.append(values) values = line @@ -144,15 +139,15 @@ class Neighbors(LegacyFactsBase): return facts def parse_interface(self, data): - match = re.search(r'^Interface:\s+(\S+),', data) + match = re.search(r"^Interface:\s+(\S+),", data) return match.group(1) def parse_host(self, data): - match = re.search(r'SysName:\s+(.+)$', data, re.M) + match = re.search(r"SysName:\s+(.+)$", data, re.M) if match: return match.group(1) def parse_port(self, data): - match = re.search(r'PortDescr:\s+(.+)$', data, re.M) + match = re.search(r"PortDescr:\s+(.+)$", data, re.M) if match: return match.group(1) diff --git a/plugins/module_utils/network/vyos/utils/utils.py b/plugins/module_utils/network/vyos/utils/utils.py index 960d268..5fd0da2 100644 --- a/plugins/module_utils/network/vyos/utils/utils.py +++ b/plugins/module_utils/network/vyos/utils/utils.py @@ -5,11 +5,13 @@ # utils + from __future__ import absolute_import, division, print_function + __metaclass__ = type -def search_obj_in_list(name, lst, key='name'): +def search_obj_in_list(name, lst, key="name"): for item in lst: if item[key] == name: return item @@ -19,14 +21,14 @@ def search_obj_in_list(name, lst, key='name'): def get_interface_type(interface): """Gets the type of interface """ - if interface.startswith('eth'): - return 'ethernet' - elif interface.startswith('bond'): - return 'bonding' - elif interface.startswith('vti'): - return 'vti' - elif interface.startswith('lo'): - return 'loopback' + if interface.startswith("eth"): + return "ethernet" + elif interface.startswith("bond"): + return "bonding" + elif interface.startswith("vti"): + return "vti" + elif interface.startswith("lo"): + return "loopback" def dict_delete(base, comparable): diff --git a/plugins/module_utils/network/vyos/vyos.py b/plugins/module_utils/network/vyos/vyos.py index ee15101..2d6a1a8 100644 --- a/plugins/module_utils/network/vyos/vyos.py +++ b/plugins/module_utils/network/vyos/vyos.py @@ -34,29 +34,23 @@ from ansible.module_utils.connection import Connection, ConnectionError _DEVICE_CONFIGS = {} vyos_provider_spec = { - 'host': - dict(), - 'port': - dict(type='int'), - 'username': - dict(fallback=(env_fallback, ['ANSIBLE_NET_USERNAME'])), - 'password': - dict(fallback=(env_fallback, ['ANSIBLE_NET_PASSWORD']), no_log=True), - 'ssh_keyfile': - dict(fallback=(env_fallback, ['ANSIBLE_NET_SSH_KEYFILE']), type='path'), - 'timeout': - dict(type='int'), -} -vyos_argument_spec = { - 'provider': dict(type='dict', options=vyos_provider_spec), + "host": dict(), + "port": dict(type="int"), + "username": dict(fallback=(env_fallback, ["ANSIBLE_NET_USERNAME"])), + "password": dict(fallback=(env_fallback, ["ANSIBLE_NET_PASSWORD"]), no_log=True), + "ssh_keyfile": dict( + fallback=(env_fallback, ["ANSIBLE_NET_SSH_KEYFILE"]), type="path" + ), + "timeout": dict(type="int"), } +vyos_argument_spec = {"provider": dict(type="dict", options=vyos_provider_spec)} vyos_top_spec = { - 'host': dict(removed_in_version=2.9), - 'port': dict(removed_in_version=2.9, type='int'), - 'username': dict(removed_in_version=2.9), - 'password': dict(removed_in_version=2.9, no_log=True), - 'ssh_keyfile': dict(removed_in_version=2.9, type='path'), - 'timeout': dict(removed_in_version=2.9, type='int'), + "host": dict(removed_in_version=2.9), + "port": dict(removed_in_version=2.9, type="int"), + "username": dict(removed_in_version=2.9), + "password": dict(removed_in_version=2.9, no_log=True), + "ssh_keyfile": dict(removed_in_version=2.9, type="path"), + "timeout": dict(removed_in_version=2.9, type="int"), } vyos_argument_spec.update(vyos_top_spec) @@ -66,27 +60,27 @@ def get_provider_argspec(): def get_connection(module): - if hasattr(module, '_vyos_connection'): + if hasattr(module, "_vyos_connection"): return module._vyos_connection capabilities = get_capabilities(module) - network_api = capabilities.get('network_api') - if network_api == 'cliconf': + network_api = capabilities.get("network_api") + if network_api == "cliconf": module._vyos_connection = Connection(module._socket_path) else: - module.fail_json(msg='Invalid connection type %s' % network_api) + module.fail_json(msg="Invalid connection type %s" % network_api) return module._vyos_connection def get_capabilities(module): - if hasattr(module, '_vyos_capabilities'): + if hasattr(module, "_vyos_capabilities"): return module._vyos_capabilities try: capabilities = Connection(module._socket_path).get_capabilities() except ConnectionError as exc: - module.fail_json(msg=to_text(exc, errors='surrogate_then_replace')) + module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) module._vyos_capabilities = json.loads(capabilities) return module._vyos_capabilities @@ -103,8 +97,8 @@ def get_config(module, flags=None, format=None): try: out = connection.get_config(flags=flags, format=format) except ConnectionError as exc: - module.fail_json(msg=to_text(exc, errors='surrogate_then_replace')) - cfg = to_text(out, errors='surrogate_then_replace').strip() + module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) + cfg = to_text(out, errors="surrogate_then_replace").strip() _DEVICE_CONFIGS = cfg return cfg @@ -112,10 +106,9 @@ def get_config(module, flags=None, format=None): def run_commands(module, commands, check_rc=True): connection = get_connection(module) try: - response = connection.run_commands(commands=commands, - check_rc=check_rc) + response = connection.run_commands(commands=commands, check_rc=check_rc) except ConnectionError as exc: - module.fail_json(msg=to_text(exc, errors='surrogate_then_replace')) + module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) return response @@ -123,10 +116,10 @@ def load_config(module, commands, commit=False, comment=None): connection = get_connection(module) try: - response = connection.edit_config(candidate=commands, - commit=commit, - comment=comment) + response = connection.edit_config( + candidate=commands, commit=commit, comment=comment + ) except ConnectionError as exc: - module.fail_json(msg=to_text(exc, errors='surrogate_then_replace')) + module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) - return response.get('diff') + return response.get("diff") |