Exemple #1
0
def main():
    argument_spec = dict(
        vrf=dict(required=True),
        afi=dict(required=True, choices=['ipv4', 'ipv6']),
        route_target_both_auto_evpn=dict(required=False, type='bool'),
        state=dict(choices=['present', 'absent'], default='present'),
        safi=dict(choices=['unicast', 'multicast'], removed_in_version="2.4"),
    )

    argument_spec.update(nxos_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False, 'warnings': warnings}

    config_text = get_config(module)
    config = NetworkConfig(indent=2, contents=config_text)

    path = ['vrf context %s' % module.params['vrf'],
            'address-family %s unicast' % module.params['afi']]

    try:
        current = config.get_block_config(path)
    except ValueError:
        current = None

    commands = list()
    if current and module.params['state'] == 'absent':
        commands.append('no address-family %s unicast' % module.params['afi'])

    elif module.params['state'] == 'present':

        if current:
            have = 'route-target both auto evpn' in current
            if module.params['route_target_both_auto_evpn'] is not None:
                want = bool(module.params['route_target_both_auto_evpn'])
                if want and not have:
                    commands.append('address-family %s unicast' % module.params['afi'])
                    commands.append('route-target both auto evpn')
                elif have and not want:
                    commands.append('address-family %s unicast' % module.params['afi'])
                    commands.append('no route-target both auto evpn')

        else:
            commands.append('address-family %s unicast' % module.params['afi'])
            if module.params['route_target_both_auto_evpn']:
                commands.append('route-target both auto evpn')

    if commands:
        commands.insert(0, 'vrf context %s' % module.params['vrf'])
        if not module.check_mode:
            load_config(module, commands)
        result['changed'] = True

    result['commands'] = commands

    module.exit_json(**result)
def get_candidate(module):
    candidate = NetworkConfig(indent=1)

    if module.params['src']:
        candidate.load(module.params['src'])
    elif module.params['lines']:
        candidate.add(module.params['lines'])
    return candidate
def get_candidate(module):
    candidate = NetworkConfig(indent=1)
    if module.params['src']:
        candidate.load(module.params['src'])
    elif module.params['lines']:
        parents = module.params['parents'] or list()
        candidate.add(module.params['lines'], parents=parents)
    return candidate
Exemple #4
0
def main():

    argument_spec = dict(
        lines=dict(aliases=['commands'], required=True, type='list'),

        before=dict(type='list'),
        after=dict(type='list'),

        match=dict(default='line', choices=['line', 'strict', 'exact']),
        replace=dict(default='line', choices=['line', 'block']),

        force=dict(default=False, type='bool'),
        config=dict()
    )

    argument_spec.update(asa_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)

    lines = module.params['lines']

    result = {'changed': False}

    candidate = NetworkConfig(indent=1)
    candidate.add(lines)

    acl_name = parse_acl_name(module)

    if not module.params['force']:
        contents = get_acl_config(module, acl_name)
        config = NetworkConfig(indent=1, contents=contents)

        commands = candidate.difference(config)
        commands = dumps(commands, 'commands').split('\n')
        commands = [str(c) for c in commands if c]
    else:
        commands = str(candidate).split('\n')

    if commands:
        if module.params['before']:
            commands[:0] = module.params['before']

        if module.params['after']:
            commands.extend(module.params['after'])

        if not module.check_mode:
            load_config(module, commands)

        result['changed'] = True

    result['updates'] = commands

    module.exit_json(**result)
def get_candidate(module):
    candidate = NetworkConfig(indent=1)
    banners = {}

    if module.params['src']:
        src, banners = extract_banners(module.params['src'])
        candidate.load(src)

    elif module.params['lines']:
        parents = module.params['parents'] or list()
        candidate.add(module.params['lines'], parents=parents)

    return candidate, banners
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        rollback_location=dict(),

        local_max_checkpoints=dict(type='int'),
        remote_max_checkpoints=dict(type='int'),

        rescue_location=dict(),

        state=dict(default='present', choices=['present', 'absent'])
    )

    argument_spec.update(sros_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)

    state = module.params['state']

    result = dict(changed=False)

    commands = list()
    invoke(state, module, commands)

    candidate = NetworkConfig(indent=4, contents='\n'.join(commands))
    config = get_device_config(module)
    configobjs = candidate.difference(config)

    if configobjs:
        # commands = dumps(configobjs, 'lines')
        commands = dumps(configobjs, 'commands')
        commands = sanitize_config(commands.split('\n'))

        result['updates'] = commands
        result['commands'] = commands

        # send the configuration commands to the device and merge
        # them with the current running config
        if not module.check_mode:
            load_config(module, commands)

        result['changed'] = True

    module.exit_json(**result)
def get_candidate(module):
    candidate = NetworkConfig(indent=1)
    if module.params['src']:
        candidate.load(module.params['src'])
    elif module.params['lines']:
        parents = module.params['parents'] or list()
        commands = module.params['lines'][0]
        if (isinstance(commands, dict)) and (isinstance((commands['command']), list)):
            candidate.add(commands['command'], parents=parents)
        elif (isinstance(commands, dict)) and (isinstance((commands['command']), str)):
            candidate.add([commands['command']], parents=parents)
        else:
            candidate.add(module.params['lines'], parents=parents)
    return candidate
Exemple #8
0
def map_config_to_obj(module):
    config = get_config(module)
    configobj = NetworkConfig(indent=2, contents=config)

    vrf_config = {}

    vrfs = re.findall(r'^vrf context (\S+)$', config, re.M)
    for vrf in vrfs:
        config_data = configobj.get_block_config(path=['vrf context %s' % vrf])
        vrf_config[vrf] = config_data

    return {
        'hostname': parse_hostname(config),
        'domain_lookup': 'no ip domain-lookup' not in config,
        'domain_name': parse_domain_name(config, vrf_config),
        'domain_search': parse_domain_search(config, vrf_config),
        'name_servers': parse_name_servers(config, vrf_config, vrfs),
        'system_mtu': parse_system_mtu(config)
    }
Exemple #9
0
def get_sublevel_config(running_config, module):
    contents = list()
    current_config_contents = list()
    running_config = NetworkConfig(contents=running_config, indent=1)
    obj = running_config.get_object(module.params['parents'])
    if obj:
        contents = obj.children
    contents[:0] = module.params['parents']

    indent = 0
    for c in contents:
        if isinstance(c, str):
            current_config_contents.append(c.rjust(len(c) + indent, ' '))
        if isinstance(c, ConfigLine):
            current_config_contents.append(c.raw)
        indent = 1
    sublevel_config = '\n'.join(current_config_contents)

    return sublevel_config
Exemple #10
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)
        if command_result[0] == "% Interface does not exist":
            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
Exemple #11
0
def get_candidate(module):
    candidate = NetworkConfig(indent=1)

    if module.params['src']:
        candidate.load(module.params['src'])
    elif module.params['lines']:
        candidate.add(module.params['lines'])
    candidate = dumps(candidate, 'raw')
    return candidate
Exemple #12
0
def get_candidate(module):
    candidate = NetworkConfig(indent=1)
    if module.params['src']:
        config = conversion_src(module)
        candidate.load(config)
    elif module.params['lines']:
        parents = module.params['parents'] or list()
        candidate.add(module.params['lines'], parents=parents)
    return candidate
Exemple #13
0
def get_candidate(module):
    candidate = NetworkConfig()

    if module.params['src']:
        candidate.load(module.params['src'])
    elif module.params['lines']:
        parents = module.params['parents'] or list()
        candidate.add(module.params['lines'], parents=parents)
    return candidate
    def run(self, terms, variables, **kwargs):

        ret = []

        try:
            want = terms[0]
        except IndexError:
            raise AnsibleError("value of 'want' must be specified")

        try:
            have = kwargs['have']
        except KeyError:
            raise AnsibleError("value of 'have' must be specified")

        match = kwargs.get('match', 'line')
        if match not in MATCH_CHOICES:
            choices_str = ", ".join(MATCH_CHOICES)
            raise AnsibleError("value of match must be one of: %s, got: %s" % (choices_str, match))

        replace = kwargs.get('replace', 'line')
        if replace not in REPLACE_CHOICES:
            choices_str = ", ".join(REPLACE_CHOICES)
            raise AnsibleError("value of replace must be one of: %s, got: %s" % (choices_str, replace))

        indent = int(kwargs.get('indent', 1))
        ignore_lines = kwargs.get('ignore_lines')

        running_obj = NetworkConfig(indent=indent, contents=have, ignore_lines=ignore_lines)
        candidate_obj = NetworkConfig(indent=indent, contents=want, ignore_lines=ignore_lines)

        configobjs = candidate_obj.difference(running_obj, match=match, replace=replace)

        diff = dumps(configobjs, output='commands')
        ret.append(diff)

        return ret
Exemple #15
0
def main():

    argument_spec = dict(
        lines=dict(aliases=['commands'], required=True, type='list'),

        before=dict(type='list'),
        after=dict(type='list'),

        match=dict(default='line', choices=['line', 'strict', 'exact']),
        replace=dict(default='line', choices=['line', 'block']),

        force=dict(default=False, type='bool'),
        config=dict()
    )

    argument_spec.update(asa_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)

    lines = module.params['lines']

    result = {'changed': False}

    candidate = NetworkConfig(indent=1)
    candidate.add(lines)

    acl_name = parse_acl_name(module)

    if not module.params['force']:
        contents = get_acl_config(module, acl_name)
        config = NetworkConfig(indent=1, contents=contents)

        commands = candidate.difference(config)
        commands = dumps(commands, 'commands').split('\n')
        commands = [str(c) for c in commands if c]
    else:
        commands = str(candidate).split('\n')

    if commands:
        if module.params['before']:
            commands[:0] = module.params['before']

        if module.params['after']:
            commands.extend(module.params['after'])

        if not module.check_mode:
            load_config(module, commands)

        result['changed'] = True

    result['updates'] = commands

    module.exit_json(**result)
Exemple #16
0
def get_candidate(module):
    candidate = NetworkConfig(indent=1)
    banners = {}

    if module.params['src']:
        src, banners = extract_banners(module.params['src'])
        candidate.load(src)

    elif module.params['lines']:
        parents = module.params['parents'] or list()
        candidate.add(module.params['lines'], parents=parents)

    return candidate, banners
Exemple #17
0
    def map_config_to_obj(self, config):
        results = []

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

        configobj = NetworkConfig(indent=1, contents=config)

        for intf_name in set(match):
            obj = {'state': 'present', 'name': intf_name}

            # ip addressで始まっている設定コマンドをリスト化する
            # これにはsecondaryも含まれる
            #  ip address 3.3.3.3 255.255.255.0
            #  ip address 33.33.33.33 255.255.255.0 secondary
            cmds = self.parse_config_argument(configobj, intf_name,
                                              'ip address')

            ipv4 = None
            secondary_list = []
            for cmd in cmds:
                tokens = cmd.strip().split(' ')
                if len(tokens) >= 2 and is_netmask(tokens[1]):
                    prefix = '{0}/{1}'.format(tokens[0],
                                              to_text(to_masklen(tokens[1])))
                    is_secondary = bool(
                        len(tokens) == 3 and tokens[2] == 'secondary')
                    if is_secondary:
                        secondary_list.append(prefix)
                    else:
                        ipv4 = prefix

            obj['ipv4'] = ipv4
            obj['ipv4_secondary'] = secondary_list

            ipv6_list = self.parse_config_argument(configobj, intf_name,
                                                   'ipv6 address')
            obj['ipv6'] = ipv6_list

            results.append(obj)

        return results
Exemple #18
0
def run(module, result):
    match = module.params['match']
    replace = module.params['replace']
    replace_config = replace == 'config'
    path = module.params['parents']
    comment = module.params['comment']
    admin = module.params['admin']
    check_mode = module.check_mode

    candidate = get_candidate(module)

    if match != 'none' and replace != 'config':
        contents = get_running_config(module)
        configobj = NetworkConfig(contents=contents, indent=1)
        commands = candidate.difference(configobj,
                                        path=path,
                                        match=match,
                                        replace=replace)
    else:
        commands = candidate.items

    if commands:
        commands = dumps(commands, 'commands').split('\n')

        if any((module.params['lines'], module.params['src'])):
            if module.params['before']:
                commands[:0] = module.params['before']

            if module.params['after']:
                commands.extend(module.params['after'])

            result['commands'] = commands

        commit = not check_mode
        diff = load_config(module,
                           commands,
                           commit=commit,
                           replace=replace_config,
                           comment=comment,
                           admin=admin)
        if diff:
            result['diff'] = dict(prepared=diff)
        result['changed'] = True
Exemple #19
0
    def get_diff(self,
                 candidate=None,
                 running=None,
                 diff_match='line',
                 diff_ignore_lines=None,
                 path=None,
                 diff_replace='line'):
        diff = {}
        device_operations = self.get_device_operations()
        option_values = self.get_option_values()

        if candidate is None and device_operations['supports_generate_diff']:
            raise ValueError(
                "candidate configuration is required to generate diff")

        if diff_match not in option_values['diff_match']:
            raise ValueError(
                "'match' value %s in invalid, valid values are %s" %
                (diff_match, ', '.join(option_values['diff_match'])))

        if diff_replace not in option_values['diff_replace']:
            raise ValueError(
                "'replace' value %s in invalid, valid values are %s" %
                (diff_replace, ', '.join(option_values['diff_replace'])))

        # prepare candidate configuration
        sanitized_candidate = sanitize_config(candidate)
        candidate_obj = NetworkConfig(indent=1)
        candidate_obj.load(sanitized_candidate)

        if running and diff_match != 'none':
            # running configuration
            running = mask_config_blocks_from_diff(running, candidate,
                                                   "ansible")
            running = sanitize_config(running)

            running_obj = NetworkConfig(indent=1,
                                        contents=running,
                                        ignore_lines=diff_ignore_lines)
            configdiffobjs = candidate_obj.difference(running_obj,
                                                      path=path,
                                                      match=diff_match,
                                                      replace=diff_replace)

        else:
            configdiffobjs = candidate_obj.items

        diff['config_diff'] = dumps(configdiffobjs,
                                    'commands') if configdiffobjs else ''
        return diff
Exemple #20
0
def run(module, result):
    match = module.params['match']
    replace = module.params['replace']
    path = module.params['parents']
    configobjs = None

    candidate = get_candidate(module)
    if match != 'none':
        contents = module.params['config']
        if not contents:
            contents = get_config(module)
        config = NetworkConfig(indent=1, contents=contents)
        configobjs = candidate.difference(config,
                                          path=path,
                                          match=match,
                                          replace=replace)

    else:
        configobjs = candidate.items
    if configobjs:
        commands = dumps(configobjs, 'commands').split('\n')

        if module.params['lines']:
            if module.params['before']:
                commands[:0] = module.params['before']

            if module.params['after']:
                commands.extend(module.params['after'])

        result['updates'] = commands

        # send the configuration commands to the device and merge
        # them with the current running config
        if not module.check_mode:
            load_config(module, commands)
        result['changed'] = True

    if result['changed'] or module.params['save_when'] == 'always':
        result['changed'] = True
        if not module.check_mode:
            cmd = {'command': 'write memory'}
            run_commands(module, [cmd])
Exemple #21
0
def map_config_to_obj(module):
    config = get_config(module)
    configobj = NetworkConfig(indent=1, contents=config)

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

    instances = list()

    for item in set(match):
        obj = {
            'name': item,
            'state': 'present',
            'description': parse_description(configobj, item),
            'rd': parse_rd(configobj, item),
            'interfaces': parse_interfaces(configobj, item)
        }
        instances.append(obj)
    return instances
Exemple #22
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
Exemple #23
0
def config_to_commands(config):
    set_format = config.startswith('set') or config.startswith('delete')
    candidate = NetworkConfig(indent=4, contents=config)
    if not set_format:
        candidate = [c.line for c in candidate.items]
        commands = list()
        # this filters out less specific lines
        for item in candidate:
            for index, entry in enumerate(commands):
                if item.startswith(entry):
                    del commands[index]
                    break
            commands.append(item)

        commands = ['set %s' % cmd.replace(' {', '') for cmd in commands]

    else:
        commands = str(candidate).split('\n')

    return commands
Exemple #24
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
    def get_diff(self, candidate=None, running=None, diff_match='line', diff_ignore_lines=None, path=None, diff_replace='line'):
        diff = {}

        # prepare candidate configuration
        candidate_obj = NetworkConfig(indent=1)
        candidate_obj.load(candidate)

        if running and diff_match != 'none' and diff_replace != 'config':
            # running configuration
            running_obj = NetworkConfig(indent=1, contents=running, ignore_lines=diff_ignore_lines)
            configdiffobjs = candidate_obj.difference(running_obj, path=path, match=diff_match, replace=diff_replace)
        else:
            configdiffobjs = candidate_obj.items

        diff['config_diff'] = dumps(configdiffobjs, 'commands') if configdiffobjs else ''
        return diff
Exemple #26
0
def run(module, result):
    match = module.params['match']
    replace = module.params['replace']
    path = module.params['parents']

    candidate = get_candidate(module)
    if match != 'none':
        contents = module.params['config']
        if not contents:
            contents = get_config(module)
        config = NetworkConfig(indent=1, contents=contents)
        configobjs = candidate.difference(config,
                                          path=path,
                                          match=match,
                                          replace=replace)

    else:
        configobjs = candidate.items

    total_commands = []
    if configobjs:
        commands = dumps(configobjs, 'commands').split('\n')

        if module.params['lines']:
            if module.params['before']:
                commands[:0] = module.params['before']

            if module.params['after']:
                commands.extend(module.params['after'])

        total_commands.extend(commands)
        result['updates'] = total_commands

    if module.params['save']:
        total_commands.append('configuration write')
    if total_commands:
        result['changed'] = True
        if not module.check_mode:
            load_config(module, total_commands)
Exemple #27
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):
        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,
        }

        if state == 'present':
            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
Exemple #28
0
    def get_diff(self,
                 candidate=None,
                 running=None,
                 match='line',
                 diff_ignore_lines=None,
                 path=None,
                 replace='line'):
        diff = {}
        device_operations = self.get_device_operations()
        option_values = self.get_option_values()

        if candidate is None and device_operations['supports_generate_diff']:
            raise ValueError(
                "candidate configuration is required to generate diff")

        if match not in option_values['diff_match']:
            raise ValueError(
                "'match' value %s in invalid, valid values are %s" %
                (match, ', '.join(option_values['diff_match'])))

        if replace not in option_values['diff_replace']:
            raise ValueError(
                "'replace' value %s in invalid, valid values are %s" %
                (replace, ', '.join(option_values['diff_replace'])))

        # prepare candidate configuration
        candidate_obj = NetworkConfig(indent=3)
        candidate_obj.load(candidate)

        if running and match != 'none' and replace != 'config':
            # running configuration
            running_obj = NetworkConfig(indent=3,
                                        contents=running,
                                        ignore_lines=diff_ignore_lines)
            configdiffobjs = candidate_obj.difference(running_obj,
                                                      path=path,
                                                      match=match,
                                                      replace=replace)

        else:
            configdiffobjs = candidate_obj.items

        configdiff = dumps(configdiffobjs,
                           'commands') if configdiffobjs else ''
        diff['config_diff'] = configdiff if configdiffobjs else {}
        return diff
Exemple #29
0
def map_config_to_obj(module):
    config = get_config(module)
    configobj = NetworkConfig(indent=1, 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,
            "description": parse_config_argument(configobj, item,
                                                 "description"),
            "speed": parse_config_argument(configobj, item, "speed"),
            "duplex": parse_config_argument(configobj, item, "duplex"),
            "mtu": parse_config_argument(configobj, item, "mtu"),
            "disable": True if parse_shutdown(configobj, item) else False,
            "state": "present",
        }
        instances.append(obj)
    return instances
Exemple #30
0
    def map_config_to_obj(self, config):
        results = []

        # ほとんどの情報はshow interfaces switchportから読み取るので、
        # running-configはチャネルが設定されているかどうか、しか見ない

        match = re.findall(r'^interface (\S+)', config, re.M)

        configobj = NetworkConfig(indent=1, contents=config)

        for item in set(match):
            # 'channel-group'で始まるコマンドのオプションを取り出す。コマンドがなければNone
            channel_group = self.parse_config_argument(configobj, item,
                                                       'channel-group')

            obj = {
                'name': item,
                'channel_group': channel_group,
                'state': 'present'
            }
            results.append(obj)

        return results
    def map_config_to_obj(self, config):

        # コンフィグからインタフェース名の一覧を取り出す
        match = re.findall(r'^interface (\S+)', config, re.M)
        if not match:
            return list()

        configobj = NetworkConfig(indent=1, contents=config)

        results = []
        for intf_name in set(match):
            obj = {}
            obj['name'] = intf_name
            obj['state'] = 'present'

            for param in self.supported_params:
                func = getattr(self, 'parse_%s' % param, None)
                if callable(func):
                    obj[param] = func(configobj, intf_name)

            results.append(obj)

        return results
def map_config_to_obj(module):
    compare = module.params['check_running_config']
    config = get_config(module, None, compare)
    configobj = NetworkConfig(indent=1, contents=config)
    match = re.findall(r'^interface (.+)$', config, re.M)

    if not match:
        return list()

    instances = list()

    for item in set(match):
        obj = {
            'name': item,
            'port-name': parse_config_argument(configobj, item, 'port-name'),
            'speed-duplex': parse_config_argument(configobj, item, 'speed-duplex'),
            'stp': parse_stp_arguments(module, item),
            'disable': True if parse_enable(configobj, item) else False,
            'power': parse_power_argument(configobj, item),
            'state': 'present'
        }
        instances.append(obj)
    return instances
    def map_config_to_obj(self, config):

        configobj = NetworkConfig(indent=1, contents=config)

        # interface port-channel xxx を探す
        match = re.findall(r'^interface Port-channel(\S+)', config, re.M)
        if not match:
            return list()

        results = []
        for po_number in set(match):
            obj = {}
            obj['state'] = 'present'
            obj['group'] = po_number

            # channel-group xxx を設定しているインタフェースを捕まえる
            members = []
            mode = None
            match = re.findall(r'^interface (\S+)', config, re.M)
            if match:
                for intf_name in set(match):
                    cfg = configobj['interface {}'.format(intf_name)]
                    cfg = '\n'.join(cfg.children)
                    m = re.search(
                        r'^channel-group {} mode (\S+)'.format(po_number), cfg,
                        re.M)
                    if m:
                        members.append(intf_name)
                        mode = m.group(1)

            obj['mode'] = mode
            obj['members'] = members

            results.append(obj)

        return results
def run(module, result):
    match = module.params['match']

    candidate = get_candidate(module)

    if match != 'none':
        config_text = get_active_config(module)
        config = NetworkConfig(indent=4, contents=config_text)
        configobjs = candidate.difference(config)
    else:
        configobjs = candidate.items

    if configobjs:
        commands = dumps(configobjs, 'commands')
        commands = commands.split('\n')

        result['commands'] = commands
        result['updates'] = commands

        # send the configuration commands to the device and merge
        # them with the current running config
        if not module.check_mode:
            load_config(module, commands)
        result['changed'] = True
Exemple #35
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        src=dict(type='path'),
        replace_src=dict(),
        lines=dict(aliases=['commands'], type='list'),
        parents=dict(type='list'),
        before=dict(type='list'),
        after=dict(type='list'),
        match=dict(default='line', choices=['line', 'strict', 'exact',
                                            'none']),
        replace=dict(default='line', choices=['line', 'block', 'config']),
        running_config=dict(aliases=['config']),
        intended_config=dict(),
        defaults=dict(type='bool', default=False),
        backup=dict(type='bool', default=False),
        save_when=dict(choices=['always', 'never', 'modified', 'changed'],
                       default='never'),
        diff_against=dict(choices=['running', 'startup', 'intended']),
        diff_ignore_lines=dict(type='list'),

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

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

    argument_spec.update(nxos_argument_spec)

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

    required_if = [('match', 'strict', ['lines']),
                   ('match', 'exact', ['lines']),
                   ('replace', 'block', ['lines']),
                   ('replace', 'config', ['replace_src']),
                   ('diff_against', 'intended', ['intended_config'])]

    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=mutually_exclusive,
                           required_if=required_if,
                           supports_check_mode=True)

    warnings = list()
    nxos_check_args(module, warnings)

    result = {'changed': False, 'warnings': warnings}

    config = None

    try:
        info = get_capabilities(module)
        api = info.get('network_api')
        device_info = info.get('device_info', {})
        os_platform = device_info.get('network_os_platform', '')
    except ConnectionError:
        api = ''
        os_platform = ''

    if api == 'cliconf' and module.params['replace'] == 'config':
        if '9K' not in os_platform:
            module.fail_json(
                msg=
                'replace: config is supported only on Nexus 9K series switches'
            )

    if module.params['replace_src']:
        if module.params['replace'] != 'config':
            module.fail_json(
                msg='replace: config is required with replace_src')

    if module.params['backup'] or (module._diff and
                                   module.params['diff_against'] == 'running'):
        contents = get_config(module)
        config = NetworkConfig(indent=2, contents=contents)
        if module.params['backup']:
            result['__backup__'] = contents

    if any((module.params['src'], module.params['lines'],
            module.params['replace_src'])):
        match = module.params['match']
        replace = module.params['replace']

        candidate = get_candidate(module)

        if match != 'none' and replace != 'config':
            config = get_running_config(module, config)
            path = module.params['parents']
            configobjs = candidate.difference(config,
                                              match=match,
                                              replace=replace,
                                              path=path)
        else:
            configobjs = candidate.items

        if configobjs:
            commands = dumps(configobjs, 'commands').split('\n')

            if module.params['before']:
                commands[:0] = module.params['before']

            if module.params['after']:
                commands.extend(module.params['after'])

            result['commands'] = commands
            result['updates'] = commands

            if not module.check_mode:
                load_config(module, commands)

            result['changed'] = True

    running_config = module.params['running_config']
    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 = execute_show_commands(
            module, ['show running-config', 'show startup-config'])

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

        if running_config.sha1 != startup_config.sha1:
            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 = execute_show_commands(module, 'show running-config')
            contents = output[0]
        else:
            contents = running_config

        # recreate the object in order to process diff_ignore_lines
        running_config = NetworkConfig(indent=1,
                                       contents=contents,
                                       ignore_lines=diff_ignore_lines)

        if module.params['diff_against'] == 'running':
            if module.check_mode:
                module.warn(
                    "unable to perform diff against running-config due to check mode"
                )
                contents = None
            else:
                contents = config.config_text

        elif module.params['diff_against'] == 'startup':
            if not startup_config:
                output = execute_show_commands(module, 'show startup-config')
                contents = output[0]
            else:
                contents = output[0]
                contents = startup_config.config_text

        elif module.params['diff_against'] == 'intended':
            contents = module.params['intended_config']

        if contents is not None:
            base_config = NetworkConfig(indent=1,
                                        contents=contents,
                                        ignore_lines=diff_ignore_lines)

            if running_config.sha1 != base_config.sha1:
                if module.params['diff_against'] == 'intended':
                    before = running_config
                    after = base_config
                elif module.params['diff_against'] in ('startup', 'running'):
                    before = base_config
                    after = running_config

                result.update({
                    'changed': True,
                    'diff': {
                        'before': str(before),
                        'after': str(after)
                    }
                })

    module.exit_json(**result)
def map_obj_to_commands(updates, module):
    commands = list()

    for update in updates:
        want, have = update

        def needs_update(want, have, x):
            if isinstance(want.get(x), list) and isinstance(have.get(x), list):
                return want.get(x) and (want.get(x) != have.get(x)
                                        ) and not all(elem in have.get(x)
                                                      for elem in want.get(x))
            return want.get(x) and (want.get(x) != have.get(x))

        if want['state'] == 'absent':
            commands.append('no vrf definition %s' % want['name'])
            continue

        if not have.get('state'):
            commands.extend([
                'vrf definition %s' % want['name'],
                'address-family ipv4',
                'exit',
                'address-family ipv6',
                'exit',
            ])

        if needs_update(want, have, 'description'):
            cmd = 'description %s' % want['description']
            add_command_to_vrf(want['name'], cmd, commands)

        if needs_update(want, have, 'rd'):
            cmd = 'rd %s' % want['rd']
            add_command_to_vrf(want['name'], cmd, commands)

        if needs_update(want, have, 'route_import'):
            for route in want['route_import']:
                cmd = 'route-target import %s' % route
                add_command_to_vrf(want['name'], cmd, commands)

        if needs_update(want, have, 'route_export'):
            for route in want['route_export']:
                cmd = 'route-target export %s' % route
                add_command_to_vrf(want['name'], cmd, commands)

        if needs_update(want, have, 'route_import_ipv4'):
            cmd = 'address-family ipv4'
            add_command_to_vrf(want['name'], cmd, commands)
            for route in want['route_import_ipv4']:
                cmd = 'route-target import %s' % route
                add_command_to_vrf(want['name'], cmd, commands)
            cmd = 'exit-address-family'
            add_command_to_vrf(want['name'], cmd, commands)

        if needs_update(want, have, 'route_export_ipv4'):
            cmd = 'address-family ipv4'
            add_command_to_vrf(want['name'], cmd, commands)
            for route in want['route_export_ipv4']:
                cmd = 'route-target export %s' % route
                add_command_to_vrf(want['name'], cmd, commands)
            cmd = 'exit-address-family'
            add_command_to_vrf(want['name'], cmd, commands)

        if needs_update(want, have, 'route_import_ipv6'):
            cmd = 'address-family ipv6'
            add_command_to_vrf(want['name'], cmd, commands)
            for route in want['route_import_ipv6']:
                cmd = 'route-target import %s' % route
                add_command_to_vrf(want['name'], cmd, commands)
            cmd = 'exit-address-family'
            add_command_to_vrf(want['name'], cmd, commands)

        if needs_update(want, have, 'route_export_ipv6'):
            cmd = 'address-family ipv6'
            add_command_to_vrf(want['name'], cmd, commands)
            for route in want['route_export_ipv6']:
                cmd = 'route-target export %s' % route
                add_command_to_vrf(want['name'], cmd, commands)
            cmd = 'exit-address-family'
            add_command_to_vrf(want['name'], cmd, commands)

        if want['interfaces'] is not None:
            # handle the deletes
            for intf in set(have.get('interfaces',
                                     [])).difference(want['interfaces']):
                commands.extend([
                    'interface %s' % intf,
                    'no vrf forwarding %s' % want['name']
                ])

            # handle the adds
            for intf in set(want['interfaces']).difference(
                    have.get('interfaces', [])):
                cfg = get_config(module)
                configobj = NetworkConfig(indent=1, contents=cfg)
                children = configobj['interface %s' % intf].children
                intf_config = '\n'.join(children)

                commands.extend([
                    'interface %s' % intf,
                    'vrf forwarding %s' % want['name']
                ])

                match = re.search('ip address .+', intf_config, re.M)
                if match:
                    commands.append(match.group())

    return commands
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']),
        multiline_delimiter=dict(default='@'),

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

        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', 'intended', 'running']),
        diff_ignore_lines=dict(type='list'),
    )

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

    required_if = [('match', 'strict', ['lines']),
                   ('match', 'exact', ['lines']),
                   ('replace', 'block', ['lines']),
                   ('diff_against', 'intended', ['intended_config'])]

    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=mutually_exclusive,
                           required_if=required_if,
                           supports_check_mode=True)

    result = {'changed': False}

    warnings = list()
    check_args(module, 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=1, contents=contents)
        if module.params['backup']:
            result['__backup__'] = contents

    if any((module.params['lines'], module.params['src'])):
        match = module.params['match']
        replace = module.params['replace']
        path = module.params['parents']

        candidate = get_candidate(module)

        if match != 'none':
            config = get_running_config(module, config)
            path = module.params['parents']
            configobjs = candidate.difference(config, path=path, match=match, replace=replace)
        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

            # send the configuration commands to the device and merge
            # them with the current running config
            if not module.check_mode:
                if commands:
                    load_config(module, commands)

            result['changed'] = True

    running_config = None
    startup_config = None

    diff_ignore_lines = module.params['diff_ignore_lines']

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

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

        if running_config.sha1 != startup_config.sha1:
            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, 'show running-config')
            contents = output[0]
        else:
            contents = running_config.config_text

        # recreate the object in order to process diff_ignore_lines
        running_config = NetworkConfig(indent=1, contents=contents, ignore_lines=diff_ignore_lines)

        if module.params['diff_against'] == 'running':
            if module.check_mode:
                module.warn("unable to perform diff against running-config due to check mode")
                contents = None
            else:
                contents = config.config_text

        elif module.params['diff_against'] == 'startup':
            if not startup_config:
                output = run_commands(module, 'show startup-config')
                contents = output[0]
            else:
                contents = 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)
Exemple #38
0
    def get_diff(self,
                 candidate=None,
                 running=None,
                 diff_match='line',
                 diff_ignore_lines=None,
                 path=None,
                 diff_replace=None):
        diff = {}
        device_operations = self.get_device_operations()
        option_values = self.get_option_values()

        if candidate is None and device_operations['supports_generate_diff']:
            raise ValueError(
                "candidate configuration is required to generate diff")

        if diff_match not in option_values['diff_match']:
            raise ValueError(
                "'match' value %s in invalid, valid values are %s" %
                (diff_match, ', '.join(option_values['diff_match'])))

        if diff_replace:
            raise ValueError("'replace' in diff is not supported")

        if diff_ignore_lines:
            raise ValueError("'diff_ignore_lines' in diff is not supported")

        if path:
            raise ValueError("'path' in diff is not supported")

        set_format = candidate.startswith('set') or candidate.startswith(
            'delete')
        candidate_obj = NetworkConfig(indent=4, contents=candidate)
        if not set_format:
            config = [c.line for c in candidate_obj.items]
            commands = list()
            # this filters out less specific lines
            for item in config:
                for index, entry in enumerate(commands):
                    if item.startswith(entry):
                        del commands[index]
                        break
                commands.append(item)

            candidate_commands = [
                'set %s' % cmd.replace(' {', '') for cmd in commands
            ]

        else:
            candidate_commands = str(candidate).strip().split('\n')

        if diff_match == 'none':
            diff['config_diff'] = list(candidate_commands)
            return diff

        running_commands = [
            str(c).replace("'", '') for c in running.splitlines()
        ]

        updates = list()
        visited = set()

        for line in candidate_commands:
            item = str(line).replace("'", '')

            if not item.startswith('set') and not item.startswith('delete'):
                raise ValueError(
                    'line must start with either `set` or `delete`')

            elif item.startswith('set') and item not in running_commands:
                updates.append(line)

            elif item.startswith('delete'):
                if not running_commands:
                    updates.append(line)
                else:
                    item = re.sub(r'delete', 'set', item)
                    for entry in running_commands:
                        if entry.startswith(item) and line not in visited:
                            updates.append(line)
                            visited.add(line)

        diff['config_diff'] = list(updates)
        return diff
Exemple #39
0
    def get_diff(self,
                 candidate=None,
                 running=None,
                 diff_match='line',
                 diff_ignore_lines=None,
                 path=None,
                 diff_replace='line'):
        """
        Generate diff between candidate and running configuration. If the
        remote host supports onbox diff capabilities ie. supports_onbox_diff in that case
        candidate and running configurations are not required to be passed as argument.
        In case if onbox diff capability is not supported candidate argument is mandatory
        and running argument is optional.
        :param candidate: The configuration which is expected to be present on remote host.
        :param running: The base configuration which is used to generate diff.
        :param diff_match: Instructs how to match the candidate configuration with current device configuration
                      Valid values are 'line', 'strict', 'exact', 'none'.
                      'line' - commands are matched line by line
                      'strict' - command lines are matched with respect to position
                      'exact' - command lines must be an equal match
                      'none' - will not compare the candidate configuration with the running configuration
        :param diff_ignore_lines: Use this argument to specify one or more lines that should be
                                  ignored during the diff.  This is used for lines in the configuration
                                  that are automatically updated by the system.  This argument takes
                                  a list of regular expressions or exact line matches.
        :param path: The ordered set of parents that uniquely identify the section or hierarchy
                     the commands should be checked against.  If the parents argument
                     is omitted, the commands are checked against the set of top
                    level or global commands.
        :param diff_replace: Instructs on the way to perform the configuration on the device.
                        If the replace argument is set to I(line) then the modified lines are
                        pushed to the device in configuration mode.  If the replace argument is
                        set to I(block) then the entire command block is pushed to the device in
                        configuration mode if any line is not correct.
        :return: Configuration diff in  json format.
               {
                   'config_diff': '',
                   'banner_diff': {}
               }

        """
        diff = {}
        device_operations = self.get_device_operations()
        option_values = self.get_option_values()

        if candidate is None and device_operations['supports_generate_diff']:
            raise ValueError(
                "candidate configuration is required to generate diff")

        if diff_match not in option_values['diff_match']:
            raise ValueError(
                "'match' value %s in invalid, valid values are %s" %
                (diff_match, ', '.join(option_values['diff_match'])))

        if diff_replace not in option_values['diff_replace']:
            raise ValueError(
                "'replace' value %s in invalid, valid values are %s" %
                (diff_replace, ', '.join(option_values['diff_replace'])))

        # prepare candidate configuration
        candidate_obj = NetworkConfig(indent=1)
        want_src, want_banners = self._extract_banners(candidate)
        candidate_obj.load(want_src)

        if running and diff_match != 'none':
            # running configuration
            have_src, have_banners = self._extract_banners(running)
            running_obj = NetworkConfig(indent=1,
                                        contents=have_src,
                                        ignore_lines=diff_ignore_lines)
            configdiffobjs = candidate_obj.difference(running_obj,
                                                      path=path,
                                                      match=diff_match,
                                                      replace=diff_replace)

        else:
            configdiffobjs = candidate_obj.items
            have_banners = {}

        diff['config_diff'] = dumps(configdiffobjs,
                                    'commands') if configdiffobjs else ''
        banners = self._diff_banners(want_banners, have_banners)
        diff['banner_diff'] = banners if banners else {}
        return diff