def checkpoint(filename, module):
    commands = [{
        'command': 'terminal dont-ask',
        'output': 'text',
    }, {
        'command': 'checkpoint file %s' % filename,
        'output': 'text',
    }]
    run_commands(module, commands)
def save_config(module, result):
    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')
def get_vpc(module):
    body = run_commands(module, ['show vpc | json'])[0]
    if body:
        domain = str(body['vpc-domain-id'])
    else:
        body = run_commands(module, ['show run vpc | inc domain'])[0]
        if body:
            domain = body.split()[2]
        else:
            domain = 'not configured'

    vpc = {}
    if domain != 'not configured':
        run = get_config(module, flags=['vpc all'])
        if run:
            vpc['domain'] = domain
            for key in PARAM_TO_DEFAULT_KEYMAP.keys():
                vpc[key] = PARAM_TO_DEFAULT_KEYMAP.get(key)
            vpc['auto_recovery'] = get_auto_recovery_default(module)
            vpc_list = run.split('\n')
            for each in vpc_list:
                if 'role priority' in each:
                    line = each.split()
                    vpc['role_priority'] = line[-1]
                if 'system-priority' in each:
                    line = each.split()
                    vpc['system_priority'] = line[-1]
                if re.search(r'delay restore \d+', each):
                    line = each.split()
                    vpc['delay_restore'] = line[-1]
                if 'delay restore interface-vlan' in each:
                    line = each.split()
                    vpc['delay_restore_interface_vlan'] = line[-1]
                if 'delay restore orphan-port' in each:
                    line = each.split()
                    vpc['delay_restore_orphan_port'] = line[-1]
                if 'auto-recovery' in each:
                    vpc['auto_recovery'] = False if 'no ' in each else True
                    line = each.split()
                    vpc['auto_recovery_reload_delay'] = line[-1]
                if 'peer-gateway' in each:
                    vpc['peer_gw'] = False if 'no ' in each else True
                if 'peer-keepalive destination' in each:
                    # destination is reqd; src & vrf are optional
                    m = re.search(
                        r'destination (?P<pkl_dest>[\d.]+)'
                        r'(?:.* source (?P<pkl_src>[\d.]+))*'
                        r'(?:.* vrf (?P<pkl_vrf>\S+))*', each)
                    if m:
                        for pkl in m.groupdict().keys():
                            if m.group(pkl):
                                vpc[pkl] = m.group(pkl)
    return vpc
Example #4
0
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 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()

    current = get_current(module)
    desired = get_desired(module)

    state = module.params['state']

    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, output='text'):
    cmds = [{
        'command': command,
        'output': output,
    }]

    return run_commands(module, cmds)
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_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 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 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
Example #12
0
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)
Example #13
0
def execute_show_command(command, module, output='text'):
    command = {
        'command': command,
        'output': output,
    }

    return run_commands(module, [command])
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 get_reset_reasons(module):
    command = {
        'command': 'show maintenance on-reload reset-reasons',
        'output': 'text'
    }
    body = run_commands(module, [command])[0]
    return body
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)
Example #18
0
def execute_show_command(command, module, output='json'):
    cmds = [{
        'command': command,
        'output': output,
    }]
    body = run_commands(module, cmds)
    return body
Example #19
0
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)

    warnings = list()
    result = {'changed': False, 'warnings': warnings}
    commands = parse_commands(module, 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_text(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_text(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 been satisfied'
        module.fail_json(msg=msg, failed_conditions=failed_conditions)

    result.update({
        'stdout': responses,
        'stdout_lines': list(to_lines(responses)),
    })

    module.exit_json(**result)
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, command_type='cli_show'):
    output = 'text'
    commands = [{
        'command': command,
        'output': output,
    }]
    return run_commands(module, commands)
def get_system_mode(module):
    command = {'command': 'show system mode', 'output': 'text'}
    body = run_commands(module, [command])[0]
    if body and 'normal' in body.lower():
        mode = 'normal'
    else:
        mode = 'maintenance'
    return mode
def execute_show_command(module, command):
    format = 'text'
    cmds = [{
        'command': command,
        'output': format,
    }]
    output = run_commands(module, cmds)
    return output
Example #24
0
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_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 execute_show_commands(module, commands, output='text'):
    cmds = []
    for command in to_list(commands):
        cmd = {
            'command': command,
            'output': output,
        }
        cmds.append(cmd)
    body = run_commands(module, cmds)
    return body
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
Example #28
0
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]
Example #29
0
 def run(self, command, output='text'):
     command_string = command
     command = {'command': command, 'output': output}
     resp = run_commands(self.module, [command], check_rc='retry_json')
     try:
         return resp[0]
     except IndexError:
         self.warnings.append(
             'command %s failed, facts for this command will not be populated'
             % command_string)
         return None
def get_configured_track(module, ctrack):
    check_track = '{0}'.format(ctrack)
    track_exists = False
    command = 'show track'
    try:
        body = run_commands(module, {'command': command, 'output': 'text'})
        match = re.findall(r'Track\s+(\d+)', body[0])
    except IndexError:
        return None
    if check_track in match:
        track_exists = True
    return track_exists