Beispiel #1
1
def load(module, commands, result):
    candidate = NetworkConfig(indent=2, contents='\n'.join(commands))
    config = get_config(module)
    configobjs = candidate.difference(config)

    if configobjs:
        commands = dumps(configobjs, 'commands').split('\n')
        result['updates'] = commands
        if not module.check_mode:
            load_config(module, commands, result)
        result['changed'] = True
Beispiel #2
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'])
    return candidate
Beispiel #3
0
def get_candidate(module):
    candidate = NetworkConfig(device_os='sros')
    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
Beispiel #4
0
def main():
    """ main entry point for module execution
    """

    argument_spec = dict(
        src=dict(required=True),
        force=dict(default=False, type='bool'),
        include_defaults=dict(default=False, type='bool'),
        backup=dict(default=False, type='bool'),
        replace=dict(default=False, type='bool'),
        config=dict()
    )

    mutually_exclusive = [('config', 'backup'), ('config', 'force')]

    module = NetworkModule(argument_spec=argument_spec,
                           mutually_exclusive=mutually_exclusive,
                           supports_check_mode=True)

    replace = module.params['replace']

    commands = list()
    running = None

    result = dict(changed=False)

    candidate = NetworkConfig(contents=module.params['src'], indent=3)

    if replace:
        if module.params['transport'] == 'cli':
            module.fail_json(msg='config replace is only supported over eapi')
        commands = str(candidate).split('\n')
    else:
        contents = get_config(module)
        if contents:
            running = NetworkConfig(contents=contents, indent=3)
            result['_backup'] = contents

        if not module.params['force']:
            commands = candidate.difference((running or list()))
            commands = dumps(commands, 'commands').split('\n')
            commands = [str(c) for c in commands if c]
        else:
            commands = str(candidate).split('\n')

    commands = filter_exit(commands)
    if commands:
        if not module.check_mode:
            response = module.config.load_config(commands, replace=replace,
                                                 commit=True)
            result['responses'] = response
        result['changed'] = True

    result['updates'] = commands
    module.exit_json(**result)
Beispiel #5
0
def load(module, instance, commands, result):
    candidate = NetworkConfig(indent=3)
    candidate.add(commands, parents=['management api http-commands'])

    config = get_config(module)
    configobjs = candidate.difference(config)

    if configobjs:
        commands = dumps(configobjs, 'commands').split('\n')
        result['updates'] = commands
        load_config(module, instance, commands, result)
Beispiel #6
0
def get_config(module):
    contents = module.params['config']
    if not contents:
        try:
            contents = module.cli(['show running-config nxapi all'])[0]
        except NetworkError:
            contents = None
    config = NetworkConfig(indent=2)
    if contents:
        config.load(contents)
    return config
Beispiel #7
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
Beispiel #8
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()
    )

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

    lines = module.params['lines']

    before = module.params['before']
    after = module.params['after']

    match = module.params['match']
    replace = module.params['replace']

    result = dict(changed=False)

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

    acl_name = parse_acl_name(module)

    if not module.params['force']:
        contents = get_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 not module.check_mode:
            response = module.config(commands)
            result['responses'] = response
        result['changed'] = True

    result['updates'] = commands

    module.exit_json(**result)
Beispiel #9
0
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)
Beispiel #10
0
def load_config(module, commands, result):
    candidate = NetworkConfig(device_os='sros', contents='\n'.join(commands))
    config = get_config(module)
    configobjs = candidate.difference(config)

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

        result['updates'] = commands

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

        result['changed'] = True
Beispiel #11
0
def map_config_to_obj(module):
    config = get_config(module)
    configobj = NetworkConfig(indent=2, contents=config)

    vrf_config = {}

    vrfs = re.findall('^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)
    }
Beispiel #12
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
Beispiel #13
0
def main():
    """ main entry point for module execution
    """

    argument_spec = dict(
        src=dict(),
        force=dict(default=False, type='bool'),
        include_defaults=dict(default=True, type='bool'),
        backup=dict(default=False, type='bool'),
        config=dict(),
    )

    mutually_exclusive = [('config', 'backup'), ('config', 'force')]

    module = NetworkModule(argument_spec=argument_spec,
                           mutually_exclusive=mutually_exclusive,
                           supports_check_mode=True)

    result = dict(changed=False)

    candidate = NetworkConfig(contents=module.params['src'], indent=2)

    contents = get_config(module)
    if contents:
        config = NetworkConfig(contents=contents, indent=2)
        result['_backup'] = str(contents)

    if not module.params['force']:
        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 not module.check_mode:
            response = module.config(commands)
            result['responses'] = response
        result['changed'] = True

    result['updates'] = commands
    module.exit_json(**result)
Beispiel #14
0
def get_config(module):
    config = module.params['running_config']
    if not config:
        config = module.config.get_config(include_defaults=True)
    return NetworkConfig(indent=2, contents=config)
Beispiel #15
0
def main():
    """ main entry point for module execution
    """

    argument_spec = dict(
        src=dict(type='str'),
        force=dict(default=False, type='bool'),
        backup=dict(default=False, type='bool'),
        config=dict(type='dict'),
    )

    mutually_exclusive = [('config', 'backup'), ('config', 'force')]

    module = NetworkModule(argument_spec=argument_spec,
                           mutually_exclusive=mutually_exclusive,
                           supports_check_mode=True)

    if not module.params['transport'] and not HAS_OPS:
        module.fail_json(msg='unable to import ops.dc library')

    result = dict(changed=False)

    contents = get_config(module)
    result['_backup'] = contents

    if module.params['transport'] in ['ssh', 'rest']:
        config = contents

        try:
            src = module.from_json(module.params['src'])
        except ValueError:
            module.fail_json(msg='unable to load src due to json parsing error')

        changeset = diff(src, config)
        candidate = merge(changeset, config)

        updates = dict()
        for path, key, new_value, old_value in changeset:
            path = '%s.%s' % ('.'.join(path), key)
            updates[path] = str(new_value)
        result['updates'] = updates

        if changeset:
            if not module.check_mode:
                module.config(config)
            result['changed'] = True

    else:
        candidate = NetworkConfig(contents=module.params['src'], indent=4)

        if contents:
            config = NetworkConfig(contents=contents, indent=4)

        if not module.params['force']:
            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 not module.check_mode:
                response = module.config(commands)
                result['responses'] = response
            result['changed'] = True

        result['updates'] = commands

    module.exit_json(**result)
Beispiel #16
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'),

        m_facts=dict(default=False, type='bool', removed_in_version="2.4"),
        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
            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)
Beispiel #17
0
def get_config(module, result):
    contents = module.params['config']
    if not contents:
        defaults = module.params['defaults']
        contents = module.config.get_config(detail=defaults)
    return NetworkConfig(device_os='sros', contents=contents)
def get_config(module):
    contents = module.params['config']
    if not contents:
        defaults = module.params['defaults']
        contents = module.config.get_config(include_defaults=defaults)
    return NetworkConfig(indent=2, contents=contents)
def main():

    argument_spec = dict(lines=dict(aliases=['commands'], type='list'),
                         parents=dict(type='list'),
                         src=dict(type='path'),
                         before=dict(type='list'),
                         after=dict(type='list'),
                         match=dict(
                             default='line',
                             choices=['line', 'strict', 'exact', 'none']),
                         replace=dict(default='line',
                                      choices=['line', 'block']),
                         update=dict(choices=['merge', 'check'],
                                     default='merge'),
                         save=dict(type='bool', default=False),
                         config=dict(),
                         backup=dict(type='bool', default=False))

    argument_spec.update(dellos10_argument_spec)

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

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

    parents = module.params['parents'] or list()

    match = module.params['match']
    replace = module.params['replace']

    warnings = list()
    check_args(module, warnings)

    result = dict(changed=False, saved=False, warnings=warnings)

    candidate = get_candidate(module)
    if match != 'none':
        config = get_config(module)
        if parents:
            contents = get_sublevel_config(config, module)
            config = NetworkConfig(contents=contents, indent=1)
        else:
            config = NetworkConfig(contents=config, indent=1)
        configobjs = candidate.difference(config, match=match, replace=replace)

    else:
        configobjs = candidate.items

    if module.params['backup']:
        result['__backup__'] = get_config(module)

    commands = list()

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

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

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

        if not module.check_mode and module.params['update'] == 'merge':
            load_config(module, commands)

            if module.params['save']:
                cmd = {
                    'command': 'copy runing-config startup-config',
                    'prompt': WARNING_PROMPTS_RE,
                    'answer': 'yes'
                }
                run_commands(module, [cmd])
                result['saved'] = True

        result['changed'] = True

    result['updates'] = commands

    module.exit_json(**result)
Beispiel #20
0
def get_running_config(module):
    contents = module.params['config']
    if not contents:
        contents = get_config(module)
    return NetworkConfig(indent=1, contents=contents)
Beispiel #21
0
def main():

    argument_spec = dict(lines=dict(aliases=['commands'], type='list'),
                         parents=dict(type='list'),
                         src=dict(type='path'),
                         before=dict(type='list'),
                         after=dict(type='list'),
                         match=dict(
                             default='line',
                             choices=['line', 'strict', 'exact', 'none']),
                         replace=dict(default='line',
                                      choices=['line', 'block']),
                         update=dict(choices=['merge', 'check'],
                                     default='merge'),
                         save=dict(type='bool', default=False),
                         config=dict(),
                         backup=dict(type='bool', default=False))

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

    module = NetworkModule(argument_spec=argument_spec,
                           connect_on_load=False,
                           mutually_exclusive=mutually_exclusive,
                           supports_check_mode=True)

    parents = module.params['parents'] or list()

    match = module.params['match']
    replace = module.params['replace']
    result = dict(changed=False, saved=False)

    candidate = get_candidate(module)

    if match != 'none':
        config = get_config(module)
        if parents:
            contents = get_sublevel_config(config, module)
            config = NetworkConfig(contents=contents, indent=1)
        configobjs = candidate.difference(config, match=match, replace=replace)

    else:
        configobjs = candidate.items

    if module.params['backup']:
        result['__backup__'] = module.cli('show running-config')[0]

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

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

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

        if not module.check_mode and module.params['update'] == 'merge':
            response = module.config.load_config(commands)
            result['responses'] = response

            if module.params['save']:
                module.config.save_config()
                result['saved'] = True

        result['changed'] = True

    result['updates'] = commands

    module.exit_json(**result)
Beispiel #22
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']),
        running_config=dict(aliases=['config']),
        intended_config=dict(),
        defaults=dict(type='bool', default=False),
        backup=dict(type='bool', default=False),
        save_when=dict(choices=['always', 'never', 'modified'],
                       default='never'),
        diff_against=dict(choices=['running', 'startup', 'intended']),
        diff_ignore_lines=dict(type='list'),

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

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

    argument_spec.update(nxos_argument_spec)

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

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

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

    warnings = list()
    nxos_check_args(module, warnings)

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

    config = None

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

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

        candidate = get_candidate(module)

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

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

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

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

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

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

            result['changed'] = True

    running_config = None
    startup_config = None

    diff_ignore_lines = module.params['diff_ignore_lines']

    if module.params['save']:
        module.params['save_when'] = 'always'

    if module.params['save_when'] != 'never':
        output = 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 or module.params[
                'save_when'] == 'always':
            result['changed'] = True
            if not module.check_mode:
                cmd = {
                    'command': 'copy running-config startup-config',
                    'output': 'text'
                }
                run_commands(module, [cmd])
            else:
                module.warn(
                    'Skipping command `copy running-config startup-config` '
                    'due to check_mode.  Configuration not copied to '
                    'non-volatile storage')

    if module._diff:
        if not running_config:
            output = execute_show_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 = 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:
                result.update({
                    'changed': True,
                    'diff': {
                        'before': str(base_config),
                        'after': str(running_config)
                    }
                })

    module.exit_json(**result)
def main():
    """ main entry point for module execution
    """

    argument_spec = dict(
        src=dict(type='str'),
        force=dict(default=False, type='bool'),
        backup=dict(default=False, type='bool'),
        config=dict(type='dict'),
    )

    mutually_exclusive = [('config', 'backup'), ('config', 'force')]

    module = NetworkModule(argument_spec=argument_spec,
                           mutually_exclusive=mutually_exclusive,
                           supports_check_mode=True)

    if not module.params['transport'] and not HAS_OPS:
        module.fail_json(msg='unable to import ops.dc library')

    result = dict(changed=False)

    contents = get_config(module)
    result['_backup'] = contents

    if module.params['transport'] in ['ssh', 'rest']:
        config = contents

        try:
            src = module.from_json(module.params['src'])
        except ValueError:
            module.fail_json(msg='unable to load src due to json parsing error')

        changeset = diff(src, config)
        candidate = merge(changeset, config)

        updates = dict()
        for path, key, new_value, old_value in changeset:
            path = '%s.%s' % ('.'.join(path), key)
            updates[path] = str(new_value)
        result['updates'] = updates

        if changeset:
            if not module.check_mode:
                module.config(config)
            result['changed'] = True

    else:
        candidate = NetworkConfig(contents=module.params['src'], indent=4)

        if contents:
            config = NetworkConfig(contents=contents, indent=4)

        if not module.params['force']:
            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 not module.check_mode:
                response = module.config(commands)
                result['responses'] = response
            result['changed'] = True

        result['updates'] = commands

    module.exit_json(**result)
Beispiel #24
0
def get_config(module, result):
    contents = module.params['config']
    if not contents:
        contents = module.config.get_config()
    return NetworkConfig(indent=1, contents=contents)
Beispiel #25
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']),
        multiline_delimiter=dict(default='@'),
        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=['startup', 'intended', 'running']),
        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.7'))

    argument_spec.update(ios_argument_spec)

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

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

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

    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, want_banners = get_candidate(module)

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

        banners = diff_banners(want_banners, have_banners)

        if configobjs or banners:
            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
            result['banners'] = banners

            # 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)
                if banners:
                    load_banners(module, banners)

            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,
                              ['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:
                result.update({
                    'changed': True,
                    'diff': {
                        'before': str(base_config),
                        'after': str(running_config)
                    }
                })

    module.exit_json(**result)
Beispiel #26
0
def get_config(module, result):
    contents = module.params['config'] or result.get('__config__')
    if not contents:
        contents = module.config.get_config()
        result['__config__'] = contents
    return NetworkConfig(device_os='sros', contents=contents)
def get_config(module):
    contents = module.config.get_config()
    return NetworkConfig(device_os='sros', contents=contents)