diff --git a/network/nxos/nxos_igmp_interface.py b/network/nxos/nxos_igmp_interface.py
new file mode 100644
index 00000000000..5f74d34eab1
--- /dev/null
+++ b/network/nxos/nxos_igmp_interface.py
@@ -0,0 +1,895 @@
+#!/usr/bin/python
+#
+# This file is part of Ansible
+#
+# Ansible is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Ansible is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with Ansible. If not, see .
+#
+
+DOCUMENTATION = '''
+---
+module: nxos_igmp_interface
+version_added: "2.2"
+short_description: Manages IGMP interface configuration.
+description:
+ - Manages IGMP interface configuration settings.
+extends_documentation_fragment: nxos
+author:
+ - Jason Edelman (@jedelman8)
+ - Gabriele Gerbino (@GGabriele)
+notes:
+ - When C(state=default), supported params will be reset to a default state.
+ These include C(version), C(startup_query_interval),
+ C(startup_query_count), C(robustness), C(querier_timeout), C(query_mrt),
+ C(query_interval), C(last_member_qrt), C(last_member_query_count),
+ C(group_timeout), C(report_llg), and C(immediate_leave).
+ - When C(state=absent), all configs for C(oif_prefix), C(oif_source), and
+ C(oif_routemap) will be removed.
+ - PIM must be enabled to use this module.
+ - This module is for Layer 3 interfaces.
+ - Route-map check not performed (same as CLI) check when configuring
+ route-map with 'static-oif'
+ - If restart is set to true with other params set, the restart will happen
+ last, i.e. after the configuration takes place.
+options:
+ interface:
+ description:
+ - The full interface name for IGMP configuration.
+ e.g. I(Ethernet1/2).
+ required: true
+ version:
+ description:
+ - IGMP version. It can be 2 or 3.
+ required: false
+ default: null
+ choices: ['2', '3']
+ startup_query_interval:
+ description:
+ - Query interval used when the IGMP process starts up.
+ The range is from 1 to 18000. The default is 31.
+ required: false
+ default: null
+ startup_query_count:
+ description:
+ - Query count used when the IGMP process starts up.
+ The range is from 1 to 10. The default is 2.
+ required: false
+ default: null
+ robustness:
+ description:
+ - Sets the robustness variable. Values can range from 1 to 7.
+ The default is 2.
+ required: false
+ default: null
+ querier_timeout:
+ description:
+ - Sets the querier timeout that the software uses when deciding
+ to take over as the querier. Values can range from 1 to 65535
+ seconds. The default is 255 seconds.
+ required: false
+ default: null
+ query_mrt:
+ description:
+ - Sets the response time advertised in IGMP queries.
+ Values can range from 1 to 25 seconds. The default is 10 seconds.
+ required: false
+ default: null
+ query_interval:
+ description:
+ - Sets the frequency at which the software sends IGMP host query
+ messages. Values can range from 1 to 18000 seconds.
+ he default is 125 seconds.
+ required: false
+ default: null
+ last_member_qrt:
+ description:
+ - Sets the query interval waited after sending membership reports
+ before the software deletes the group state. Values can range
+ from 1 to 25 seconds. The default is 1 second.
+ required: false
+ default: null
+ last_member_query_count:
+ description:
+ - Sets the number of times that the software sends an IGMP query
+ in response to a host leave message.
+ Values can range from 1 to 5. The default is 2.
+ required: false
+ default: null
+ group_timeout:
+ description:
+ - Sets the group membership timeout for IGMPv2.
+ Values can range from 3 to 65,535 seconds.
+ The default is 260 seconds.
+ required: false
+ default: null
+ report_llg:
+ description:
+ - Configures report-link-local-groups.
+ Enables sending reports for groups in 224.0.0.0/24.
+ Reports are always sent for nonlink local groups.
+ By default, reports are not sent for link local groups.
+ required: false
+ choices: ['true', 'false']
+ default: false
+ immediate_leave:
+ description:
+ - Enables the device to remove the group entry from the multicast
+ routing table immediately upon receiving a leave message for
+ the group. Use this command to minimize the leave latency of
+ IGMPv2 group memberships on a given IGMP interface because the
+ device does not send group-specific queries.
+ The default is disabled.
+ required: false
+ choices: ['true', 'false']
+ default: false
+ oif_routemap:
+ description:
+ - Configure a routemap for static outgoing interface (OIF).
+ required: false
+ default: null
+ oif_prefix:
+ description:
+ - Configure a prefix for static outgoing interface (OIF).
+ required: false
+ default: null
+ oif_source:
+ description:
+ - Configure a source for static outgoing interface (OIF).
+ required: false
+ default: null
+ restart:
+ description:
+ - Restart IGMP.
+ required: false
+ choices: ['true', 'false']
+ default: null
+ state:
+ description:
+ - Manages desired state of the resource.
+ required: false
+ default: present
+ choices: ['present', 'default']
+'''
+EXAMPLES = '''
+- nxos_igmp_interface:
+ interface: ethernet1/32
+ startup_query_interval: 30
+ state: present
+ username: "{{ un }}"
+ password: "{{ pwd }}"
+ host: "{{ inventory_hostname }}"
+'''
+
+RETURN = '''
+proposed:
+ description: k/v pairs of parameters passed into module
+ returned: always
+ type: dict
+ sample: {"asn": "65535", "router_id": "1.1.1.1", "vrf": "test"}
+existing:
+ description: k/v pairs of existing BGP configuration
+ type: dict
+ sample: {"asn": "65535", "bestpath_always_compare_med": false,
+ "bestpath_aspath_multipath_relax": false,
+ "bestpath_compare_neighborid": false,
+ "bestpath_compare_routerid": false,
+ "bestpath_cost_community_ignore": false,
+ "bestpath_med_confed": false,
+ "bestpath_med_missing_as_worst": false,
+ "bestpath_med_non_deterministic": false, "cluster_id": "",
+ "confederation_id": "", "confederation_peers": "",
+ "graceful_restart": true, "graceful_restart_helper": false,
+ "graceful_restart_timers_restart": "120",
+ "graceful_restart_timers_stalepath_time": "300", "local_as": "",
+ "log_neighbor_changes": false, "maxas_limit": "",
+ "neighbor_down_fib_accelerate": false, "reconnect_interval": "60",
+ "router_id": "11.11.11.11", "suppress_fib_pending": false,
+ "timer_bestpath_limit": "", "timer_bgp_hold": "180",
+ "timer_bgp_keepalive": "60", "vrf": "test"}
+end_state:
+ description: k/v pairs of BGP configuration after module execution
+ returned: always
+ type: dict
+ sample: {"asn": "65535", "bestpath_always_compare_med": false,
+ "bestpath_aspath_multipath_relax": false,
+ "bestpath_compare_neighborid": false,
+ "bestpath_compare_routerid": false,
+ "bestpath_cost_community_ignore": false,
+ "bestpath_med_confed": false,
+ "bestpath_med_missing_as_worst": false,
+ "bestpath_med_non_deterministic": false, "cluster_id": "",
+ "confederation_id": "", "confederation_peers": "",
+ "graceful_restart": true, "graceful_restart_helper": false,
+ "graceful_restart_timers_restart": "120",
+ "graceful_restart_timers_stalepath_time": "300", "local_as": "",
+ "log_neighbor_changes": false, "maxas_limit": "",
+ "neighbor_down_fib_accelerate": false, "reconnect_interval": "60",
+ "router_id": "1.1.1.1", "suppress_fib_pending": false,
+ "timer_bestpath_limit": "", "timer_bgp_hold": "180",
+ "timer_bgp_keepalive": "60", "vrf": "test"}
+updates:
+ description: commands sent to the device
+ returned: always
+ type: list
+ sample: ["router bgp 65535", "vrf test", "router-id 1.1.1.1"]
+changed:
+ description: check to see if a change was made on the device
+ returned: always
+ type: boolean
+ sample: true
+'''
+
+import json
+import collections
+
+# COMMON CODE FOR MIGRATION
+import re
+
+from ansible.module_utils.basic import get_exception
+from ansible.module_utils.netcfg import NetworkConfig, ConfigLine
+from ansible.module_utils.shell import ShellError
+
+try:
+ from ansible.module_utils.nxos import get_module
+except ImportError:
+ from ansible.module_utils.nxos import NetworkModule
+
+
+def to_list(val):
+ if isinstance(val, (list, tuple)):
+ return list(val)
+ elif val is not None:
+ return [val]
+ else:
+ return list()
+
+
+class CustomNetworkConfig(NetworkConfig):
+
+ def expand_section(self, configobj, S=None):
+ if S is None:
+ S = list()
+ S.append(configobj)
+ for child in configobj.children:
+ if child in S:
+ continue
+ self.expand_section(child, S)
+ return S
+
+ def get_object(self, path):
+ for item in self.items:
+ if item.text == path[-1]:
+ parents = [p.text for p in item.parents]
+ if parents == path[:-1]:
+ return item
+
+ def to_block(self, section):
+ return '\n'.join([item.raw for item in section])
+
+ def get_section(self, path):
+ try:
+ section = self.get_section_objects(path)
+ return self.to_block(section)
+ except ValueError:
+ return list()
+
+ def get_section_objects(self, path):
+ if not isinstance(path, list):
+ path = [path]
+ obj = self.get_object(path)
+ if not obj:
+ raise ValueError('path does not exist in config')
+ return self.expand_section(obj)
+
+
+ def add(self, lines, parents=None):
+ """Adds one or lines of configuration
+ """
+
+ ancestors = list()
+ offset = 0
+ obj = None
+
+ ## global config command
+ if not parents:
+ for line in to_list(lines):
+ item = ConfigLine(line)
+ item.raw = line
+ if item not in self.items:
+ self.items.append(item)
+
+ else:
+ for index, p in enumerate(parents):
+ try:
+ i = index + 1
+ obj = self.get_section_objects(parents[:i])[0]
+ ancestors.append(obj)
+
+ except ValueError:
+ # add parent to config
+ offset = index * self.indent
+ obj = ConfigLine(p)
+ obj.raw = p.rjust(len(p) + offset)
+ if ancestors:
+ obj.parents = list(ancestors)
+ ancestors[-1].children.append(obj)
+ self.items.append(obj)
+ ancestors.append(obj)
+
+ # add child objects
+ for line in to_list(lines):
+ # check if child already exists
+ for child in ancestors[-1].children:
+ if child.text == line:
+ break
+ else:
+ offset = len(parents) * self.indent
+ item = ConfigLine(line)
+ item.raw = line.rjust(len(line) + offset)
+ item.parents = ancestors
+ ancestors[-1].children.append(item)
+ self.items.append(item)
+
+
+def get_network_module(**kwargs):
+ try:
+ return get_module(**kwargs)
+ except NameError:
+ return NetworkModule(**kwargs)
+
+def get_config(module, include_defaults=False):
+ config = module.params['config']
+ if not config:
+ try:
+ config = module.get_config()
+ except AttributeError:
+ defaults = module.params['include_defaults']
+ config = module.config.get_config(include_defaults=defaults)
+ return CustomNetworkConfig(indent=2, contents=config)
+
+def load_config(module, candidate):
+ config = get_config(module)
+
+ commands = candidate.difference(config)
+ commands = [str(c).strip() for c in commands]
+
+ save_config = module.params['save']
+
+ result = dict(changed=False)
+
+ if commands:
+ if not module.check_mode:
+ try:
+ module.configure(commands)
+ except AttributeError:
+ module.config(commands)
+
+ if save_config:
+ try:
+ module.config.save_config()
+ except AttributeError:
+ module.execute(['copy running-config startup-config'])
+
+ result['changed'] = True
+ result['updates'] = commands
+
+ return result
+# END OF COMMON CODE
+
+def get_cli_body_ssh(command, response, module):
+ """Get response for when transport=cli. This is kind of a hack and mainly
+ needed because these modules were originally written for NX-API. And
+ not every command supports "| json" when using cli/ssh. As such, we assume
+ if | json returns an XML string, it is a valid command, but that the
+ resource doesn't exist yet. Instead, the output will be a raw string
+ when issuing commands containing 'show run'.
+ """
+ if 'xml' in response[0]:
+ body = []
+ elif 'show run' in command:
+ body = response
+ else:
+ try:
+ response = response[0].replace(command + '\n\n', '').strip()
+ body = [json.loads(response)]
+ except ValueError:
+ module.fail_json(msg='Command does not support JSON output',
+ command=command)
+ return body
+
+
+def execute_show(cmds, module, command_type=None):
+ command_type_map = {
+ 'cli_show': 'json',
+ 'cli_show_ascii': 'text'
+ }
+
+ try:
+ if command_type:
+ response = module.execute(cmds, command_type=command_type)
+ else:
+ response = module.execute(cmds)
+ except ShellError:
+ clie = get_exception()
+ module.fail_json(msg='Error sending {0}'.format(cmds),
+ error=str(clie))
+ except AttributeError:
+ try:
+ if command_type:
+ command_type = command_type_map.get(command_type)
+ module.cli.add_commands(cmds, output=command_type)
+ response = module.cli.run_commands()
+ else:
+ module.cli.add_commands(cmds, output=command_type)
+ response = module.cli.run_commands()
+ except ShellError:
+ clie = get_exception()
+ module.fail_json(msg='Error sending {0}'.format(cmds),
+ error=str(clie))
+ return response
+
+
+def execute_show_command(command, module, command_type='cli_show'):
+ if module.params['transport'] == 'cli':
+ command += ' | json'
+ cmds = [command]
+ response = execute_show(cmds, module)
+ body = get_cli_body_ssh(command, response, module)
+ elif module.params['transport'] == 'nxapi':
+ cmds = [command]
+ body = execute_show(cmds, module, command_type=command_type)
+
+ return body
+
+
+def get_interface_mode(interface, intf_type, module):
+ command = 'show interface {0}'.format(interface)
+ interface = {}
+ mode = 'unknown'
+
+ if intf_type in ['ethernet', 'portchannel']:
+ body = execute_show_command(command, module)[0]
+ interface_table = body['TABLE_interface']['ROW_interface']
+ mode = str(interface_table.get('eth_mode', 'layer3'))
+ if mode == 'access' or mode == 'trunk':
+ mode = 'layer2'
+ elif intf_type == 'loopback' or intf_type == 'svi':
+ mode = 'layer3'
+ return mode
+
+
+def get_interface_type(interface):
+ if interface.upper().startswith('ET'):
+ return 'ethernet'
+ elif interface.upper().startswith('VL'):
+ return 'svi'
+ elif interface.upper().startswith('LO'):
+ return 'loopback'
+ elif interface.upper().startswith('MG'):
+ return 'management'
+ elif interface.upper().startswith('MA'):
+ return 'management'
+ elif interface.upper().startswith('PO'):
+ return 'portchannel'
+ else:
+ return 'unknown'
+
+
+def apply_key_map(key_map, table):
+ new_dict = {}
+ for key, value in table.items():
+ new_key = key_map.get(key)
+ if new_key:
+ value = table.get(key)
+ if value:
+ new_dict[new_key] = value
+ else:
+ new_dict[new_key] = value
+ return new_dict
+
+
+def flatten_list(command_lists):
+ flat_command_list = []
+ for command in command_lists:
+ if isinstance(command, list):
+ flat_command_list.extend(command)
+ else:
+ flat_command_list.append(command)
+ return flat_command_list
+
+
+def get_igmp_interface(module, interface):
+ command = 'show ip igmp interface {0}'.format(interface)
+ igmp = {}
+
+ key_map = {
+ 'IGMPVersion': 'version',
+ 'ConfiguredStartupQueryInterval': 'startup_query_interval',
+ 'StartupQueryCount': 'startup_query_count',
+ 'RobustnessVariable': 'robustness',
+ 'QuerierTimeout': 'querier_timeout',
+ 'ConfiguredMaxResponseTime': 'query_mrt',
+ 'ConfiguredQueryInterval': 'query_interval',
+ 'LastMemberMTR': 'last_member_qrt',
+ 'LastMemberQueryCount': 'last_member_query_count',
+ 'ConfiguredGroupTimeout': 'group_timeout'
+ }
+
+ body = execute_show_command(command, module)[0]
+
+ if body:
+ resource = body['TABLE_vrf']['ROW_vrf']['TABLE_if']['ROW_if']
+ igmp = apply_key_map(key_map, resource)
+ report_llg = str(resource['ReportingForLinkLocal'])
+ if report_llg == 'true':
+ igmp['report_llg'] = True
+ elif report_llg == 'false':
+ igmp['report_llg'] = False
+
+ immediate_leave = str(resource['ImmediateLeave']) # returns en or dis
+ if immediate_leave == 'en':
+ igmp['immediate_leave'] = True
+ elif immediate_leave == 'dis':
+ igmp['immediate_leave'] = False
+
+ # the next block of code is used to retrieve anything with:
+ # ip igmp static-oif *** i.e.. could be route-map ROUTEMAP
+ # or PREFIX source , etc.
+ command = 'show run interface {0} | inc oif'.format(interface)
+
+ body = execute_show_command(
+ command, module, command_type='cli_show_ascii')[0]
+
+ staticoif = []
+ if body:
+ split_body = body.split('\n')
+ route_map_regex = ('.*ip igmp static-oif route-map\s+'
+ '(?P\S+).*')
+ prefix_source_regex = ('.*ip igmp static-oif\s+(?P'
+ '((\d+.){3}\d+))(\ssource\s'
+ '(?P