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')
Beispiel #2
0
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')
Beispiel #3
0
def validate_vrf(value, module):
    out = run_commands(module, ['show vrf'])
    configured_vrfs = re.findall(r'^\s+(\w+)(?=\s)', out[0], re.M)
    configured_vrfs.append('default')
    if value not in configured_vrfs:
        module.fail_json(msg='vrf `%s` is not configured on the system' %
                         value)
Beispiel #4
0
def map_config_to_obj(module):
    objs = []
    output = run_commands(module, ['show vrf'])
    lines = output[0].strip().splitlines()[2:]

    for l in lines:
        if not l:
            continue

        splitted_line = re.split(r'\s{2,}', l.strip())

        if len(splitted_line) == 1:
            continue
        else:
            obj = {}
            obj['name'] = splitted_line[0]
            obj['rd'] = splitted_line[1]
            obj['interfaces'] = None

            if len(splitted_line) > 4:
                obj['interfaces'] = []

                for i in splitted_line[4].split(','):
                    obj['interfaces'].append(i.strip())

            objs.append(obj)

    return objs
def map_config_to_obj(module):
    config = get_config(module, flags=['| section interface'])
    configobj = NetworkConfig(indent=3, contents=config)

    match = re.findall(r'^interface (\S+)', config, re.M)
    if not match:
        return list()

    instances = list()

    for item in set(match):
        command = 'sh int {0} switchport | include Switchport'
        switchport_cfg = run_commands(module, command.format(item))[0].split(':')[1].strip()
        if switchport_cfg == 'Enabled':
            state = 'present'
        else:
            state = 'absent'

        obj = {
            'name': item.lower(),
            'state': state,
        }

        obj['access_vlan'] = parse_config_argument(configobj, item, 'switchport access vlan')
        obj['native_vlan'] = parse_config_argument(configobj, item, 'switchport trunk native vlan')
        obj['trunk_allowed_vlans'] = parse_config_argument(configobj, item, 'switchport trunk allowed vlan')
        if obj['access_vlan']:
            obj['mode'] = 'access'
        else:
            obj['mode'] = 'trunk'

        instances.append(obj)

    return instances
Beispiel #6
0
def verify_state(updates, module):
    want, have = updates

    invalid_state = [('http', 'httpServer'), ('https', 'httpsServer'),
                     ('local_http', 'localHttpServer'),
                     ('socket', 'unixSocketServer')]

    timeout = module.params['timeout'] or 30
    state = module.params['state']

    while invalid_state:
        out = run_commands(module,
                           ['show management api http-commands | json'])
        for index, item in enumerate(invalid_state):
            want_key, eapi_key = item
            if want[want_key] is not None:
                if want[want_key] == out[0][eapi_key]['running']:
                    del invalid_state[index]
            elif state == 'stopped':
                if not out[0][eapi_key]['running']:
                    del invalid_state[index]
            else:
                del invalid_state[index]
        time.sleep(1)
        timeout -= 1
        if timeout == 0:
            module.fail_json(
                msg='timeout expired before eapi running state changed')
Beispiel #7
0
def verify_state(updates, module):
    want, have = updates

    invalid_state = [('http', 'httpServer'),
                     ('https', 'httpsServer'),
                     ('local_http', 'localHttpServer'),
                     ('socket', 'unixSocketServer')]

    timeout = module.params['timeout'] or 30
    state = module.params['state']

    while invalid_state:
        out = run_commands(module, ['show management api http-commands | json'])
        for index, item in enumerate(invalid_state):
            want_key, eapi_key = item
            if want[want_key] is not None:
                if want[want_key] == out[0][eapi_key]['running']:
                    del invalid_state[index]
            elif state == 'stopped':
                if not out[0][eapi_key]['running']:
                    del invalid_state[index]
            else:
                del invalid_state[index]
        time.sleep(1)
        timeout -= 1
        if timeout == 0:
            module.fail_json(msg='timeout expired before eapi running state changed')
def map_config_to_obj(module):
    config = get_config(module, flags=['| section interface'])
    configobj = NetworkConfig(indent=3, contents=config)

    match = re.findall(r'^interface (\S+)', config, re.M)
    if not match:
        return list()

    instances = list()

    for item in set(match):
        command = {'command': 'show interfaces {0} switchport | include Switchport'.format(item),
                   'output': 'text'}
        switchport_cfg = run_commands(module, command)[0].split(':')[1].strip()
        if switchport_cfg == 'Enabled':
            state = 'present'
        else:
            state = 'absent'

        obj = {
            'name': item.lower(),
            'state': state,
        }

        obj['access_vlan'] = parse_config_argument(configobj, item, 'switchport access vlan')
        obj['native_vlan'] = parse_config_argument(configobj, item, 'switchport trunk native vlan')
        obj['trunk_allowed_vlans'] = parse_config_argument(configobj, item, 'switchport trunk allowed vlan')
        if obj['access_vlan']:
            obj['mode'] = 'access'
        else:
            obj['mode'] = 'trunk'

        instances.append(obj)

    return instances
def main():
    """entry point for module execution
    """
    argument_spec = dict(
        commands=dict(type='list', required=True),

        wait_for=dict(type='list', aliases=['waitfor']),
        match=dict(default='all', choices=['all', 'any']),

        retries=dict(default=10, type='int'),
        interval=dict(default=1, type='int')
    )

    argument_spec.update(eos_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):
            if item(responses):
                if match == 'any':
                    conditionals = list()
                    break
                conditionals.remove(item)

        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)
Beispiel #10
0
def has_lldp(module):
    output = run_commands(module, ['show lldp'])

    is_lldp_enable = False
    if len(output) > 0 and "LLDP is not enabled" not in output[0]:
        is_lldp_enable = True

    return is_lldp_enable
Beispiel #11
0
def collect_facts(module, result):
    out = run_commands(module, ['show management api http-commands | json'])
    facts = dict(eos_eapi_urls=dict())
    for each in out[0]['urls']:
        intf, url = each.split(' : ')
        key = str(intf).strip()
        if key not in facts['eos_eapi_urls']:
            facts['eos_eapi_urls'][key] = list()
        facts['eos_eapi_urls'][key].append(str(url).strip())
    result['ansible_facts'] = facts
Beispiel #12
0
def collect_facts(module, result):
    out = run_commands(module, ['show management api http-commands | json'])
    facts = dict(eos_eapi_urls=dict())
    for each in out[0]['urls']:
        intf, url = each.split(' : ')
        key = str(intf).strip()
        if key not in facts['eos_eapi_urls']:
            facts['eos_eapi_urls'][key] = list()
        facts['eos_eapi_urls'][key].append(str(url).strip())
    result['ansible_facts'] = facts
Beispiel #13
0
def map_config_to_obj(module):
    out = run_commands(module, ['show management api http-commands | json'])
    return {
        'http': out[0]['httpServer']['configured'],
        'http_port': out[0]['httpServer']['port'],
        'https': out[0]['httpsServer']['configured'],
        'https_port': out[0]['httpsServer']['port'],
        'local_http': out[0]['localHttpServer']['configured'],
        'local_http_port': out[0]['localHttpServer']['port'],
        'socket': out[0]['unixSocketServer']['configured'],
        'vrf': out[0]['vrf'],
        'state': parse_state(out)
    }
Beispiel #14
0
def map_config_to_obj(module):
    out = run_commands(module, ['show management api http-commands | json'])
    return {
        'http': out[0]['httpServer']['configured'],
        'http_port': out[0]['httpServer']['port'],
        'https': out[0]['httpsServer']['configured'],
        'https_port': out[0]['httpsServer']['port'],
        'local_http': out[0]['localHttpServer']['configured'],
        'local_http_port': out[0]['localHttpServer']['port'],
        'socket': out[0]['unixSocketServer']['configured'],
        'vrf': out[0]['vrf'],
        'state': parse_state(out)
    }
Beispiel #15
0
def validate_vrf(value, module):
    out = run_commands(module, ['show vrf'])
    configured_vrfs = []
    lines = out[0].strip().splitlines()[3:]
    for l in lines:
        if not l:
            continue
        splitted_line = re.split(r'\s{2,}', l.strip())
        if len(splitted_line) > 2:
            configured_vrfs.append(splitted_line[0])

    configured_vrfs.append('default')
    if value not in configured_vrfs:
        module.fail_json(msg='vrf `%s` is not configured on the system' % value)
Beispiel #16
0
def map_config_to_obj(module, warnings):
    config = get_config(module, flags=['| section interface'])
    configobj = NetworkConfig(indent=3, contents=config)

    match = re.findall(r'^interface (\S+)', config, re.M)
    if not match:
        return list()

    instances = list()

    for item in set(match):
        command = {
            'command':
            'show interfaces {0} switchport | include Switchport'.format(item),
            'output':
            'text'
        }
        command_result = run_commands(module, command, check_rc=False)
        if "Interface does not exist" in command_result[0]:
            warnings.append(
                "Could not gather switchport information for {0}: {1}".format(
                    item, command_result[0]))
            continue
        elif command_result[0] != "":
            switchport_cfg = command_result[0].split(':')[1].strip()

            if switchport_cfg == 'Enabled':
                state = 'present'
            else:
                state = 'absent'

            obj = {
                'name': item.lower(),
                'state': state,
            }

        obj['access_vlan'] = parse_config_argument(configobj, item,
                                                   'switchport access vlan')
        obj['native_vlan'] = parse_config_argument(
            configobj, item, 'switchport trunk native vlan')
        obj['trunk_allowed_vlans'] = parse_config_argument(
            configobj, item, 'switchport trunk allowed vlan')
        if obj['access_vlan']:
            obj['mode'] = 'access'
        else:
            obj['mode'] = 'trunk'

        instances.append(obj)

    return instances
Beispiel #17
0
def validate_vrf(value, module):
    out = run_commands(module, ['show vrf'])
    configured_vrfs = []
    lines = out[0].strip().splitlines()[3:]
    for l in lines:
        if not l:
            continue
        splitted_line = re.split(r'\s{2,}', l.strip())
        if len(splitted_line) > 2:
            configured_vrfs.append(splitted_line[0])

    configured_vrfs.append('default')
    if value not in configured_vrfs:
        module.fail_json(msg='vrf `%s` is not configured on the system' % value)
Beispiel #18
0
def map_config_to_obj(module):
    output = run_commands(module, ['show banner %s' % module.params['banner']])
    obj = {'banner': module.params['banner'], 'state': 'absent'}
    if output:
        if module.params['transport'] == 'eapi':
            # On EAPI we need to extract the banner text from dict key
            # 'loginBanner'
            if module.params['banner'] == 'login':
                banner_response_key = 'loginBanner'
            else:
                banner_response_key = 'motd'
            if isinstance(output[0], dict) and banner_response_key in output[0].keys():
                obj['text'] = output[0]
        else:
            obj['text'] = output[0]
        obj['state'] = 'present'
    return obj
Beispiel #19
0
def map_config_to_obj(module):
    output = run_commands(module, ['show banner %s' % module.params['banner']])
    obj = {'banner': module.params['banner'], 'state': 'absent'}
    if output:
        if module.params['transport'] == 'eapi':
            # On EAPI we need to extract the banner text from dict key
            # 'loginBanner'
            if module.params['banner'] == 'login':
                banner_response_key = 'loginBanner'
            else:
                banner_response_key = 'motd'
            if isinstance(output[0], dict) and banner_response_key in output[0].keys():
                obj['text'] = output[0]
        else:
            obj['text'] = output[0]
        obj['state'] = 'present'
    return obj
Beispiel #20
0
def map_config_to_obj(module):
    objs = []
    output = run_commands(module, ['show vrf'])

    lines = output[0].strip().splitlines()[3:]

    out_len = len(lines)
    index = 0
    while out_len > index:
        line = lines[index]
        if not line:
            continue

        splitted_line = re.split(r'\s{2,}', line.strip())

        if len(splitted_line) == 1:
            index += 1
            continue
        else:
            obj = dict()
            obj['name'] = splitted_line[0]
            obj['rd'] = splitted_line[1]
            obj['interfaces'] = []

            if len(splitted_line) > 4:
                obj['interfaces'] = []
                interfaces = splitted_line[4]
                if interfaces.endswith(','):
                    while interfaces.endswith(','):
                        # gather all comma separated interfaces
                        if out_len <= index:
                            break
                        index += 1
                        line = lines[index]
                        vrf_line = re.split(r'\s{2,}', line.strip())
                        interfaces += vrf_line[-1]

                for i in interfaces.split(','):
                    obj['interfaces'].append(i.strip().lower())
        index += 1
        objs.append(obj)

    return objs
def main():
    """ main entry point for custom module execution
    """
    argument_spec = dict()
    argument_spec.update(eos_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)
    module.params['commands'] = ['show run | include ip route']
    result = dict(changed=False)
    warnings = list()
    check_args(module, warnings)
    commands = parse_commands(module, warnings)
    if warnings:
        restul['warnings'] = warnings
    responses = run_commands(module, commands)
    result['static_routes'] = responses
    result['static_routes_lines'] = to_lines(responses)
    module.exit_json(**result)
Beispiel #22
0
def map_config_to_obj(module):
    objs = []
    output = run_commands(module, ['show vrf'])

    lines = output[0].strip().splitlines()[3:]

    out_len = len(lines)
    index = 0
    while out_len > index:
        line = lines[index]
        if not line:
            continue

        splitted_line = re.split(r'\s{2,}', line.strip())

        if len(splitted_line) == 1:
            index += 1
            continue
        else:
            obj = dict()
            obj['name'] = splitted_line[0]
            obj['rd'] = splitted_line[1]
            obj['interfaces'] = []

            if len(splitted_line) > 4:
                obj['interfaces'] = []
                interfaces = splitted_line[4]
                if interfaces.endswith(','):
                    while interfaces.endswith(','):
                        # gather all comma separated interfaces
                        if out_len <= index:
                            break
                        index += 1
                        line = lines[index]
                        vrf_line = re.split(r'\s{2,}', line.strip())
                        interfaces += vrf_line[-1]

                for i in interfaces.split(','):
                    obj['interfaces'].append(i.strip().lower())
        index += 1
        objs.append(obj)

    return objs
def map_config_to_obj(module):
    objs = []

    try:
        out = run_commands(module, ['show ip route | json'])[0]
    except IndexError:
        out = {}
    if out:
        try:
            vrfs = out['vrfs']['default']['routes']
        except (AttributeError, KeyError, TypeError):
            vrfs = {}
    if vrfs:
        for address in vrfs:
            obj = {}
            obj['address'] = address
            obj['admin_distance'] = vrfs[address].get('preference')
            obj['next_hop'] = vrfs[address].get('vias')[0].get('nexthopAddr')
            objs.append(obj)

    return objs
Beispiel #24
0
def map_config_to_obj(module):
    objs = []
    vlans = run_commands(module, ['show vlan conf | json'])

    for vlan in vlans[0]['vlans']:
        obj = {}
        obj['vlan_id'] = vlan
        obj['name'] = vlans[0]['vlans'][vlan]['name']
        obj['state'] = vlans[0]['vlans'][vlan]['status']
        obj['interfaces'] = []

        interfaces = vlans[0]['vlans'][vlan]

        for interface in interfaces['interfaces']:
            obj['interfaces'].append(interface)

        if obj['state'] == 'suspended':
            obj['state'] = 'suspend'

        objs.append(obj)

    return objs
Beispiel #25
0
def map_config_to_obj(module):
    objs = []
    output = run_commands(module, ['show vlan'])
    lines = output[0].strip().splitlines()[2:]

    for l in lines:
        splitted_line = re.split(r'\s{2,}', l.strip())
        obj = {}
        obj['vlan_id'] = splitted_line[0]
        obj['name'] = splitted_line[1]
        obj['state'] = splitted_line[2]

        if obj['state'] == 'suspended':
            obj['state'] = 'suspend'

        obj['interfaces'] = []
        if len(splitted_line) > 3:

            for i in splitted_line[3].split(','):
                obj['interfaces'].append(i.strip().replace('Et', 'ethernet'))

        objs.append(obj)

    return objs
Beispiel #26
0
    def show(self, sh_cmd):
        cmd = {"command": sh_cmd, "output": "json"}

        result = run_commands(self.module, [cmd])

        return result[0]
Beispiel #27
0
def main():
    """ main entry point for module execution
    """
    backup_spec = dict(filename=dict(), dir_path=dict(type='path'))
    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', 'config']),
        defaults=dict(type='bool', default=False),
        backup=dict(type='bool', default=False),
        backup_options=dict(type='dict', options=backup_spec),
        save_when=dict(choices=['always', 'never', 'modified', 'changed'],
                       default='never'),
        diff_against=dict(
            choices=['startup', 'session', 'intended', 'running'],
            default='session'),
        diff_ignore_lines=dict(type='list'),
        running_config=dict(aliases=['config']),
        intended_config=dict(),
    )

    argument_spec.update(eos_argument_spec)

    mutually_exclusive = [('lines', 'src'), ('parents', 'src')]

    required_if = [('match', 'strict', ['lines']),
                   ('match', 'exact', ['lines']),
                   ('replace', 'block', ['lines']),
                   ('replace', 'config', ['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()
    check_args(module, warnings)

    result = {'changed': False}
    if warnings:
        result['warnings'] = warnings

    diff_ignore_lines = module.params['diff_ignore_lines']
    config = None
    contents = None
    flags = ['all'] if module.params['defaults'] else []
    connection = get_connection(module)

    if module.params['backup'] or (module._diff and
                                   module.params['diff_against'] == 'running'):
        contents = get_config(module, flags=flags)
        config = NetworkConfig(indent=1, 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']
        path = module.params['parents']

        candidate = get_candidate(module)
        running = get_running_config(module, contents, flags=flags)

        try:
            response = connection.get_diff(candidate=candidate,
                                           running=running,
                                           diff_match=match,
                                           diff_ignore_lines=diff_ignore_lines,
                                           path=path,
                                           diff_replace=replace)
        except ConnectionError as exc:
            module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))

        config_diff = response['config_diff']

        if config_diff:
            commands = config_diff.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

            replace = module.params['replace'] == 'config'
            commit = not module.check_mode

            response = load_config(module,
                                   commands,
                                   replace=replace,
                                   commit=commit)

            if 'diff' in response and module.params[
                    'diff_against'] == 'session':
                result['diff'] = {'prepared': response['diff']}

            if 'session' in response:
                result['session'] = response['session']

            result['changed'] = True

    running_config = module.params['running_config']
    startup_config = None

    if module.params['save_when'] == 'always':
        save_config(module, result)
    elif module.params['save_when'] == 'modified':
        output = run_commands(module, [{
            'command': 'show running-config',
            'output': 'text'
        }, {
            'command': 'show startup-config',
            'output': 'text'
        }])

        running_config = NetworkConfig(indent=3,
                                       contents=output[0],
                                       ignore_lines=diff_ignore_lines)
        startup_config = NetworkConfig(indent=3,
                                       contents=output[1],
                                       ignore_lines=diff_ignore_lines)

        if running_config.sha1 != startup_config.sha1:
            save_config(module, result)

    elif module.params['save_when'] == 'changed' and result['changed']:
        save_config(module, result)

    if module._diff:
        if not running_config:
            output = run_commands(module, {
                'command': 'show running-config',
                'output': 'text'
            })
            contents = output[0]
        else:
            contents = running_config

        # recreate the object in order to process diff_ignore_lines
        running_config = NetworkConfig(indent=3,
                                       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, {
                    'command': 'show startup-config',
                    'output': 'text'
                })
                contents = output[0]
            else:
                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=3,
                                        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)
Beispiel #28
0
def check_declarative_intent_params(module, want, result):
    failed_conditions = []
    have_neighbors = None
    for w in want:
        want_state = w.get('state')
        want_tx_rate = w.get('tx_rate')
        want_rx_rate = w.get('rx_rate')
        want_neighbors = w.get('neighbors')

        if want_state not in ('up', 'down') and not want_tx_rate and not want_rx_rate and not want_neighbors:
            continue

        if result['changed']:
            sleep(w['delay'])

        command = {'command': 'show interfaces %s' % w['name'], 'output': 'text'}
        output = run_commands(module, [command])

        if want_state in ('up', 'down'):
            match = re.search(r'%s (\w+)' % 'line protocol is', output[0], re.M)
            have_state = None
            if match:
                have_state = match.group(1)
            if have_state is None or not conditional(want_state, have_state.strip()):
                failed_conditions.append('state ' + 'eq(%s)' % want_state)

        if want_tx_rate:
            match = re.search(r'%s (\d+)' % 'output rate', output[0], 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'%s (\d+)' % 'input rate', output[0], 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:
                command = {'command': 'show lldp neighbors {}'.format(w['name']), 'output': 'text'}
                have_neighbors = run_commands(module, [command])

            if have_neighbors[0]:
                lines = have_neighbors[0].strip().split('\n')
                col = None
                for index, line in enumerate(lines):
                    if re.search(r"^Port\s+Neighbor Device ID\s+Neighbor Port ID\s+TTL", line):
                        col = index
                        break

                if col and col < len(lines) - 1:
                    for items in lines[col + 1:]:
                        value = re.split(r'\s+', items)
                        try:
                            have_port.append(value[2])
                            have_host.append(value[1])
                        except IndexError:
                            pass

            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
Beispiel #29
0
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', 'config']),

        defaults=dict(type='bool', default=False),
        backup=dict(type='bool', default=False),

        save_when=dict(choices=['always', 'never', 'modified', 'changed'], default='never'),

        diff_against=dict(choices=['startup', 'session', 'intended', 'running'], default='session'),
        diff_ignore_lines=dict(type='list'),

        running_config=dict(aliases=['config']),
        intended_config=dict(),

        # save is deprecated as of ans2.4, use save_when instead
        save=dict(default=False, type='bool', removed_in_version='2.8'),

        # force argument deprecated in ans2.2
        force=dict(default=False, type='bool', removed_in_version='2.6')
    )

    argument_spec.update(eos_argument_spec)

    mutually_exclusive = [('lines', 'src'),
                          ('parents', 'src'),
                          ('save', 'save_when')]

    required_if = [('match', 'strict', ['lines']),
                   ('match', 'exact', ['lines']),
                   ('replace', 'block', ['lines']),
                   ('replace', 'config', ['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()
    check_args(module, warnings)

    result = {'changed': False}
    if warnings:
        result['warnings'] = warnings

    config = None

    if module.params['backup'] or (module._diff and module.params['diff_against'] == 'running'):
        contents = get_config(module)
        config = NetworkConfig(indent=3, 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' and replace != 'config':
            config_text = get_running_config(module)
            config = NetworkConfig(indent=3, contents=config_text)
            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

            replace = module.params['replace'] == 'config'
            commit = not module.check_mode

            response = load_config(module, commands, replace=replace, commit=commit)

            if 'diff' in response and module.params['diff_against'] == 'session':
                result['diff'] = {'prepared': response['diff']}

            if 'session' in response:
                result['session'] = response['session']

            result['changed'] = True

    running_config = None
    startup_config = None

    diff_ignore_lines = module.params['diff_ignore_lines']

    if module.params['save_when'] == 'always' or module.params['save']:
        save_config(module, result)
    elif module.params['save_when'] == 'modified':
        output = run_commands(module, [{'command': 'show running-config', 'output': 'text'},
                                       {'command': 'show startup-config', 'output': 'text'}])

        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:
            save_config(module, result)

    elif module.params['save_when'] == 'changed' and result['changed']:
        save_config(module, result)

    if module._diff:
        if not running_config:
            output = run_commands(module, {'command': 'show running-config', 'output': 'text'})
            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, {'command': 'show startup-config', 'output': 'text'})
                contents = output[0]
            else:
                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)
Beispiel #30
0
 def populate(self):
     self.responses = run_commands(self.module, list(self.COMMANDS))
Beispiel #31
0
def main():
    """entry point for module execution
    """
    argument_spec = dict(
        commands=dict(type='list', required=True),

        wait_for=dict(type='list', aliases=['waitfor']),
        match=dict(default='all', choices=['all', 'any']),

        retries=dict(default=10, type='int'),
        interval=dict(default=1, type='int')
    )

    argument_spec.update(eos_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)
    if 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):
            if item(responses):
                if match == 'any':
                    conditionals = list()
                    break
                conditionals.remove(item)

        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({
        'changed': False,
        'stdout': responses,
        'stdout_lines': to_lines(responses)
    })

    module.exit_json(**result)
Beispiel #32
0
 def populate(self):
     self.responses = run_commands(self.module,
                                   list(self.COMMANDS),
                                   check_rc=False)
Beispiel #33
0
 def populate(self):
     self.responses = run_commands(self.module, list(self.COMMANDS))
Beispiel #34
0
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', 'config']),
        defaults=dict(type='bool', default=False),
        backup=dict(type='bool', default=False),
        save_when=dict(choices=['always', 'never', 'modified', 'changed'],
                       default='never'),
        diff_against=dict(
            choices=['startup', 'session', 'intended', 'running'],
            default='session'),
        diff_ignore_lines=dict(type='list'),
        running_config=dict(aliases=['config']),
        intended_config=dict(),

        # save is deprecated as of ans2.4, use save_when instead
        save=dict(default=False, type='bool', removed_in_version='2.8'),

        # force argument deprecated in ans2.2
        force=dict(default=False, type='bool', removed_in_version='2.6'))

    argument_spec.update(eos_argument_spec)

    mutually_exclusive = [('lines', 'src'), ('parents', 'src'),
                          ('save', 'save_when')]

    required_if = [('match', 'strict', ['lines']),
                   ('match', 'exact', ['lines']),
                   ('replace', 'block', ['lines']),
                   ('replace', 'config', ['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()
    check_args(module, warnings)

    result = {'changed': False}
    if warnings:
        result['warnings'] = warnings

    config = None

    if module.params['backup'] or (module._diff and
                                   module.params['diff_against'] == 'running'):
        contents = get_config(module)
        config = NetworkConfig(indent=3, 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' and replace != 'config':
            config_text = get_running_config(module)
            config = NetworkConfig(indent=3, contents=config_text)
            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

            replace = module.params['replace'] == 'config'
            commit = not module.check_mode

            response = load_config(module,
                                   commands,
                                   replace=replace,
                                   commit=commit)

            if 'diff' in response and module.params[
                    'diff_against'] == 'session':
                result['diff'] = {'prepared': response['diff']}

            if 'session' in response:
                result['session'] = response['session']

            result['changed'] = True

    running_config = None
    startup_config = None

    diff_ignore_lines = module.params['diff_ignore_lines']

    if module.params['save_when'] == 'always' or module.params['save']:
        save_config(module, result)
    elif module.params['save_when'] == 'modified':
        output = run_commands(module, [{
            'command': 'show running-config',
            'output': 'text'
        }, {
            'command': 'show startup-config',
            'output': 'text'
        }])

        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:
            save_config(module, result)

    elif module.params['save_when'] == 'changed' and result['changed']:
        save_config(module, result)

    if module._diff:
        if not running_config:
            output = run_commands(module, {
                'command': 'show running-config',
                'output': 'text'
            })
            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, {
                    'command': 'show startup-config',
                    'output': 'text'
                })
                contents = output[0]
            else:
                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)