def execute_show_command(command, module, command_type='cli_show_ascii'): cmds = [command] if module.params['transport'] == 'cli': body = run_commands(module, cmds) elif module.params['transport'] == 'nxapi': body = run_commands(module, cmds) return body
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'): if module.params['transport'] == 'cli': command += ' | json' cmds = [command] body = run_commands(module, cmds) elif module.params['transport'] == 'nxapi': cmds = [command] body = run_commands(module, cmds) return body
def execute_show_command(command, module): if module.params['transport'] == 'cli': if 'show port-channel summary' in command: command += ' | json' cmds = [command] body = run_commands(module, cmds) elif module.params['transport'] == 'nxapi': cmds = [command] body = run_commands(module, cmds) return body
def execute_show_command(command, module, command_type='cli_show'): if module.params['transport'] == 'cli': if 'show run' not in command: command += ' | json' cmds = [command] body = run_commands(module, cmds) elif module.params['transport'] == 'nxapi': cmds = {'command': command, 'output': 'text'} 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'), include_defaults=dict(default=False), config=dict(), save=dict(type='bool', default=False) ) 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': if desired['flush_routes'] and not current['flush_routes']: commands.append('ip igmp flush-routes') if desired['enforce_rtr_alert'] and not current['enforce_rtr_alert']: commands.append('ip igmp enforce-router-alert') 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']: run_commands(module, 'restart igmp') module.exit_json(**result)
def get_available_features(feature, module): available_features = {} feature_regex = '(?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 execute_show_command(command, module): cmds = [{ 'command': command, 'output': 'text', }] return run_commands(module, cmds)
def execute_show_command(command, module): command = { 'command': command, 'output': 'text', } return run_commands(module, [command])
def execute_show_command(command, module): command = { 'command': command, 'output': 'json', } return run_commands(module, command)
def execute_show_command(command, module, command_type='cli_show'): command = { 'command': command, 'output': 'text', } return run_commands(module, command)
def get_flash_size(module): command = 'dir {}'.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, text=False): command = { 'command': command, 'output': 'json', } if text: command['output'] = 'text' return run_commands(module, command)
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): if 'show run' not in command: output = 'json' else: output = 'text' cmds = [{ 'command': command, 'output': output, }] return run_commands(module, cmds)[0]
def run(self, command, output=None): command_string = command if output: 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 map_config_to_obj(module): output = run_commands(module, ['show banner %s' % module.params['banner']])[0] if isinstance(output, dict): output = list(output.values())[0] obj = {'banner': module.params['banner'], 'state': 'absent'} if output: obj['text'] = output obj['state'] = 'present' return obj
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 get_list_of_vlans(module): body = run_commands(module, ['show vlan | json'])[0] vlan_list = [] vlan_table = body.get('TABLE_vlanbrief')['ROW_vlanbrief'] if isinstance(vlan_table, list): for vlan in vlan_table: vlan_list.append(str(vlan['vlanshowbr-vlanid-utf'])) else: vlan_list.append('1') return vlan_list
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 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 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_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 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("^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 get_portchannel_list(module): portchannels = [] pc_list = [] try: body = run_commands(module, ['show port-channel summary | json'])[0] pc_list = body['TABLE_channel']['ROW_channel'] except (KeyError, AttributeError, TypeError): return portchannels if pc_list: if isinstance(pc_list, dict): pc_list = [pc_list] for pc in pc_list: portchannels.append(pc['group']) return portchannels
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_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 execute_show_command(command, module): command += ' | json' cmds = [command] body = run_commands(module, cmds) return body
def checkpoint(filename, module): commands = ['terminal dont-ask', 'checkpoint file %s' % filename] run_commands(module, commands)
def rollback(filename, module): commands = ['rollback running-config file %s' % filename] run_commands(module, commands)
def rollback(filename, module): commands = [{ 'command': 'rollback running-config file %s' % filename, 'output': 'text', }] run_commands(module, commands)
def main(): """ main entry point for module execution """ argument_spec = dict( src=dict(type='path'), 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']), 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'), ('save', 'save_when')] required_if = [('match', 'strict', ['lines']), ('match', 'exact', ['lines']), ('replace', 'block', ['lines']), ('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 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'])): match = module.params['match'] replace = module.params['replace'] candidate = get_candidate(module) if match != 'none': 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 = run_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 = run_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 = run_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: result.update({ 'changed': True, 'diff': { 'before': str(base_config), 'after': str(running_config) } }) module.exit_json(**result)
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=['section vpc']) if run: vpc_list = run.split('\n') for each in vpc_list: if 'delay restore' in each: line = each.split() if len(line) == 5: 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 execute_show_command(command, module, text=False): if text is False: command += ' | json' cmds = [command] return run_commands(module, cmds)
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 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
def reboot(module): cmds = [ {'command': 'terminal-dont-ask'}, {'command': 'reload', 'output': 'text'} ] run_commands(module, cmds)
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() check_args(module, warnings) 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'] transport = module.params['transport'] 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 transport == 'cli'): 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 transport == 'cli': 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 execute_show_command(command, module): if module.params['transport'] == 'cli': command += ' | json' cmds = [command] body = run_commands(module, cmds) return body
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: exc = get_exception() module.fail_json(msg=str(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: exc = get_exception() module.fail_json(msg=str(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 populate(self): self.responses = run_commands(self.module, list(self.COMMANDS))