diff --git a/library/__init__.py b/library/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/library/iosxr_facts.py b/library/iosxr_facts.py new file mode 100644 index 0000000..190e7cb --- /dev/null +++ b/library/iosxr_facts.py @@ -0,0 +1,199 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# Copyright 2019 Red Hat +# GNU General Public License v3.0+ +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +""" +The module file for iosxr_facts +""" + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +ANSIBLE_METADATA = {'metadata_version': '1.1', + 'status': [u'preview'], + 'supported_by': 'network'} + + +DOCUMENTATION = """ +--- +module: iosxr_facts +version_added: 2.2 +short_description: Get facts about iosxr devices. +extends_documentation_fragment: iosxr +description: + - Collects facts from network devices running the iosxr operating + system. This module places the facts gathered in the fact tree keyed by the + respective resource name. The facts module will always collect a + base set of facts from the device and can enable or disable + collection of additional facts. +author: + - Ricardo Carrillo Cruz (@rcarrillocruz) + - Nilashish Chakraborty (@Nilashishc) +options: + gather_subset: + description: + - When supplied, this argument will restrict the facts collected + to a given subset. Possible values for this argument include + all, hardware, config, and interfaces. Can specify a list of + values to include a larger subset. Values can also be used + with an initial C(M(!)) to specify that a specific subset should + not be collected. + required: false + default: '!config' + gather_network_resources: + description: + - When supplied, this argument will restrict the facts collected + to a given subset. Possible values for this argument include + all and the resources like interfaces, lacp etc. + Can specify a list of values to include a larger subset. Values + can also be used with an initial C(M(!)) to specify that a + specific subset should not be collected. + required: false + choices: ['all', 'lacp'] + version_added: "2.9" +""" + +EXAMPLES = """ +# Gather all facts +- iosxr_facts: + gather_subset: all + gather_network_resources: all + +# Collect only the config and default facts +- iosxr_facts: + gather_subset: + - config + +# Do not collect hardware facts +- iosxr_facts: + gather_subset: + - "!hardware" + +# Collect only the lag_interfaces facts +- iosxr_facts: + gather_subset: + - "!all" + - "!min" + gather_network_resources: + - lacp + +# Do not collect lag_interfaces facts +- iosxr_facts: + gather_network_resources: + - "!lacp" + +# Collect lag_interfaces and minimal default facts +- iosxr_facts: + gather_subset: min + gather_network_resources: lacp +""" + +RETURN = """ +ansible_net_gather_subset: + description: The list of fact subsets collected from the device + returned: always + type: list + +# default +ansible_net_version: + description: The operating system version running on the remote device + returned: always + type: str +ansible_net_hostname: + description: The configured hostname of the device + returned: always + type: str +ansible_net_image: + description: The image file the device is running + returned: always + type: str +ansible_net_api: + description: The name of the transport + returned: always + type: str +ansible_net_python_version: + description: The Python version Ansible controller is using + returned: always + type: str +ansible_net_model: + description: The model name returned from the device + returned: always + type: str + +# hardware +ansible_net_filesystems: + description: All file system names available on the device + returned: when hardware is configured + type: list +ansible_net_memfree_mb: + description: The available free memory on the remote device in Mb + returned: when hardware is configured + type: int +ansible_net_memtotal_mb: + description: The total memory on the remote device in Mb + returned: when hardware is configured + type: int + +# config +ansible_net_config: + description: The current active config from the device + returned: when config is configured + type: str + +# interfaces +ansible_net_all_ipv4_addresses: + description: All IPv4 addresses configured on the device + returned: when interfaces is configured + type: list +ansible_net_all_ipv6_addresses: + description: All IPv6 addresses configured on the device + returned: when interfaces is configured + type: list +ansible_net_interfaces: + description: A hash of all interfaces running on the system + returned: when interfaces is configured + type: dict +ansible_net_neighbors: + description: The list of LLDP neighbors from the remote device + returned: when interfaces is configured + type: dict + +# network resources +ansible_net_gather_network_resources: + description: The list of fact resource subsets collected from the device + returned: always + type: list +""" + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.network.iosxr.iosxr import iosxr_argument_spec +from ansible.module_utils.network.iosxr.argspec.facts.facts import FactsArgs +from ansible.module_utils.network.iosxr.facts.facts import Facts + + +def main(): + """ + Main entry point for module execution + + :returns: ansible_facts + """ + spec = FactsArgs.argument_spec + spec.update(iosxr_argument_spec) + + module = AnsibleModule(argument_spec=spec, + supports_check_mode=True) + warnings = ['default value for `gather_subset` ' + 'will be changed to `min` from `!config` v2.11 onwards'] + + result = Facts(module).get_facts() + + ansible_facts, additional_warnings = result + warnings.extend(additional_warnings) + + module.exit_json(ansible_facts=ansible_facts, warnings=warnings) + + +if __name__ == '__main__': + main() diff --git a/library/iosxr_interfaces.py b/library/iosxr_interfaces.py new file mode 100644 index 0000000..284d242 --- /dev/null +++ b/library/iosxr_interfaces.py @@ -0,0 +1,372 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# Copyright 2019 Red Hat +# GNU General Public License v3.0+ +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +############################################# +# WARNING # +############################################# +# +# This file is auto generated by the resource +# module builder playbook. +# +# Do not edit this file manually. +# +# Changes to this file will be over written +# by the resource module builder. +# +# Changes should be made in the model used to +# generate this file or in the resource module +# builder template. +# +############################################# + +""" +The module file for ios_interfaces +""" + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +GENERATOR_VERSION = '1.0' + +ANSIBLE_METADATA = {'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'network'} + +NETWORK_OS = "iosxr" +RESOURCE = "interfaces" +COPYRIGHT = "Copyright 2019 Red Hat" + +DOCUMENTATION = """ + module: iosxr_interfaces + version_added: 2.9 + short_description: Manage interface attributes on Cisco IOS-XR network devices + description: This module manages the interface attributes on Cisco IOS-XR network devices. + author: Sumit Jaiswal (@justjais) + options: + config: + description: A dictionary of interface options + type: list + elements: dict + suboptions: + name: + description: + - Full name of the interface to configure in C(type + path) format. e.g. C(GigabitEthernet0/0/0/0) + type: str + required: True + description: + description: + - Interface description. + type: str + enabled: + default: True + description: + - Administrative state of the interface. + - Set the value to C(True) to administratively enable the interface or C(False) to disable it. + type: bool + active: + default: active + description: + - Whether the interface is C(active) or C(preconfigured). Preconfiguration allows you to configure modular + services cards before they are inserted into the router. When the cards are inserted, they are instantly + configured. Active cards are the ones already inserted. + type: str + choices: ['active', 'preconfigure'] + speed: + description: + - Configure the speed for an interface. Default is auto-negotiation when not configured. + type: str + choices: ['10', '100', '1000'] + mtu: + description: + - Sets the MTU value for the interface. Range is between 64 and 65535. Applicable for Ethernet interfaces only. + type: str + duplex: + description: + - Configures the interface duplex mode. Default is auto-negotiation when not configured. + type: str + choices: ['full', 'half'] + state: + choices: + - merged + - replaced + - overridden + - deleted + default: merged + description: + - The state the configuration should be left in + type: str +""" + +EXAMPLES = """ +--- +# Using merged + +# Before state: +# ------------- +# +# viosxr#show running-config interface +# interface GigabitEthernet0/0/0/1 +# shutdown +# ! +# interface GigabitEthernet0/0/0/2 +# vrf custB +# ipv4 address 178.18.169.23 255.255.255.0 +# dot1q native vlan 30 +# ! +# interface GigabitEthernet0/0/0/3 +# description Replaced by Ansible Team +# mtu 2000 +# vrf custB +# ipv4 address 10.10.0.2 255.255.255.0 +# dot1q native vlan 1021 +# ! + +- name: Configure Ethernet interfaces + iosxr_interfaces: + config: + - name: GigabitEthernet0/0/0/2 + description: 'Configured by Ansible' + enabled: True + - name: GigabitEthernet0/0/0/3 + description: 'Configured by Ansible Network' + enabled: False + duplex: full + operation: merged + +# After state: +# ------------ +# +# viosxr#show running-config interface +# interface GigabitEthernet0/0/0/1 +# shutdown +# ! +# interface GigabitEthernet0/0/0/2 +# description Configured and Merged by Ansible Network +# vrf custB +# ipv4 address 178.18.169.23 255.255.255.0 +# dot1q native vlan 30 +# ! +# interface GigabitEthernet0/0/0/3 +# description Configured and Merged by Ansible Network +# mtu 2600 +# vrf custB +# ipv4 address 10.10.0.2 255.255.255.0 +# duplex full +# shutdown +# dot1q native vlan 1021 +# ! + +# Using replaced + +# Before state: +# ------------ +# +# viosxr#show running-config interface +# interface GigabitEthernet0/0/0/1 +# description Configured by Ansible +# shutdown +# ! +# interface GigabitEthernet0/0/0/2 +# description Test +# vrf custB +# ipv4 address 178.18.169.23 255.255.255.0 +# dot1q native vlan 30 +# ! +# interface GigabitEthernet0/0/0/3 +# vrf custB +# ipv4 address 10.10.0.2 255.255.255.0 +# dot1q native vlan 1021 +# ! + +- name: Configure following interfaces and replace their existing config + iosxr_interfaces: + config: + - name: GigabitEthernet0/0/0/2 + description: Configured by Ansible + enabled: True + mtu: 2000 + - name: GigabitEthernet0/0/0/3 + description: 'Configured by Ansible Network' + enabled: False + duplex: auto + operation: replaced + +# After state: +# ------------ +# +# viosxr#show running-config interface +# interface GigabitEthernet0/0/0/1 +# description Configured by Ansible +# shutdown +# ! +# interface GigabitEthernet0/0/0/2 +# description Configured and Replaced by Ansible +# mtu 2000 +# vrf custB +# ipv4 address 178.18.169.23 255.255.255.0 +# dot1q native vlan 30 +# ! +# interface GigabitEthernet0/0/0/3 +# description Configured and Replaced by Ansible Network +# vrf custB +# ipv4 address 10.10.0.2 255.255.255.0 +# duplex half +# shutdown +# dot1q native vlan 1021 +# ! + +# Using overridden + +# Before state: +# ------------ +# +# viosxr#show running-config interface +# interface GigabitEthernet0/0/0/1 +# shutdown +# ! +# interface GigabitEthernet0/0/0/2 +# description Configured by Ansible +# vrf custB +# ipv4 address 178.18.169.23 255.255.255.0 +# dot1q native vlan 30 +# ! +# interface GigabitEthernet0/0/0/3 +# description Configured by Ansible +# mtu 2600 +# vrf custB +# ipv4 address 10.10.0.2 255.255.255.0 +# duplex full +# shutdown +# dot1q native vlan 1021 +# ! + +- name: Override interfaces + iosxr_interfaces: + config: + - name: GigabitEthernet0/0/0/2 + description: 'Configured by Ansible' + enabled: True + duplex: auto + - name: GigabitEthernet0/0/0/3 + description: 'Configured by Ansible Network' + enabled: False + speed: 1000 + operation: overridden + +# After state: +# ------------ +# +# viosxr#show running-config interface +# interface GigabitEthernet0/0/0/1 +# shutdown +# ! +# interface GigabitEthernet0/0/0/2 +# description Configured and Overridden by Ansible Network +# vrf custB +# ipv4 address 178.18.169.23 255.255.255.0 +# speed 1000 +# dot1q native vlan 30 +# ! +# interface GigabitEthernet0/0/0/3 +# description Configured and Overridden by Ansible Network +# mtu 2000 +# vrf custB +# ipv4 address 10.10.0.2 255.255.255.0 +# duplex full +# shutdown +# dot1q native vlan 1021 +# ! + +# Using deleted + +# Before state: +# ------------ +# +# viosxr#show running-config interface +# interface GigabitEthernet0/0/0/1 +# shutdown +# ! +# interface GigabitEthernet0/0/0/2 +# description Configured and Overridden by Ansible Network +# vrf custB +# ipv4 address 178.18.169.23 255.255.255.0 +# speed 1000 +# dot1q native vlan 30 +# ! +# interface GigabitEthernet0/0/0/3 +# description Configured and Overridden by Ansible Network +# mtu 2000 +# vrf custB +# ipv4 address 10.10.0.2 255.255.255.0 +# duplex full +# shutdown +# dot1q native vlan 1021 +# ! + +- name: Delete IOSXR interfaces as in given arguments + iosxr_interfaces: + config: + - name: GigabitEthernet0/0/0/2 + - name: GigabitEthernet0/0/0/3 + operation: deleted + +# After state: +# ------------ +# +# viosxr#show running-config interface +# interface GigabitEthernet0/0/0/1 +# shutdown +# ! +# interface GigabitEthernet0/0/0/2 +# vrf custB +# ipv4 address 178.18.169.23 255.255.255.0 +# dot1q native vlan 30 +# ! +# interface GigabitEthernet0/0/0/3 +# vrf custB +# ipv4 address 10.10.0.2 255.255.255.0 +# dot1q native vlan 1021 +# ! +""" + +RETURN = """ +before: + description: The configuration prior to the model invocation + returned: always + type: list + sample: The configuration returned will alwys be in the same format of the paramters above. +after: + description: The resulting configuration model invocation + returned: when changed + type: list + sample: The configuration returned will alwys be in the same format of the paramters above. +commands: + description: The set of commands pushed to the remote device + returned: always + type: list + sample: ['interface GigabitEthernet0/0/0/2', 'description: Configured by Ansible', 'shutdown'] +""" + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.network.iosxr.argspec.interfaces.interfaces import InterfacesArgs +from ansible.module_utils.network.iosxr.config.interfaces.interfaces import Interfaces + + +def main(): + """ + Main entry point for module execution + :returns: the result form module invocation + """ + module = AnsibleModule(argument_spec=InterfacesArgs.argument_spec, + supports_check_mode=True) + + result = Interfaces(module).execute_module() + module.exit_json(**result) + + +if __name__ == '__main__': + main() + diff --git a/module_utils/__init__.py b/module_utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/module_utils/network/__init__.py b/module_utils/network/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/module_utils/network/iosxr/__init__.py b/module_utils/network/iosxr/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/module_utils/network/iosxr/argspec/__init__.py b/module_utils/network/iosxr/argspec/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/module_utils/network/iosxr/argspec/facts/__init__.py b/module_utils/network/iosxr/argspec/facts/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/module_utils/network/iosxr/argspec/facts/facts.py b/module_utils/network/iosxr/argspec/facts/facts.py new file mode 100644 index 0000000..4689f3a --- /dev/null +++ b/module_utils/network/iosxr/argspec/facts/facts.py @@ -0,0 +1,29 @@ +# +# -*- coding: utf-8 -*- +# Copyright 2019 Red Hat +# GNU General Public License v3.0+ +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +""" +The arg spec for the iosxr facts module. +""" + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +class FactsArgs(object): # pylint: disable=R0903 + """ The arg spec for the iosxr facts module + """ + + def __init__(self, **kwargs): + pass + + choices = [ + 'all', + 'interfaces' + ] + + argument_spec = { + 'gather_subset': dict(default=['!config'], type='list'), + 'gather_network_resources': dict(choices=choices, type='list'), + } diff --git a/module_utils/network/iosxr/argspec/interfaces/__init__.py b/module_utils/network/iosxr/argspec/interfaces/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/module_utils/network/iosxr/argspec/interfaces/interfaces.py b/module_utils/network/iosxr/argspec/interfaces/interfaces.py new file mode 100644 index 0000000..11e0646 --- /dev/null +++ b/module_utils/network/iosxr/argspec/interfaces/interfaces.py @@ -0,0 +1,47 @@ +# +# -*- coding: utf-8 -*- +# Copyright 2019 Red Hat +# GNU General Public License v3.0+ +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +############################################# +# WARNING # +############################################# +# +# This file is auto generated by the resource +# module builder playbook. +# +# Do not edit this file manually. +# +# Changes to this file will be over written +# by the resource module builder. +# +# Changes should be made in the model used to +# generate this file or in the resource module +# builder template. +# +############################################# +""" +The arg spec for the ios_interfaces module +""" + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +class InterfacesArgs(object): + + def __init__(self, **kwargs): + pass + + argument_spec = {'config': {'elements': 'dict', + 'options': {'name': {'type': 'str', 'required': True}, + 'description': {'type': 'str'}, + 'enabled': {'default': True, 'type': 'bool'}, + 'speed': {'type': 'int', 'choices': [10, 100, 1000]}, + 'mtu': {'type': 'int'}, + 'duplex': {'type': 'str', 'choices': ['full', 'half']}}, + 'type': 'list'}, + 'state': {'choices': ['merged', 'replaced', 'overridden', 'deleted'], + 'default': 'merged', + 'type': 'str'}} diff --git a/module_utils/network/iosxr/config/__init__.py b/module_utils/network/iosxr/config/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/module_utils/network/iosxr/config/interfaces/__init__.py b/module_utils/network/iosxr/config/interfaces/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/module_utils/network/iosxr/config/interfaces/interfaces.py b/module_utils/network/iosxr/config/interfaces/interfaces.py new file mode 100644 index 0000000..208c1e8 --- /dev/null +++ b/module_utils/network/iosxr/config/interfaces/interfaces.py @@ -0,0 +1,278 @@ +# -*- coding: utf-8 -*- +# Copyright 2019 Red Hat Inc. +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +""" +The iosxr_interfaces class +It is in this file where the current configuration (as dict) +is compared to the provided configuration (as dict) and the command set +necessary to bring the current configuration to it's desired end-state is +created +""" + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +from ansible.module_utils.network.common.cfg.base import ConfigBase +from ansible.module_utils.network.common.utils import to_list +from ansible.module_utils.network.iosxr.facts.facts import Facts +from ansible.module_utils.network.iosxr.utils.utils import get_interface_type, dict_diff +from ansible.module_utils.network.iosxr.utils.utils import remove_command_from_interface, add_command_to_interface +from ansible.module_utils.network.iosxr.utils.utils import filter_dict_having_none_value, remove_duplicate_interface +import q + +class Interfaces(ConfigBase): + """ + The iosxr_interfaces class + """ + + gather_subset = [ + '!all', + '!min', + ] + + gather_network_resources = [ + 'interfaces', + ] + + params = ('description', 'mtu', 'speed', 'duplex') + + def __init__(self, module): + super(Interfaces, self).__init__(module) + + def get_interfaces_facts(self): + """ Get the 'facts' (the current configuration) + :rtype: A dictionary + :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') + if not interfaces_facts: + return [] + return interfaces_facts + + def execute_module(self): + """ Execute the module + :rtype: A dictionary + :returns: The result from module execution + """ + result = {'changed': False} + commands = list() + warnings = list() + + existing_interfaces_facts = self.get_interfaces_facts() + commands.extend(self.set_config(existing_interfaces_facts)) + if commands: + if not self._module.check_mode: + self._connection.edit_config(commands) + result['changed'] = True + result['commands'] = commands + + changed_interfaces_facts = self.get_interfaces_facts() + + result['before'] = existing_interfaces_facts + if result['changed']: + result['after'] = changed_interfaces_facts + + result['warnings'] = warnings + return result + + def set_config(self, existing_interfaces_facts): + """ Collect the configuration from the args passed to the module, + collect the current configuration (as a dict from facts) + :rtype: A list + :returns: the commands necessary to migrate the current configuration + to the desired configuration + """ + want = self._module.params['config'] + have = existing_interfaces_facts + resp = self.set_state(want, have) + + return to_list(resp) + + def set_state(self, want, have): + """ Select the appropriate function based on the state provided + :param want: the desired configuration as a dictionary + :param have: the current configuration as a dictionary + :rtype: A list + :returns: the commands necessary to migrate the current configuration + to the desired configuration + """ + commands = [] + state = self._module.params['state'] + + if state == 'overridden': + commands = self._state_overridden(want, have) + elif state == 'deleted': + commands = self._state_deleted(want, have) + elif state == 'merged': + commands = self._state_merged(want, have) + elif state == 'replaced': + commands = self._state_replaced(want, have) + + return commands + + @staticmethod + def _state_replaced(want, have): + """ The command generator when state is replaced + :rtype: A list + :returns: the commands necessary to migrate the current configuration + to the desired configuration + """ + commands = [] + + for interface in want: + for each in have: + if each['name'] == interface['name']: + break + elif interface['name'] in each['name']: + break + else: + continue + have_dict = filter_dict_having_none_value(interface, each) + kwargs = {'want': {}, 'have': have_dict} + commands.extend(Interfaces._clear_config(**kwargs)) + kwargs = {'want': interface, 'have': each, 'commands': commands} + commands.extend(Interfaces._set_config(**kwargs)) + # Remove the duplicate interface call + commands = remove_duplicate_interface(commands) + + return commands + + @staticmethod + def _state_overridden(want, have): + """ The command generator when state is overridden + :rtype: A list + :returns: the commands necessary to migrate the current configuration + to the desired configuration + """ + commands = [] + + for each in have: + for interface in want: + if each['name'] == interface['name']: + break + elif interface['name'] in each['name']: + break + else: + # We didn't find a matching desired state, which means we can + # pretend we recieved an empty desired state. + interface = dict(name=each['name']) + kwargs = {'want': interface, 'have': each} + commands.extend(Interfaces._clear_config(**kwargs)) + continue + have_dict = filter_dict_having_none_value(interface, each) + kwargs = {'want': {}, 'have': have_dict} + commands.extend(Interfaces._clear_config(**kwargs)) + kwargs = {'want': interface, 'have': each, 'commands': commands} + commands.extend(Interfaces._set_config(**kwargs)) + # Remove the duplicate interface call + commands = remove_duplicate_interface(commands) + + return commands + + @staticmethod + def _state_merged(want, have): + """ The command generator when state is merged + :rtype: A list + :returns: the commands necessary to merge the provided into + the current configuration + """ + commands = [] + + for interface in want: + for each in have: + if each['name'] == interface['name']: + break + elif interface['name'] in each['name']: + break + else: + continue + kwargs = {'want': interface, 'have': each} + commands.extend(Interfaces._set_config(**kwargs)) + + return commands + + @staticmethod + def _state_deleted(want, have): + """ The command generator when state is deleted + :rtype: A list + :returns: the commands necessary to remove the current configuration + of the provided objects + """ + commands = [] + + if want: + for interface in want: + for each in have: + if each['name'] == interface['name']: + break + elif interface['name'] in each['name']: + break + else: + continue + interface = dict(name=interface['name']) + kwargs = {'want': interface, 'have': each} + commands.extend(Interfaces._clear_config(**kwargs)) + else: + for each in have: + kwargs = {'want': {}, 'have': each} + commands.extend(Interfaces._clear_config(**kwargs)) + + return commands + + @staticmethod + def _set_config(**kwargs): + # Set the interface config based on the want and have config + commands = [] + want = kwargs['want'] + have = kwargs['have'] + + interface = 'interface ' + want['name'] + + # Get the diff b/w want and have + want_dict = dict_diff(want) + have_dict = dict_diff(have) + diff = want_dict - have_dict + q(want_dict, have_dict, diff) + if diff: + diff = dict(diff) + for item in Interfaces.params: + if diff.get(item): + cmd = item + ' ' + str(want.get(item)) + add_command_to_interface(interface, cmd, commands) + if diff.get('enabled'): + add_command_to_interface(interface, 'no shutdown', commands) + elif diff.get('enabled') is False: + add_command_to_interface(interface, 'shutdown', commands) + + return commands + + @staticmethod + def _clear_config(**kwargs): + # Delete the interface config based on the want and have config + commands = [] + want = kwargs['want'] + have = kwargs['have'] + if want.get('name'): + interface_type = get_interface_type(want['name']) + interface = 'interface ' + want['name'] + else: + interface_type = get_interface_type(have['name']) + interface = 'interface ' + have['name'] + + if have.get('description') and want.get('description') != have.get('description'): + remove_command_from_interface(interface, 'description', commands) + if not have.get('enabled') and want.get('enabled') != have.get('enabled'): + # if enable is False set enable as True which is the default behavior + remove_command_from_interface(interface, 'shutdown', commands) + + if interface_type.lower() == 'gigabitethernet': + if have.get('speed') and have.get('speed') != 'auto' and want.get('speed') != have.get('speed'): + remove_command_from_interface(interface, 'speed', commands) + if have.get('duplex') and have.get('duplex') != 'auto' and want.get('duplex') != have.get('duplex'): + remove_command_from_interface(interface, 'duplex', commands) + if have.get('mtu') and want.get('mtu') != have.get('mtu'): + remove_command_from_interface(interface, 'mtu', commands) + + return commands diff --git a/module_utils/network/iosxr/facts/__init__.py b/module_utils/network/iosxr/facts/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/module_utils/network/iosxr/facts/facts.py b/module_utils/network/iosxr/facts/facts.py new file mode 100644 index 0000000..8222fca --- /dev/null +++ b/module_utils/network/iosxr/facts/facts.py @@ -0,0 +1,59 @@ +# +# -*- coding: utf-8 -*- +# Copyright 2019 Red Hat +# GNU General Public License v3.0+ +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +""" +The facts class for iosxr +this file validates each subset of facts and selectively +calls the appropriate facts gathering function +""" + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +from ansible.module_utils.network.iosxr.argspec.facts.facts import FactsArgs +from ansible.module_utils.network.common.facts.facts import FactsBase +from ansible.module_utils.network.iosxr.facts.interfaces.interfaces import InterfacesFacts +from ansible.module_utils.network.iosxr.facts.legacy.base import Default, Hardware, Interfaces, Config + + +FACT_LEGACY_SUBSETS = dict( + default=Default, + hardware=Hardware, + interfaces=Interfaces, + config=Config, +) +FACT_RESOURCE_SUBSETS = dict( + interfaces=InterfacesFacts, +) + + +class Facts(FactsBase): + """ The fact class for iosxr + """ + + VALID_LEGACY_GATHER_SUBSETS = frozenset(FACT_LEGACY_SUBSETS.keys()) + VALID_RESOURCE_SUBSETS = frozenset(FACT_RESOURCE_SUBSETS.keys()) + + def __init__(self, module): + super(Facts, self).__init__(module) + + def get_facts(self, legacy_facts_type=None, resource_facts_type=None, data=None): + """ Collect the facts for iosxr + + :param legacy_facts_type: List of legacy facts types + :param resource_facts_type: List of resource fact types + :param data: previously collected conf + :rtype: dict + :return: the facts gathered + """ + 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) + + if self.VALID_LEGACY_GATHER_SUBSETS: + self.get_network_legacy_facts(FACT_LEGACY_SUBSETS, legacy_facts_type) + + return self.ansible_facts, self._warnings diff --git a/module_utils/network/iosxr/facts/interfaces/__init__.py b/module_utils/network/iosxr/facts/interfaces/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/module_utils/network/iosxr/facts/interfaces/interfaces.py b/module_utils/network/iosxr/facts/interfaces/interfaces.py new file mode 100644 index 0000000..346e91d --- /dev/null +++ b/module_utils/network/iosxr/facts/interfaces/interfaces.py @@ -0,0 +1,102 @@ +# +# -*- coding: utf-8 -*- +# Copyright 2019 Red Hat +# GNU General Public License v3.0+ +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +""" +The ios interfaces fact class +It is in this file the configuration is collected from the device +for a given resource, parsed, and the facts tree is populated +based on the configuration. +""" + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + +from copy import deepcopy +import re +from ansible.module_utils.network.common import utils +from ansible.module_utils.network.iosxr.utils.utils import get_interface_type, normalize_interface +from ansible.module_utils.network.iosxr.argspec.interfaces.interfaces import InterfacesArgs + + +class InterfacesFacts(object): + """ The iosxr interfaces fact class + """ + + def __init__(self, module, subspec='config', options='options'): + self._module = module + self.argument_spec = InterfacesArgs.argument_spec + spec = deepcopy(self.argument_spec) + if subspec: + if options: + facts_argument_spec = spec[subspec][options] + else: + facts_argument_spec = spec[subspec] + else: + facts_argument_spec = spec + + self.generated_spec = utils.generate_dict(facts_argument_spec) + + def populate_facts(self, connection, ansible_facts, data=None): + """ Populate the facts for interfaces + :param module: the module instance + :param connection: the device connection + :param data: previously collected conf + :rtype: dictionary + :returns: facts + """ + if connection: + pass + + objs = [] + if not data: + data = connection.get('show running-config interface') + + # operate on a collection of resource x + config = data.split('interface ') + for conf in config: + if conf: + obj = self.render_config(self.generated_spec, conf) + 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)) + + ansible_facts['ansible_network_resources'].update(facts) + return ansible_facts + + def render_config(self, spec, conf): + """ + Render config as dictionary structure and delete keys from spec for null values + :param spec: The facts tree, generated from the argspec + :param conf: The configuration + :rtype: dictionary + :returns: The generated config + """ + + config = deepcopy(spec) + match = re.search(r'^(\S+)', conf) + if match.group(1).lower() == "preconfigure": + match = re.search(r'^(\S+ \S+)', conf) + intf = match.group(1) + if get_interface_type(intf) == 'unknown': + return {} + # populate the facts from the configuration + config['name'] = normalize_interface(intf) + config['description'] = utils.parse_conf_arg(conf, 'description') + if utils.parse_conf_arg(conf, 'speed'): + config['speed'] = int(utils.parse_conf_arg(conf, 'speed')) + if utils.parse_conf_arg(conf, 'mtu'): + config['mtu'] = int(utils.parse_conf_arg(conf, 'mtu')) + config['duplex'] = utils.parse_conf_arg(conf, 'duplex') + enabled = utils.parse_conf_cmd_arg(conf, 'shutdown', False) + config['enabled'] = enabled if enabled is not None else True + + return utils.remove_empties(config) diff --git a/module_utils/network/iosxr/utils/__init__.py b/module_utils/network/iosxr/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/module_utils/network/iosxr/utils/utils.py b/module_utils/network/iosxr/utils/utils.py new file mode 100644 index 0000000..5ad3452 --- /dev/null +++ b/module_utils/network/iosxr/utils/utils.py @@ -0,0 +1,148 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# Copyright 2019 Red Hat Inc. +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + +# utils + +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +from ansible.module_utils.six import iteritems + + +def remove_command_from_interface(interface, cmd, commands): + # To delete the passed config + if interface not in commands: + commands.insert(0, interface) + commands.append('no %s' % cmd) + return commands + + +def add_command_to_interface(interface, cmd, commands): + # To set the passed config + if interface not in commands: + commands.insert(0, interface) + commands.append(cmd) + + +def dict_diff(sample_dict): + # Generate a set with passed dictionary for comparison + test_dict = {} + for k, v in iteritems(sample_dict): + if v is not None: + test_dict.update({k: v}) + return_set = set(tuple(test_dict.items())) + return return_set + + +def filter_dict_having_none_value(want, have): + # Generate dict with have dict value which is None in want dict + test_dict = dict() + test_dict['name'] = want.get('name') + for k, v in iteritems(want): + if v is None: + val = have.get(k) + test_dict.update({k: val}) + return test_dict + + +def remove_duplicate_interface(commands): + # Remove duplicate interface from commands + set_cmd = [] + for each in commands: + if 'interface' in each: + interface = each + if interface not in set_cmd: + set_cmd.append(each) + else: + set_cmd.append(each) + + return set_cmd + + +def search_obj_in_list(name, lst): + for o in lst: + if o['name'] == name: + return o + return None + + +def normalize_interface(name): + """Return the normalized interface name + """ + if not name: + return + + def _get_number(name): + digits = '' + for char in name: + if char.isdigit() or char in '/.': + digits += char + return digits + + if name.lower().startswith('gi'): + if_type = 'GigabitEthernet' + elif name.lower().startswith('fa'): + if_type = 'FastEthernet' + elif name.lower().startswith('fo'): + if_type = 'FortyGigE' + elif name.lower().startswith('et'): + if_type = 'Ethernet' + elif name.lower().startswith('vl'): + if_type = 'Vlan' + elif name.lower().startswith('lo'): + if_type = 'loopback' + elif name.lower().startswith('po'): + if_type = 'port-channel' + elif name.lower().startswith('nv'): + if_type = 'nve' + elif name.lower().startswith('twe'): + if_type = 'TwentyFiveGigE' + elif name.lower().startswith('hu'): + if_type = 'HundredGigE' + else: + if_type = None + + number_list = name.split(' ') + if len(number_list) == 2: + number = number_list[-1].strip() + else: + number = _get_number(name) + + if if_type: + proper_interface = if_type + number + else: + proper_interface = name + + return proper_interface + + +def get_interface_type(interface): + """Gets the type of interface + """ + + if interface.upper().startswith('GI'): + return 'GigabitEthernet' + elif interface.upper().startswith('FA'): + return 'FastEthernet' + elif interface.upper().startswith('FO'): + return 'FortyGigE' + elif interface.upper().startswith('ET'): + return 'Ethernet' + elif interface.upper().startswith('VL'): + return 'Vlan' + elif interface.upper().startswith('LO'): + return 'loopback' + elif interface.upper().startswith('PO'): + return 'port-channel' + elif interface.upper().startswith('NV'): + return 'nve' + elif interface.upper().startswith('TWE'): + return 'TwentyFiveGigE' + elif interface.upper().startswith('HU'): + return 'HundredGigE' + elif interface.upper().startswith('PRE'): + return 'preconfigure' + else: + return 'unknown' \ No newline at end of file diff --git a/tests/modules/interfaces/deleted.yaml b/tests/modules/interfaces/deleted.yaml new file mode 100644 index 0000000..e49d2ca --- /dev/null +++ b/tests/modules/interfaces/deleted.yaml @@ -0,0 +1,34 @@ +--- +- debug: + msg: "START iosxr_interfaces Deleted integration tests on connection={{ ansible_connection }}" + +- include_tasks: reset_config.yaml + +- name: Delete attributes of given interfaces (Note: This won't delete the interface itself) + iosxr_interfaces: + config: + - name: GigabitEthernet0/0/0/1 + - name: GigabitEthernet0/0/0/2 + state: deleted + +- iosxr_facts: + gather_subset: net_configuration_interfaces + +- set_fact: + expected_output: + - name: GigabitEthernet0/0/0/1 + duplex: auto + enable: True + - name: GigabitEthernet0/0/0/2 + duplex: auto + enable: True + - name: GigabitEthernet0/0/0/3 + description: 'Configured by Ansible-Network' + duplex: auto + enable: True + +- assert: + that: + - "ansible_facts.net_configuration.interfaces == expected_output" + +- include_tasks: reset_config.yaml diff --git a/tests/modules/interfaces/main.yaml b/tests/modules/interfaces/main.yaml new file mode 100644 index 0000000..506c655 --- /dev/null +++ b/tests/modules/interfaces/main.yaml @@ -0,0 +1,15 @@ +--- +- hosts: iosxr + gather_subset: + - net_configuration_interfaces + + tasks: + - import_role: + name: ~/collections/network + + - include_tasks: "{{ item }}.yaml" + loop: + - merged + - replaced + - overridden + - delete diff --git a/tests/modules/interfaces/merged.yaml b/tests/modules/interfaces/merged.yaml new file mode 100644 index 0000000..ed8bee7 --- /dev/null +++ b/tests/modules/interfaces/merged.yaml @@ -0,0 +1,44 @@ +--- +- debug: + msg: "START iosxr_interfaces Merged integration tests on connection={{ ansible_connection }}" + +- include_tasks: reset_config.yaml + +- name: Merge provided configuration with device configuration + iosxr_interfaces: + config: + - name: GigabitEthernet0/0/0/1 + enable: True + - name: GigabitEthernet0/0/0/2 + description: 'Configured by Ansible-Network' + speed: 10 + duplex: half + enable: False + state: merged + +- iosxr_facts: + gather_subset: net_configuration_interfaces + +- set_fact: + expected_output: + - name: GigabitEthernet0/0/0/1 + description: Interface 1 + speed: 100 + duplex: auto + enable: True + - name: GigabitEthernet0/0/0/2 + description: 'Configured by Ansible-Network' + speed: 10 + duplex: half + enable: False + mtu: 1000 + - name: GigabitEthernet0/0/0/3 + description: 'Configured by Ansible-Network' + duplex: auto + enable: True + +- assert: + that: + - "ansible_facts.net_configuration.interfaces == expected_output" + +- include_tasks: reset_config.yaml diff --git a/tests/modules/interfaces/overridden.yaml b/tests/modules/interfaces/overridden.yaml new file mode 100644 index 0000000..e8e2b76 --- /dev/null +++ b/tests/modules/interfaces/overridden.yaml @@ -0,0 +1,37 @@ +--- +- debug: + msg: "START iosxr_interfaces Overridden integration tests on connection={{ ansible_connection }}" + +- include_tasks: reset_config.yaml + +- name: Override device configuration of all interfaces with provided configuration + iosxr_interfaces: + config: + - name: GigabitEthernet0/0/0/1 + enable: True + - name: GigabitEthernet0/0/0/2 + description: 'Configured by Ansible-Network' + enable: False + state: overridden + +- iosxr_facts: + gather_subset: net_configuration_interfaces + +- set_fact: + expected_output: + - name: GigabitEthernet0/0/0/2 + duplex: auto + enable: True + - name: GigabitEthernet0/0/0/2 + description: 'Configured by Ansible-Network' + duplex: auto + enable: False + - name: GigabitEthernet0/0/0/3 + duplex: auto + enable: True + +- assert: + that: + - "ansible_facts.net_configuration.interfaces == expected_output" + +- include_tasks: reset_config.yaml diff --git a/tests/modules/interfaces/replaced.yaml b/tests/modules/interfaces/replaced.yaml new file mode 100644 index 0000000..8a5e74d --- /dev/null +++ b/tests/modules/interfaces/replaced.yaml @@ -0,0 +1,38 @@ +--- +- debug: + msg: "START iosxr_interfaces Replaced integration tests on connection={{ ansible_connection }}" + +- include_tasks: reset_config.yaml + +- name: Replaces device configuration of listed interfaces with provided configuration + iosxr_interfaces: + config: + - name: GigabitEthernet0/0/0/1 + enable: True + - name: GigabitEthernet0/0/0/2 + description: 'Configured by Ansible-Network' + enable: False + state: replaced + +- iosxr_facts: + gather_subset: net_configuration_interfaces + +- set_fact: + expected_output: + - name: GigabitEthernet0/0/0/1 + duplex: auto + enable: True + - name: GigabitEthernet0/0/0/2 + description: 'Configured by Ansible-Network' + duplex: auto + enable: False + - name: GigabitEthernet0/0/0/3 + description: 'Configured by Ansible-Network' + duplex: auto + enable: True + +- assert: + that: + - "ansible_facts.net_configuration.interfaces == expected_output" + +- include_tasks: reset_config.yaml diff --git a/tests/modules/interfaces/reset_config.yaml b/tests/modules/interfaces/reset_config.yaml new file mode 100644 index 0000000..d91e0a0 --- /dev/null +++ b/tests/modules/interfaces/reset_config.yaml @@ -0,0 +1,40 @@ +--- +- name: Reset initial config + cli_config: + config: | + interface GigabitEthernet0/0/0/1 + description Ansible-Network configured + shutdown + duplex auto + speed 100 + interface GigabitEthernet0/0/0/2 + duplex auto + speed auto + mtu 1000 + interface GigabitEthernet0/0/0/3 + description Ansible-Network configured + duplex auto + speed auto + +- iosxr_facts: + gather_subset: net_configuration_interfaces + +- set_fact: + expected_output: + - name: GigabitEthernet0/0/0/1 + description: 'Ansible-Network configured' + speed: 100 + duplex: auto + enable: False + - name: GigabitEthernet0/0/0/2 + duplex: auto + enable: True + mtu: 1000 + - name: GigabitEthernet0/0/0/3 + description: 'Configured by Ansible-Network' + duplex: auto + enable: True + +- assert: + that: + - "ansible_facts.net_configuration.interfaces == expected_output" \ No newline at end of file