示例#1
0
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)

            else:
                dest = None

            obj.append({
                "dest": dest,
                "name": parse_name(line, dest),
                "size": parse_size(line, dest),
                "facility": parse_facility(line),
                "level": parse_level(line, dest),
            })

    return obj
示例#2
0
def map_config_to_obj(module):
    data = get_config(module, flags=['section username'])

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

    instances = list()

    for user in set(match):
        regex = r'username %s .+$' % user
        cfg = re.findall(regex, data, re.M)
        cfg = '\n'.join(cfg)
        obj = {
            'name': user,
            'state': 'present',
            'nopassword': '******' in cfg,
            'configured_password': None,
            'sshkey': parse_sshkey(cfg),
            'privilege': parse_privilege(cfg),
            'role': parse_role(cfg)
        }
        instances.append(obj)

    return instances
示例#3
0
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)

            else:
                dest = None

            obj.append({
                'dest': dest,
                'name': parse_name(line, dest),
                'size': parse_size(line, dest),
                'facility': parse_facility(line),
                'level': parse_level(line, dest)
            })

    return obj
示例#4
0
def map_config_to_obj(module):
    data = get_config(module, flags=["section username"])

    match = re.findall(r"^username (\S+)", data, re.M)
    if not match:
        return list()

    instances = list()

    for user in set(match):
        regex = r"username %s .+$" % user
        cfg = re.findall(regex, data, re.M)
        cfg = "\n".join(cfg)
        obj = {
            "name": user,
            "state": "present",
            "nopassword": "******" in cfg,
            "configured_password": None,
            "sshkey": parse_sshkey(cfg),
            "privilege": parse_privilege(cfg),
            "role": parse_role(cfg),
        }
        instances.append(obj)

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

    try:
        out = get_config(module, flags=['| include ip.route'])
    except IndexError:
        out = ''
    if out:
        lines = out.splitlines()
        for line in lines:
            obj = {}
            add_match = re.search(r'ip route ([\d\./]+)', line, re.M)
            if add_match:
                obj['vrf'] = 'default'
                address = add_match.group(1)
                if is_address(address):
                    obj['address'] = address
                hop_match = re.search(
                    r'ip route {0} ([\d\./]+)'.format(address), line, re.M)
                if hop_match:
                    hop = hop_match.group(1)
                    if is_hop(hop):
                        obj['next_hop'] = hop
                    dist_match = re.search(
                        r'ip route {0} {1} (\d+)'.format(address, hop), line,
                        re.M)
                    if dist_match:
                        distance = dist_match.group(1)
                        obj['admin_distance'] = int(distance)
                    else:
                        obj['admin_distance'] = 1

            vrf_match = re.search(r'ip route vrf ([\w]+) ([\d\./]+)', line,
                                  re.M)
            if vrf_match:
                vrf = vrf_match.group(1)
                obj['vrf'] = vrf
                address = vrf_match.group(2)
                if is_address(address):
                    obj['address'] = address
                hop_vrf_match = re.search(
                    r'ip route vrf {0} {1} ([\d\./]+)'.format(vrf, address),
                    line, re.M)
                if hop_vrf_match:
                    hop = hop_vrf_match.group(1)
                    if is_hop(hop):
                        obj['next_hop'] = hop
                    dist_vrf_match = re.search(
                        r'ip route vrf {0} {1} {2} (\d+)'.format(
                            vrf, address, hop), line, re.M)
                    if dist_vrf_match:
                        distance = dist_vrf_match.group(1)
                        obj['admin_distance'] = int(distance)
                    else:
                        obj['admin_distance'] = 1

            objs.append(obj)

    return objs
def has_vrf(module, vrf):
    global _CONFIGURED_VRFS
    if _CONFIGURED_VRFS is not None:
        return vrf in _CONFIGURED_VRFS
    config = get_config(module)
    _CONFIGURED_VRFS = re.findall(r"vrf instance (\S+)", config)
    _CONFIGURED_VRFS.append("default")
    return vrf in _CONFIGURED_VRFS
示例#7
0
def has_vrf(module, vrf):
    global _CONFIGURED_VRFS
    if _CONFIGURED_VRFS is not None:
        return vrf in _CONFIGURED_VRFS
    config = get_config(module)
    _CONFIGURED_VRFS = re.findall(r'vrf definition (\S+)', config)
    _CONFIGURED_VRFS.append('default')
    return vrf in _CONFIGURED_VRFS
示例#8
0
def get_running_config(module, config=None, flags=None):
    contents = module.params["running_config"]
    if not contents:
        if config:
            contents = config
        else:
            contents = get_config(module, flags=flags)
    return contents
示例#9
0
def has_lldp(module):
    config = get_config(module, flags=["| section lldp"])

    is_lldp_enable = False
    if "no lldp run" not in config:
        is_lldp_enable = True

    return is_lldp_enable
示例#10
0
def map_config_to_obj(module):
    config = get_config(module)
    return {
        'hostname': parse_hostname(config),
        'domain_name': parse_domain_name(config),
        'domain_list': re.findall(r'^ip domain-list (\S+)', config, re.M),
        'lookup_source': parse_lookup_source(config),
        'name_servers': parse_name_servers(config)
    }
示例#11
0
def map_config_to_obj(module):
    config = get_config(module)
    return {
        "hostname": parse_hostname(config),
        "domain_name": parse_domain_name(config),
        "domain_list": re.findall(r"^ip domain-list (\S+)", config, re.M),
        "lookup_source": parse_lookup_source(config),
        "name_servers": parse_name_servers(config),
    }
示例#12
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

        if 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,
                "access_vlan":
                parse_config_argument(configobj, item,
                                      "switchport access vlan"),
                "native_vlan":
                parse_config_argument(configobj, item,
                                      "switchport trunk native vlan"),
                "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
示例#13
0
def get_channel(group, module):
    channel = {}
    config = get_config(module, flags=["| section channel-group"])

    for line in config.split("\n"):
        stripped = line.strip()
        match = re.search(r"interface (\S+)", stripped, re.M)

        if match:
            member = match.group(1)
            channel["mode"] = parse_mode(group, member, config)
            channel["members"] = parse_members(group, config)

    return channel
示例#14
0
def get_channel(group, module):
    channel = {}
    config = get_config(module, flags=['| section channel-group'])

    for line in config.split('\n'):
        l = line.strip()
        match = re.search(r'interface (\S+)', l, re.M)

        if match:
            member = match.group(1)
            channel['mode'] = parse_mode(group, member, config)
            channel['members'] = parse_members(group, config)

    return channel
示例#15
0
def map_config_to_obj(module):
    objs = list()
    config = get_config(module, flags=['| section port-channel'])

    for line in config.split('\n'):
        l = line.strip()
        match = re.search(r'interface Port-Channel(\S+)', l, re.M)
        if match:
            obj = {}
            group = match.group(1)
            obj['group'] = group
            obj['min_links'] = parse_min_links(group, config)
            obj.update(get_channel(group, module))
            objs.append(obj)

    return objs
示例#16
0
def map_config_to_obj(module):
    objs = list()
    config = get_config(module, flags=["| section port-channel"])

    for line in config.split("\n"):
        stripped = line.strip()
        match = re.search(r"interface Port-Channel(\S+)", stripped, re.M)
        if match:
            obj = {}
            group = match.group(1)
            obj["group"] = group
            obj["min_links"] = parse_min_links(group, config)
            obj.update(get_channel(group, module))
            objs.append(obj)

    return objs
示例#17
0
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):
        obj = {
            "name": item.lower(),
            "ipv4": parse_config_argument(configobj, item, "ip address"),
            "ipv6": parse_config_argument(configobj, item, "ipv6 address"),
            "state": "present",
        }
        instances.append(obj)

    return instances
示例#18
0
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):
        obj = {
            'name': item.lower(),
            'ipv4': parse_config_argument(configobj, item, 'ip address'),
            'ipv6': parse_config_argument(configobj, item, 'ipv6 address'),
            'state': 'present'
        }
        instances.append(obj)

    return instances
示例#19
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

        if 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,
                'access_vlan': parse_config_argument(configobj, item, 'switchport access vlan'),
                'native_vlan': parse_config_argument(configobj, item, 'switchport trunk native vlan'),
                '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
示例#20
0
def map_config_to_obj(module):
    config = get_config(module)
    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):
        obj = {
            'name': item.lower(),
            'description': parse_config_argument(configobj, item, 'description'),
            'speed': parse_config_argument(configobj, item, 'speed'),
            'mtu': parse_config_argument(configobj, item, 'mtu'),
            'disable': parse_shutdown(configobj, item),
            'state': 'present'
        }
        instances.append(obj)
    return instances
示例#21
0
def map_config_to_obj(module):
    config = get_config(module)
    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):
        obj = {
            "name": item.lower(),
            "description": parse_config_argument(configobj, item,
                                                 "description"),
            "speed": parse_config_argument(configobj, item, "speed"),
            "mtu": parse_config_argument(configobj, item, "mtu"),
            "disable": parse_shutdown(configobj, item),
            "state": "present",
        }
        instances.append(obj)
    return instances
示例#22
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", elements="str"),
        parents=dict(type="list", elements="str"),
        before=dict(type="list", elements="str"),
        after=dict(type="list", elements="str"),
        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", elements="str"),
        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()

    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)

    # Refuse to diff_against: session if sessions are disabled
    if (module.params["diff_against"] == "session"
            and not connection.supports_sessions):
        module.fail_json(
            msg=
            "Cannot diff against sessions when sessions are disabled. Please change diff_against to another value"
        )

    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)

            result["changed"] = True

            if module.params["diff_against"] == "session":
                if "diff" in response:
                    result["diff"] = {"prepared": response["diff"]}
                else:
                    result["changed"] = False

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

    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)
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()

    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)

    # Refuse to diff_against: session if sessions are disabled
    if module.params[
            'diff_against'] == 'session' and not connection.supports_sessions:
        module.fail_json(
            msg=
            "Cannot diff against sessions when sessions are disabled. Please change diff_against to another value"
        )

    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)

            result['changed'] = True

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

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

    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)