def checkpoint(filename, module): commands = [{ 'command': 'terminal dont-ask', 'output': 'text', }, { 'command': 'checkpoint file %s' % filename, 'output': 'text', }] run_commands(module, commands)
def execute_show_command(command, module, command_type='cli_show_ascii'): cmds = [command] device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if network_api == 'cliconf': body = run_commands(module, cmds) elif network_api == 'nxapi': body = run_commands(module, cmds) return body
def execute_show_command(command, module): device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if network_api == 'cliconf': cmds = [command] body = run_commands(module, cmds) elif network_api == 'nxapi': cmds = {'command': command, 'output': 'text'} body = run_commands(module, cmds) return body
def get_auto_recovery_default(module): auto = False data = run_commands(module, ['show inventory | json'])[0] pid = data['TABLE_inv']['ROW_inv'][0]['productid'] if re.search(r'N7K', pid): auto = True elif re.search(r'N9K', pid): data = run_commands(module, ['show hardware | json'])[0] ver = data['kickstart_ver_str'] if re.search(r'7.0\(3\)F', ver): auto = True return auto
def execute_show_command(command, module): device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if network_api == 'cliconf': if 'show port-channel summary' in command: command += ' | json' cmds = [command] body = run_commands(module, cmds) elif network_api == 'nxapi': cmds = [command] body = run_commands(module, cmds) return body
def main(): argument_spec = dict( flush_routes=dict(type='bool'), enforce_rtr_alert=dict(type='bool'), restart=dict(type='bool', default=False), state=dict(choices=['present', 'default'], default='present') ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() check_args(module, warnings) current = get_current(module) desired = get_desired(module) state = module.params['state'] restart = module.params['restart'] commands = list() if state == 'default': if current['flush_routes']: commands.append('no ip igmp flush-routes') if current['enforce_rtr_alert']: commands.append('no ip igmp enforce-router-alert') elif state == 'present': ldict = {'flush_routes': 'flush-routes', 'enforce_rtr_alert': 'enforce-router-alert'} for arg in ['flush_routes', 'enforce_rtr_alert']: if desired[arg] and not current[arg]: commands.append('ip igmp {0}'.format(ldict.get(arg))) elif current[arg] and not desired[arg]: commands.append('no ip igmp {0}'.format(ldict.get(arg))) result = {'changed': False, 'updates': commands, 'warnings': warnings} if commands: if not module.check_mode: load_config(module, commands) result['changed'] = True if module.params['restart']: cmd = {'command': 'restart igmp', 'output': 'text'} run_commands(module, cmd) module.exit_json(**result)
def execute_show_command(module, command): format = 'json' cmds = [{ 'command': command, 'output': format, }] output = run_commands(module, cmds, False) if len(output) == 0 or len(output[0]) == 0: # If we get here the platform does not # support structured output. Resend as # text. cmds[0]['output'] = 'text' output = run_commands(module, cmds, False) return output
def get_interface_mode(name, module): """Gets current mode of interface: layer2 or layer3 Args: device (Device): This is the device object of an NX-API enabled device using the Device class within device.py interface (string): full name of interface, i.e. Ethernet1/1, loopback10, port-channel20, vlan20 Returns: str: 'layer2' or 'layer3' """ command = 'show interface {0} | json'.format(name) intf_type = get_interface_type(name) mode = 'unknown' interface_table = {} try: body = run_commands(module, [command])[0] interface_table = body['TABLE_interface']['ROW_interface'] except (KeyError, AttributeError, IndexError): return mode if interface_table: # HACK FOR NOW if intf_type in ['ethernet', 'portchannel']: mode = str(interface_table.get('eth_mode', 'layer3')) if mode in ['access', 'trunk']: mode = 'layer2' if mode == 'routed': mode = 'layer3' elif intf_type == 'loopback' or intf_type == 'svi': mode = 'layer3' return mode
def execute_show_command(command, module, output='text'): command = { 'command': command, 'output': output, } return run_commands(module, [command])
def get_udld_interface(module, interface): command = 'show run udld all | section ' + interface.title() + '$' interface_udld = {} mode = None mode_str = None try: body = run_commands(module, [{'command': command, 'output': 'text'}])[0] if 'aggressive' in body: mode = 'aggressive' mode_str = 'aggressive' elif 'no udld enable' in body: mode = 'disabled' mode_str = 'no udld enable' elif 'no udld disable' in body: mode = 'enabled' mode_str = 'no udld disable' elif 'udld disable' in body: mode = 'disabled' mode_str = 'udld disable' elif 'udld enable' in body: mode = 'enabled' mode_str = 'udld enable' interface_udld['mode'] = mode except (KeyError, AttributeError, IndexError): interface_udld = {} return interface_udld, mode_str
def execute_show_command(command, module): command = { 'command': command, 'output': 'json', } return run_commands(module, command)
def execute_show_command(command, module): command = [{ 'command': command, 'output': 'text', }] return run_commands(module, command)
def interface_is_portchannel(name, module): """Checks to see if an interface is part of portchannel bundle Args: interface (str): full name of interface, i.e. Ethernet1/1 Returns: True/False based on if interface is a member of a portchannel bundle """ intf_type = get_interface_type(name) if intf_type == 'ethernet': command = 'show interface {0} | json'.format(name) try: body = run_commands(module, [command])[0] interface_table = body['TABLE_interface']['ROW_interface'] except (KeyError, AttributeError, IndexError): interface_table = None if interface_table: state = interface_table.get('eth_bundle') if state: return True else: return False return False
def get_switchport(port, module): """Gets current config of L2 switchport Args: device (Device): This is the device object of an NX-API enabled device using the Device class within device.py port (str): full name of interface, i.e. Ethernet1/1 Returns: dictionary with k/v pairs for L2 vlan config """ command = 'show interface {0} switchport | json'.format(port) try: body = run_commands(module, [command])[0] sp_table = body['TABLE_interface']['ROW_interface'] except (KeyError, AttributeError, IndexError): sp_table = None if sp_table: key_map = { "interface": "name", "oper_mode": "mode", "switchport": "switchport", "access_vlan": "access_vlan", "access_vlan_name": "access_vlan_name", "native_vlan": "native_vlan", "native_vlan_name": "native_vlan_name", "trunk_vlans": "trunk_vlans" } sp = apply_key_map(key_map, sp_table) return sp else: return {}
def get_available_features(feature, module): available_features = {} feature_regex = r'(?P<feature>\S+)\s+\d+\s+(?P<state>.*)' command = {'command': 'show feature', 'output': 'text'} try: body = run_commands(module, [command])[0] split_body = body.splitlines() except (KeyError, IndexError): return {} for line in split_body: try: match_feature = re.match(feature_regex, line, re.DOTALL) feature_group = match_feature.groupdict() feature = feature_group['feature'] state = feature_group['state'] except AttributeError: feature = '' state = '' if feature and state: if 'enabled' in state: state = 'enabled' if feature not in available_features: available_features[feature] = state else: if available_features[feature] == 'disabled' and state == 'enabled': available_features[feature] = state return available_features
def get_flash_size(module): command = 'dir {0}'.format(module.params['file_system']) body = run_commands(module, {'command': command, 'output': 'text'})[0] match = re.search(r'(\d+) bytes free', body) bytes_free = match.group(1) return int(bytes_free)
def execute_show_command(command, module): if 'show run' not in command: output = 'json' else: output = 'text' cmds = [{ 'command': command, 'output': output, }] return run_commands(module, cmds)[0]
def get_active_vpc_peer_link(module): peer_link = None try: body = run_commands(module, ['show vpc brief | json'])[0] peer_link = body['TABLE_peerlink']['ROW_peerlink']['peerlink-ifindex'] except (KeyError, AttributeError, TypeError): return peer_link return peer_link
def execute_show_command(command, module): cmd = {} cmd['answer'] = None cmd['command'] = command cmd['output'] = 'text' cmd['prompt'] = None body = run_commands(module, [cmd]) return body
def execute_show_command(command, module, command_type='cli_show'): if 'status' not in command: output = 'json' else: output = 'text' cmds = [{ 'command': command, 'output': output, }] body = run_commands(module, cmds) return body
def run(self, command, output='text'): command_string = command command = { 'command': command, 'output': output } resp = run_commands(self.module, [command], check_rc=False) try: return resp[0] except IndexError: self.warnings.append('command %s failed, facts will not be populated' % command_string) return None
def execute_show_command(command, module): if 'show run' not in command: command = { 'command': command, 'output': 'json', } else: command = { 'command': command, 'output': 'text', } return run_commands(module, [command])
def execute_show_command(command, module, command_type='cli_show'): if command_type == 'cli_show_ascii': cmds = [{ 'command': command, 'output': 'text', }] else: cmds = [{ 'command': command, 'output': 'json', }] return run_commands(module, cmds)
def execute_show_command(command, module, text=False): if text: cmds = [{ 'command': command, 'output': 'text' }] else: cmds = [{ 'command': command, 'output': 'json' }] return run_commands(module, cmds)
def execute_show_command(command, module): if 'show run' not in command: output = 'json' else: output = 'text' cmds = [{ 'command': command, 'output': output, }] body = run_commands(module, cmds, check_rc=False) if body and "Invalid" in body[0]: return [] else: return body
def get_vrf_list(module): try: body = run_commands(module, ['show vrf all | json'])[0] vrf_table = body['TABLE_vrf']['ROW_vrf'] except (KeyError, AttributeError): return [] vrf_list = [] if vrf_table: for each in vrf_table: vrf_list.append(str(each['vrf_name'].lower())) return vrf_list
def map_config_to_obj(module): out = run_commands(module, ['show user-account | json']) data = out[0] objects = list() for item in to_list(data['TABLE_template']['ROW_template']): objects.append({ 'name': item['usr_name'], 'configured_password': parse_password(item), 'sshkey': item.get('sshkey_info'), 'roles': parse_roles(item), 'state': 'present' }) return objects
def get_existing_portchannel_to_vpc_mappings(module): pc_vpc_mapping = {} try: body = run_commands(module, ['show vpc brief | json'])[0] vpc_table = body['TABLE_vpc']['ROW_vpc'] except (KeyError, AttributeError, TypeError): vpc_table = None if vpc_table: if isinstance(vpc_table, dict): vpc_table = [vpc_table] for vpc in vpc_table: pc_vpc_mapping[str(vpc['vpc-id'])] = str(vpc['vpc-ifindex']) return pc_vpc_mapping
def map_config_to_obj(module): out = run_commands(module, ['show run all | inc nxapi'], check_rc=False)[0] match = re.search(r'no feature nxapi', out, re.M) # There are two possible outcomes when nxapi is disabled on nxos platforms. # 1. Nothing is displayed in the running config. # 2. The 'no feature nxapi' command is displayed in the running config. if match or out == '': return {'state': 'absent'} out = str(out).strip() obj = {'state': 'present'} obj.update(parse_http(out)) obj.update(parse_https(out)) obj.update(parse_sandbox(out)) return obj
def get_current(module): cmd = ('show running-config | inc ntp') master = False logging = False stratum = None output = run_commands(module, ({'command': cmd, 'output': 'text'}))[0] if output: match = re.search(r"^ntp master(?: (\d+))", output, re.M) if match: master = True stratum = match.group(1) logging = 'ntp logging' in output.lower() return {'master': master, 'stratum': stratum, 'logging': logging}
def get_ping_results(command, module): cmd = {'command': command, 'output': 'text'} ping = run_commands(module, [cmd])[0] if not ping: module.fail_json(msg="An unexpected error occurred. Check all params.", command=command, destination=module.params['dest'], vrf=module.params['vrf'], source=module.params['source']) elif "can't bind to address" in ping: module.fail_json(msg="Can't bind to source address.", command=command) elif "bad context" in ping: module.fail_json(msg="Wrong VRF name inserted.", command=command, vrf=module.params['vrf']) else: splitted_ping = ping.split('\n') reference_point = get_statistics_summary_line(splitted_ping) summary, ping_pass = get_summary(splitted_ping, reference_point) rtt = get_rtt(splitted_ping, summary['packet_loss'], reference_point + 2) return (summary, rtt, ping_pass)
def get_current(module): cmd = ('show running-config', 'show ntp logging') output = run_commands(module, ({ 'command': cmd[0], 'output': 'text' }, { 'command': cmd[1], 'output': 'text' })) match = re.search(r"^ntp master(?: (\d+))", output[0], re.M) if match: master = True stratum = match.group(1) else: master = False stratum = None logging = 'enabled' in output[1].lower() return {'master': master, 'stratum': stratum, 'logging': logging}
def map_config_to_obj(module): objs = list() output = run_commands(module, ['show port-channel summary | json'])[0] if not output: return list() try: channels = output['TABLE_channel']['ROW_channel'] except (TypeError, KeyError): return objs if channels: if isinstance(channels, list): for channel in channels: obj = parse_channel_options(module, output, channel) objs.append(obj) elif isinstance(channels, dict): obj = parse_channel_options(module, output, channels) objs.append(obj) return objs
def md5sum_check(module, dst, file_system): command = 'show file {0}{1} md5sum'.format(file_system, dst) remote_filehash = run_commands(module, { 'command': command, 'output': 'text' })[0] remote_filehash = to_bytes(remote_filehash, errors='surrogate_or_strict') local_file = module.params['local_file'] try: with open(local_file, 'rb') as f: filecontent = f.read() except (OSError, IOError) as exc: module.fail_json(msg="Error reading the file: %s" % to_text(exc)) filecontent = to_bytes(filecontent, errors='surrogate_or_strict') local_filehash = hashlib.md5(filecontent).hexdigest() if local_filehash == remote_filehash: return True else: return False
def match_facility_default(module, facility, want_level): ''' Check wanted facility to see if it matches current device default ''' matches_default = False # Sample output from show logging level command # Facility Default Severity Current Session Severity # -------- ---------------- ------------------------ # bfd 5 5 # # 0(emergencies) 1(alerts) 2(critical) # 3(errors) 4(warnings) 5(notifications) # 6(information) 7(debugging) regexl = r'\S+\s+(\d+)\s+(\d+)' cmd = {'command': 'show logging level {0}'.format(facility), 'output': 'text'} facility_data = run_commands(module, cmd) for line in facility_data[0].split('\n'): mo = re.search(regexl, line) if mo and int(mo.group(1)) == int(want_level) and int(mo.group(2)) == int(want_level): matches_default = True return matches_default
def get_portchannel_vpc_config(module, portchannel): peer_link_pc = None peer_link = False vpc = "" pc = "" config = {} try: body = run_commands(module, ['show vpc brief | json'])[0] table = body['TABLE_peerlink']['ROW_peerlink'] except (KeyError, AttributeError, TypeError): table = {} if table: peer_link_pc = table.get('peerlink-ifindex', None) if peer_link_pc: plpc = str(peer_link_pc[2:]) if portchannel == plpc: config['portchannel'] = portchannel config['peer-link'] = True config['vpc'] = vpc mapping = get_existing_portchannel_to_vpc_mappings(module) for existing_vpc, port_channel in mapping.items(): port_ch = str(port_channel[2:]) if port_ch == portchannel: pc = port_ch vpc = str(existing_vpc) config['portchannel'] = pc config['peer-link'] = peer_link config['vpc'] = vpc return config
def get_vlan(vlanid, module): """Get instance of VLAN as a dictionary """ command = 'show vlan id %s | json' % vlanid try: body = run_commands(module, [command])[0] vlan_table = body['TABLE_vlanbriefid']['ROW_vlanbriefid'] mtu_table = body['TABLE_mtuinfoid']['ROW_mtuinfoid'] except (TypeError, IndexError, KeyError): return {} key_map = { "vlanshowbr-vlanid-utf": "vlan_id", "vlanshowbr-vlanname": "name", "vlanshowbr-vlanstate": "vlan_state", "vlanshowbr-shutstate": "admin_state" } vlan = apply_key_map(key_map, vlan_table) vlan['mode'] = mtu_table['vlanshowinfo-vlanmode'] value_map = { "admin_state": { "shutdown": "down", "noshutdown": "up" }, "mode": { "fabricpath-vlan": "fabricpath", "ce-vlan": "ce" } } vlan = apply_value_map(value_map, vlan) vlan['mapped_vni'] = get_vni(vlanid, module) return vlan
def rollback(filename, module): commands = [{ 'command': 'rollback running-config file %s' % filename, 'output': 'text', }] run_commands(module, commands)
def map_config_to_obj(module): obj = [] data = get_config(module, flags=['| section logging']) for line in data.split('\n'): match = re.search(r'logging (\S+)', line, re.M) if match: if match.group(1) in DEST_GROUP: dest = match.group(1) facility = None if dest == 'server': facility = parse_facility(line) elif match.group(1) == 'level': match_facility = re.search(r'logging level (\S+)', line, re.M) facility = match_facility.group(1) dest = None else: dest = None facility = None obj.append({ 'dest': dest, 'remote_server': parse_remote_server(line, dest), 'name': parse_name(line, dest), 'facility': facility, 'dest_level': parse_dest_level(line, dest, parse_name(line, dest)), 'facility_level': parse_facility_level(line, facility) }) cmd = [{ 'command': 'show logging | section enabled | section console', 'output': 'text' }, { 'command': 'show logging | section enabled | section monitor', 'output': 'text' }] default_data = run_commands(module, cmd) for line in default_data: flag = False match = re.search( r'Logging (\w+):(?:\s+) (?:\w+) (?:\W)Severity: (\w+)', str(line), re.M) if match: if match.group(1) == 'console' and match.group(2) == 'critical': dest_level = '2' flag = True elif match.group(1) == 'monitor' and match.group( 2) == 'notifications': dest_level = '5' flag = True if flag: obj.append({ 'dest': match.group(1), 'remote_server': None, 'name': None, 'facility': None, 'dest_level': dest_level, 'facility_level': None }) return obj
def main(): argument_spec = dict( interface=dict(required=True, type='str'), version=dict(required=False, type='str'), startup_query_interval=dict(required=False, type='str'), startup_query_count=dict(required=False, type='str'), robustness=dict(required=False, type='str'), querier_timeout=dict(required=False, type='str'), query_mrt=dict(required=False, type='str'), query_interval=dict(required=False, type='str'), last_member_qrt=dict(required=False, type='str'), last_member_query_count=dict(required=False, type='str'), group_timeout=dict(required=False, type='str'), report_llg=dict(type='bool'), immediate_leave=dict(type='bool'), oif_routemap=dict(required=False, type='str'), oif_prefix=dict(required=False, type='str', removed_in_version='2.10'), oif_source=dict(required=False, type='str', removed_in_version='2.10'), oif_ps=dict(required=False, type='raw'), restart=dict(type='bool', default=False), state=dict(choices=['present', 'absent', 'default'], default='present') ) argument_spec.update(nxos_argument_spec) mutually_exclusive = [('oif_ps', 'oif_prefix'), ('oif_ps', 'oif_source'), ('oif_ps', 'oif_routemap'), ('oif_prefix', 'oif_routemap')] module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, supports_check_mode=True) warnings = list() check_args(module, warnings) state = module.params['state'] interface = module.params['interface'] oif_prefix = module.params['oif_prefix'] oif_source = module.params['oif_source'] oif_routemap = module.params['oif_routemap'] oif_ps = module.params['oif_ps'] if oif_source and not oif_prefix: module.fail_json(msg='oif_prefix required when setting oif_source') elif oif_source and oif_prefix: oif_ps = [{'source': oif_source, 'prefix': oif_prefix}] elif not oif_source and oif_prefix: oif_ps = [{'prefix': oif_prefix}] intf_type = get_interface_type(interface) if get_interface_mode(interface, intf_type, module) == 'layer2': module.fail_json(msg='this module only works on Layer 3 interfaces') existing = get_igmp_interface(module, interface) existing_copy = existing.copy() end_state = existing_copy if not existing.get('version'): module.fail_json(msg='pim needs to be enabled on the interface') existing_oif_prefix_source = existing.get('oif_prefix_source') # not json serializable existing.pop('oif_prefix_source') if oif_routemap and existing_oif_prefix_source: module.fail_json(msg='Delete static-oif configurations on this ' 'interface if you want to use a routemap') if oif_ps and existing.get('oif_routemap'): module.fail_json(msg='Delete static-oif route-map configuration ' 'on this interface if you want to config ' 'static entries') args = [ 'version', 'startup_query_interval', 'startup_query_count', 'robustness', 'querier_timeout', 'query_mrt', 'query_interval', 'last_member_qrt', 'last_member_query_count', 'group_timeout', 'report_llg', 'immediate_leave', 'oif_routemap', ] changed = False commands = [] proposed = dict((k, v) for k, v in module.params.items() if v is not None and k in args) CANNOT_ABSENT = ['version', 'startup_query_interval', 'startup_query_count', 'robustness', 'querier_timeout', 'query_mrt', 'query_interval', 'last_member_qrt', 'last_member_query_count', 'group_timeout', 'report_llg', 'immediate_leave'] if state == 'absent': for each in CANNOT_ABSENT: if each in proposed: module.fail_json(msg='only params: oif_prefix, oif_source, ' 'oif_ps, oif_routemap can be used when ' 'state=absent') # delta check for all params except oif_ps delta = dict(set(proposed.items()).difference(existing.items())) if oif_ps: if oif_ps == 'default': delta['oif_ps'] = [] else: delta['oif_ps'] = oif_ps if state == 'present': if delta: command = config_igmp_interface(delta, existing, existing_oif_prefix_source) if command: commands.append(command) elif state == 'default': command = config_default_igmp_interface(existing, delta) if command: commands.append(command) elif state == 'absent': command = None if existing.get('oif_routemap') or existing_oif_prefix_source: command = config_remove_oif(existing, existing_oif_prefix_source) if command: commands.append(command) command = config_default_igmp_interface(existing, delta) if command: commands.append(command) cmds = [] results = {} if commands: commands.insert(0, ['interface {0}'.format(interface)]) cmds = flatten_list(commands) if module.check_mode: module.exit_json(changed=True, commands=cmds) else: load_config(module, cmds) changed = True end_state = get_igmp_interface(module, interface) if 'configure' in cmds: cmds.pop(0) if module.params['restart']: cmd = {'command': 'restart igmp', 'output': 'text'} run_commands(module, cmd) results['proposed'] = proposed results['existing'] = existing_copy results['updates'] = cmds results['changed'] = changed results['warnings'] = warnings results['end_state'] = end_state module.exit_json(**results)
def main(): """entry point for module execution """ argument_spec = dict( # { command: <str>, output: <str>, prompt: <str>, response: <str> } commands=dict(type='list', required=True), wait_for=dict(type='list', aliases=['waitfor']), match=dict(default='all', choices=['any', 'all']), retries=dict(default=10, type='int'), interval=dict(default=1, type='int')) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) result = {'changed': False} warnings = list() check_args(module, warnings) commands = parse_commands(module, warnings) result['warnings'] = warnings wait_for = module.params['wait_for'] or list() try: conditionals = [Conditional(c) for c in wait_for] except AttributeError as exc: module.fail_json(msg=to_native(exc)) retries = module.params['retries'] interval = module.params['interval'] match = module.params['match'] while retries > 0: responses = run_commands(module, commands) for item in list(conditionals): try: if item(responses): if match == 'any': conditionals = list() break conditionals.remove(item) except FailedConditionalError as exc: module.fail_json(msg=to_native(exc)) if not conditionals: break time.sleep(interval) retries -= 1 if conditionals: failed_conditions = [item.raw for item in conditionals] msg = 'One or more conditional statements have not be satisfied' module.fail_json(msg=msg, failed_conditions=failed_conditions) result.update({'stdout': responses, 'stdout_lines': to_lines(responses)}) module.exit_json(**result)
def check_declarative_intent_params(module, want): failed_conditions = [] have_neighbors = None for w in want: want_tx_rate = w.get('tx_rate') want_rx_rate = w.get('rx_rate') want_neighbors = w.get('neighbors') time.sleep(module.params['delay']) if w['interface_type']: return cmd = [{'command': 'show interface {0}'.format(w['name']), 'output': 'text'}] output = run_commands(module, cmd, check_rc=False) if output: out = output[0] else: out = '' if want_tx_rate: match = re.search(r'output rate (\d+)', out, re.M) have_tx_rate = None if match: have_tx_rate = match.group(1) if have_tx_rate is None or not conditional(want_tx_rate, have_tx_rate.strip(), cast=int): failed_conditions.append('tx_rate ' + want_tx_rate) if want_rx_rate: match = re.search(r'input rate (\d+)', out, re.M) have_rx_rate = None if match: have_rx_rate = match.group(1) if have_rx_rate is None or not conditional(want_rx_rate, have_rx_rate.strip(), cast=int): failed_conditions.append('rx_rate ' + want_rx_rate) if want_neighbors: have_host = [] have_port = [] if have_neighbors is None: cmd = [{'command': 'show lldp neighbors interface {0} detail'.format(w['name']), 'output': 'text'}] output = run_commands(module, cmd, check_rc=False) if output: have_neighbors = output[0] else: have_neighbors = '' if have_neighbors and 'Total entries displayed: 0' not in have_neighbors: for line in have_neighbors.strip().split('\n'): if line.startswith('Port Description'): have_port.append(line.split(': ')[1]) if line.startswith('System Name'): have_host.append(line.split(': ')[1]) for item in want_neighbors: host = item.get('host') port = item.get('port') if host and host not in have_host: failed_conditions.append('host ' + host) if port and port not in have_port: failed_conditions.append('port ' + port) return failed_conditions
def get_maintenance_timeout(module): command = {'command': 'show maintenance timeout', 'output': 'text'} body = run_commands(module, [command])[0] timeout = body.split()[4] return timeout
def execute_show_command(command, module, check_rc=True): command += ' | json' cmds = [command] body = run_commands(module, cmds, check_rc=check_rc) return body
def execute_show_command(command, module): command += ' | json' cmds = [command] body = run_commands(module, cmds) return body
def map_config_to_obj(module): obj = [] data = get_config(module, flags=[' all | section logging']) for line in data.split('\n'): if re.search(r'no (\S+)', line, re.M): state = 'absent' else: state = 'present' match = re.search(r'logging (\S+)', line, re.M) if state == 'present' and match: event_status = None name = None dest_level = None dest = None facility = None remote_server = None facility_link_status = None file_size = None facility_level = None if match.group(1) in DEST_GROUP: dest = match.group(1) name = parse_name(line, dest) remote_server = parse_remote_server(line, dest) dest_level = parse_dest_level(line, dest, name) if dest == 'server': facility = parse_facility(line) facility_level = parse_facility_level(line, facility, dest) if dest == 'logfile': file_size = parse_file_size(line, name, dest_level) elif match.group(1) == 'level': match_facility = re.search(r'logging level (\S+)', line, re.M) facility = match_facility.group(1) level = parse_facility_level(line, facility, dest) if level.isdigit(): facility_level = level else: facility_link_status = parse_facility_link_status( line, facility, level) elif match.group(1) == 'event' and state == 'present': event = parse_event(line) if event: status = parse_event_status(line, event) if status: event_status = event + '-' + status else: continue else: pass obj.append({ 'dest': dest, 'remote_server': remote_server, 'use_vrf': parse_use_vrf(line, dest), 'name': name, 'facility': facility, 'dest_level': dest_level, 'facility_level': facility_level, 'interface': parse_interface(line), 'facility_link_status': facility_link_status, 'event': event_status, 'file_size': file_size, 'message': parse_message(line), 'timestamp': parse_timestamp(line) }) cmd = [{ 'command': 'show logging | section enabled | section console', 'output': 'text' }, { 'command': 'show logging | section enabled | section monitor', 'output': 'text' }] default_data = run_commands(module, cmd) for line in default_data: flag = False match = re.search( r'Logging (\w+):(?:\s+) (?:\w+) (?:\W)Severity: (\w+)', str(line), re.M) if match: if match.group(1) == 'console' and match.group(2) == 'critical': dest_level = '2' flag = True elif match.group(1) == 'monitor' and match.group( 2) == 'notifications': dest_level = '5' flag = True if flag: obj.append({ 'dest': match.group(1), 'remote_server': None, 'name': None, 'facility': None, 'dest_level': dest_level, 'facility_level': None, 'use_vrf': None, 'interface': None, 'facility_link_status': None, 'event': None, 'file_size': None, 'message': None, 'timestamp': None }) return obj
def get_current(module): output = run_commands(module, {'command': 'show running-config', 'output': 'text'}) return { 'flush_routes': 'ip igmp flush-routes' in output[0], 'enforce_rtr_alert': 'ip igmp enforce-router-alert' in output[0] }
def get_reset_reasons(module): command = {'command': 'show maintenance on-reload reset-reasons', 'output': 'text'} body = run_commands(module, [command])[0] return body
def verify_remote_file_exists(module, dst, file_system='bootflash:'): command = 'dir {0}/{1}'.format(file_system, dst) body = run_commands(module, {'command': command, 'output': 'text'})[0] if 'No such file' in body: return 0 return body.split()[0].strip()
def main(): """ main entry point for module execution """ argument_spec = dict( src=dict(type='path'), replace_src=dict(), lines=dict(aliases=['commands'], type='list'), parents=dict(type='list'), before=dict(type='list'), after=dict(type='list'), match=dict(default='line', choices=['line', 'strict', 'exact', 'none']), replace=dict(default='line', choices=['line', 'block', 'config']), running_config=dict(aliases=['config']), intended_config=dict(), defaults=dict(type='bool', default=False), backup=dict(type='bool', default=False), save_when=dict(choices=['always', 'never', 'modified'], default='never'), diff_against=dict(choices=['running', 'startup', 'intended']), diff_ignore_lines=dict(type='list'), # save is deprecated as of ans2.4, use save_when instead save=dict(default=False, type='bool', removed_in_version='2.4'), # force argument deprecated in ans2.2 force=dict(default=False, type='bool', removed_in_version='2.2')) argument_spec.update(nxos_argument_spec) mutually_exclusive = [('lines', 'src', 'replace_src'), ('parents', 'src'), ('save', 'save_when')] required_if = [('match', 'strict', ['lines']), ('match', 'exact', ['lines']), ('replace', 'block', ['lines']), ('replace', 'config', ['replace_src']), ('diff_against', 'intended', ['intended_config'])] module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, required_if=required_if, supports_check_mode=True) warnings = list() nxos_check_args(module, warnings) result = {'changed': False, 'warnings': warnings} config = None try: info = get_capabilities(module) api = info.get('network_api', 'nxapi') device_info = info.get('device_info', {}) os_platform = device_info.get('network_os_platform', '') except ConnectionError: api = '' os_platform = '' if api == 'cliconf' and module.params['replace'] == 'config': if '9K' not in os_platform: module.fail_json( msg= 'replace: config is supported only on Nexus 9K series switches' ) if module.params['replace_src']: if module.params['replace'] != 'config': module.fail_json( msg='replace: config is required with replace_src') if module.params['backup'] or (module._diff and module.params['diff_against'] == 'running'): contents = get_config(module) config = NetworkConfig(indent=2, contents=contents) if module.params['backup']: result['__backup__'] = contents if any((module.params['src'], module.params['lines'], module.params['replace_src'])): match = module.params['match'] replace = module.params['replace'] candidate = get_candidate(module) if match != 'none' and replace != 'config': config = get_running_config(module, config) path = module.params['parents'] configobjs = candidate.difference(config, match=match, replace=replace, path=path) else: configobjs = candidate.items if configobjs: commands = dumps(configobjs, 'commands').split('\n') if module.params['before']: commands[:0] = module.params['before'] if module.params['after']: commands.extend(module.params['after']) result['commands'] = commands result['updates'] = commands if not module.check_mode: load_config(module, commands) result['changed'] = True running_config = None startup_config = None diff_ignore_lines = module.params['diff_ignore_lines'] if module.params['save']: module.params['save_when'] = 'always' if module.params['save_when'] != 'never': output = execute_show_commands( module, ['show running-config', 'show startup-config']) running_config = NetworkConfig(indent=1, contents=output[0], ignore_lines=diff_ignore_lines) startup_config = NetworkConfig(indent=1, contents=output[1], ignore_lines=diff_ignore_lines) if running_config.sha1 != startup_config.sha1 or module.params[ 'save_when'] == 'always': result['changed'] = True if not module.check_mode: cmd = { 'command': 'copy running-config startup-config', 'output': 'text' } run_commands(module, [cmd]) else: module.warn( 'Skipping command `copy running-config startup-config` ' 'due to check_mode. Configuration not copied to ' 'non-volatile storage') if module._diff: if not running_config: output = execute_show_commands(module, 'show running-config') contents = output[0] else: contents = running_config.config_text # recreate the object in order to process diff_ignore_lines running_config = NetworkConfig(indent=1, contents=contents, ignore_lines=diff_ignore_lines) if module.params['diff_against'] == 'running': if module.check_mode: module.warn( "unable to perform diff against running-config due to check mode" ) contents = None else: contents = config.config_text elif module.params['diff_against'] == 'startup': if not startup_config: output = execute_show_commands(module, 'show startup-config') contents = output[0] else: contents = output[0] contents = startup_config.config_text elif module.params['diff_against'] == 'intended': contents = module.params['intended_config'] if contents is not None: base_config = NetworkConfig(indent=1, contents=contents, ignore_lines=diff_ignore_lines) if running_config.sha1 != base_config.sha1: if module.params['diff_against'] == 'intended': before = running_config after = base_config elif module.params['diff_against'] in ('startup', 'running'): before = base_config after = running_config result.update({ 'changed': True, 'diff': { 'before': str(before), 'after': str(after) } }) module.exit_json(**result)
def main(): argument_spec = dict(group=dict(required=True, type='str'), interface=dict(required=True), version=dict(choices=['1', '2'], default='2', required=False), priority=dict(type='str', required=False), preempt=dict(type='str', choices=['disabled', 'enabled'], required=False), vip=dict(type='str', required=False), auth_type=dict(choices=['text', 'md5'], required=False), auth_string=dict(type='str', required=False), state=dict(choices=['absent', 'present'], required=False, default='present')) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() results = dict(changed=False, warnings=warnings) interface = module.params['interface'].lower() group = module.params['group'] version = module.params['version'] state = module.params['state'] priority = module.params['priority'] preempt = module.params['preempt'] vip = module.params['vip'] auth_type = module.params['auth_type'] auth_string = module.params['auth_string'] device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if state == 'present' and not vip: module.fail_json(msg='the "vip" param is required when state=present') for param in ['group', 'priority']: if module.params[param] is not None: validate_params(param, module) intf_type = get_interface_type(interface) if (intf_type != 'ethernet' and network_api == 'cliconf'): if is_default(interface, module) == 'DNE': module.fail_json(msg='That interface does not exist yet. Create ' 'it first.', interface=interface) if intf_type == 'loopback': module.fail_json(msg="Loopback interfaces don't support HSRP.", interface=interface) mode = get_interface_mode(interface, intf_type, module) if mode == 'layer2': module.fail_json(msg='That interface is a layer2 port.\nMake it ' 'a layer 3 port first.', interface=interface) if auth_type or auth_string: if not (auth_type and auth_string): module.fail_json(msg='When using auth parameters, you need BOTH ' 'auth_type AND auth_string.') args = dict(group=group, version=version, priority=priority, preempt=preempt, vip=vip, auth_type=auth_type, auth_string=auth_string) proposed = dict((k, v) for k, v in args.items() if v is not None) existing = get_hsrp_group(group, interface, module) # This will enforce better practice with md5 and hsrp version. if proposed.get('auth_type', None) == 'md5': if proposed['version'] == '1': module.fail_json(msg="It's recommended to use HSRP v2 " "when auth_type=md5") elif not proposed.get('auth_type', None) and existing: if (proposed['version'] == '1' and existing['auth_type'] == 'md5'): module.fail_json(msg="Existing auth_type is md5. It's recommended " "to use HSRP v2 when using md5") commands = [] if state == 'present': delta = dict(set(proposed.items()).difference(existing.items())) if delta: command = get_commands_config_hsrp(delta, interface, args) commands.extend(command) elif state == 'absent': if existing: command = get_commands_remove_hsrp(group, interface) commands.extend(command) if commands: if module.check_mode: module.exit_json(**results) else: load_config(module, commands) # validate IP if network_api == 'cliconf' and state == 'present': commands.insert(0, 'config t') body = run_commands(module, commands) validate_config(body, vip, module) results['changed'] = True if 'configure' in commands: commands.pop(0) results['commands'] = commands module.exit_json(**results)
def get_vpc(module): body = run_commands(module, ['show vpc | json'])[0] domain = str(body['vpc-domain-id']) auto_recovery = 'enabled' in str(body['vpc-auto-recovery-status']).lower() vpc = {} if domain != 'not configured': delay_restore = None pkl_src = None role_priority = '32667' system_priority = None pkl_dest = None pkl_vrf = None peer_gw = False run = get_config(module, flags=['vpc']) if run: vpc_list = run.split('\n') for each in vpc_list: if 'delay restore' in each: line = each.split() if len(line) == 3: delay_restore = line[-1] if 'peer-keepalive destination' in each: line = each.split() pkl_dest = line[2] for word in line: if 'source' in word: index = line.index(word) pkl_src = line[index + 1] if 'role priority' in each: line = each.split() role_priority = line[-1] if 'system-priority' in each: line = each.split() system_priority = line[-1] if 'peer-gateway' in each: peer_gw = True body = run_commands(module, ['show vpc peer-keepalive | json'])[0] if body: pkl_dest = body['vpc-keepalive-dest'] if 'N/A' in pkl_dest: pkl_dest = None elif len(pkl_dest) == 2: pkl_dest = pkl_dest[0] pkl_vrf = str(body['vpc-keepalive-vrf']) vpc['domain'] = domain vpc['auto_recovery'] = auto_recovery vpc['delay_restore'] = delay_restore vpc['pkl_src'] = pkl_src vpc['role_priority'] = role_priority vpc['system_priority'] = system_priority vpc['pkl_dest'] = pkl_dest vpc['pkl_vrf'] = pkl_vrf vpc['peer_gw'] = peer_gw return vpc
def remote_file_exists(module, dst, file_system='bootflash:'): command = 'dir {0}/{1}'.format(file_system, dst) body = run_commands(module, {'command': command, 'output': 'text'})[0] if 'No such file' in body: return False return True