Exemple #1
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

        diff = load_config(module, commands)
        if diff:
            result['diff'] = dict(prepared=diff)
            result['changed'] = True
Exemple #2
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)
    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
Exemple #4
0
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 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 #6
0
def get_startup_config(module):
    data = get_startup_config_text(module)
    return NetworkConfig(indent=1, contents=data)
Exemple #7
0
def main():
    """ main entry point for module execution
    """
    backup_spec = dict(filename=dict(), dir_path=dict(type='path'))
    argument_spec = dict(
        src=dict(type='path'),
        lines=dict(aliases=['commands'], type='list'),
        parents=dict(type='list'),
        before=dict(type='list'),
        after=dict(type='list'),
        match=dict(default='line', choices=['line', 'strict', 'exact',
                                            'none']),
        replace=dict(default='line', choices=['line', 'block', 'config']),
        defaults=dict(type='bool', default=False),
        backup=dict(type='bool', default=False),
        backup_options=dict(type='dict', options=backup_spec),
        save_when=dict(choices=['always', 'never', 'modified', 'changed'],
                       default='never'),
        diff_against=dict(choices=['startup', 'intended', 'running'],
                          default='running'),
        diff_ignore_lines=dict(type='list'),
        running_config=dict(aliases=['config']),
        intended_config=dict(),
    )

    argument_spec.update(aos_argument_spec)

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

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

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

    warnings = list()
    check_args(module, warnings)

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

    runnconfig_before_changes = None
    flags = ['all'] if module.params['defaults'] else []

    running_cfg = None
    if is_backup_requested(module):
        running_cfg = get_config(module, flags=flags)
        runnconfig_before_changes = NetworkConfig(
            indent=CFG_FILE_SUBCONFIG_INDENT, contents=running_cfg)
        if module.params['backup']:
            result['__backup__'] = running_cfg

    if is_new_config_provided(module):
        res = apply_config(module, running_cfg)
        result.update(res)

    if is_config_store_requested(module):
        store_config(module, result)

    # check if config difference output is requested
    if module._diff:
        diff = find_diff(module, runnconfig_before_changes)
        result.update(diff)

    module.exit_json(**result)
def main():
    """ main entry point for module execution
    """
    backup_spec = dict(
        filename=dict(),
        dir_path=dict(type='path')
    )
    argument_spec = dict(
        src=dict(type='path'),

        lines=dict(aliases=['commands'], type='list'),
        parents=dict(type='list'),

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

        match=dict(default='line', choices=['line', 'strict', 'exact', 'none']),
        replace=dict(default='line', choices=['line', 'block']),
        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 #9
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
Exemple #10
0
def main():
    """ main entry point for module execution
    """
    backup_spec = dict(filename=dict(), dir_path=dict(type='path'))
    argument_spec = dict(
        src=dict(type='path'),
        lines=dict(aliases=['commands'], type='list'),
        parents=dict(type='list'),
        before=dict(type='list'),
        after=dict(type='list'),
        match=dict(default='line', choices=['line', 'strict', 'exact',
                                            'none']),
        replace=dict(default='line', choices=['line', 'block', 'config']),
        defaults=dict(type='bool', default=False),
        backup=dict(type='bool', default=False),
        backup_options=dict(type='dict', options=backup_spec),
        save_when=dict(choices=['always', 'never', 'modified', 'changed'],
                       default='never'),
        diff_against=dict(
            choices=['startup', 'session', 'intended', 'running'],
            default='session'),
        diff_ignore_lines=dict(type='list'),
        running_config=dict(aliases=['config']),
        intended_config=dict(),
    )

    argument_spec.update(eos_argument_spec)

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

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

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

    warnings = list()
    check_args(module, warnings)

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

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

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

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

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

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

        config_diff = response['config_diff']

        if config_diff:
            commands = config_diff.split('\n')

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

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

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

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

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

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

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

            result['changed'] = True

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

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

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

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

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

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

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

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

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

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

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

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

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

    module.exit_json(**result)
def get_running_config(module):
    contents = module.params['config']
    if not contents:
        contents = get_config(module)
    return NetworkConfig(indent=1, contents=contents)
Exemple #12
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 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"),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

    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)
Exemple #14
0
def main():
    """ main entry point for module execution
    """
    backup_spec = dict(filename=dict(), dir_path=dict(type="path"))
    argument_spec = dict(
        src=dict(type="path"),
        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),
        backup_options=dict(type="dict", options=backup_spec),
        save_when=dict(choices=["always", "never", "modified", "changed"],
                       default="never"),
        diff_against=dict(choices=["running", "startup", "intended"]),
        diff_ignore_lines=dict(type="list"),
    )

    argument_spec.update(nxos_argument_spec)

    mutually_exclusive = [("lines", "src", "replace_src"), ("parents", "src")]

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

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

    config = None

    diff_ignore_lines = module.params["diff_ignore_lines"]
    path = module.params["parents"]
    connection = get_connection(module)
    contents = None
    flags = ["all"] if module.params["defaults"] else []
    replace_src = module.params["replace_src"]
    if 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, flags=flags)
        config = NetworkConfig(indent=2, contents=contents)
        if module.params["backup"]:
            result["__backup__"] = contents

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

        commit = not module.check_mode
        candidate = get_candidate(module)
        running = get_running_config(module, contents, flags=flags)
        if replace_src:
            commands = candidate.split("\n")
            result["commands"] = result["updates"] = commands
            if commit:
                load_config(module, commands, replace=replace_src)

            result["changed"] = True
        else:
            try:
                response = connection.get_diff(
                    candidate=candidate,
                    running=running,
                    diff_match=match,
                    diff_ignore_lines=diff_ignore_lines,
                    path=path,
                    diff_replace=replace,
                )
            except ConnectionError as exc:
                module.fail_json(
                    msg=to_text(exc, errors="surrogate_then_replace"))

            config_diff = response["config_diff"]
            if config_diff:
                commands = config_diff.split("\n")

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

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

                result["commands"] = commands
                result["updates"] = commands

                if commit:
                    load_config(module, commands, replace=replace_src)

                result["changed"] = True

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

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

        running_config = NetworkConfig(indent=2,
                                       contents=output[0],
                                       ignore_lines=diff_ignore_lines)
        startup_config = NetworkConfig(indent=2,
                                       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=2,
                                       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 = startup_config.config_text

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

        if contents is not None:
            base_config = NetworkConfig(indent=2,
                                        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
Exemple #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'),
        route_targets=dict(type='list',
                           elements='dict',
                           options=dict(
                               rt=dict(type='str'),
                               direction=dict(
                                   choices=['import', 'export', 'both'],
                                   default='both'),
                               state=dict(choices=['present', 'absent'],
                                          default='present'),
                           )),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

    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':
        rt_commands = list()

        if not current:
            commands.append('address-family %s unicast' % module.params['afi'])
            current = ''

        have_auto_evpn = 'route-target both auto evpn' in current
        if module.params['route_target_both_auto_evpn'] is not None:
            want_auto_evpn = bool(module.params['route_target_both_auto_evpn'])
            if want_auto_evpn and not have_auto_evpn:
                commands.append('route-target both auto evpn')
            elif have_auto_evpn and not want_auto_evpn:
                commands.append('no route-target both auto evpn')

        if module.params['route_targets'] is not None:
            for rt in module.params['route_targets']:
                if rt.get('direction') == 'both' or not rt.get('direction'):
                    rt_commands = match_current_rt(rt, 'import', current,
                                                   rt_commands)
                    rt_commands = match_current_rt(rt, 'export', current,
                                                   rt_commands)
                else:
                    rt_commands = match_current_rt(rt, rt.get('direction'),
                                                   current, rt_commands)

        if rt_commands:
            commands.extend(rt_commands)

        if commands and current:
            commands.insert(0,
                            'address-family %s unicast' % module.params['afi'])

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

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

    commands = list()
    candidate = get_candidate(module)

    if any((module.params['lines'], module.params['src'])):
        if match != 'none':
            config = get_running_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 configobjs:
            commands = dumps(configobjs, 'commands')
            if ((isinstance((module.params['lines']), list)) and (isinstance(
                (module.params['lines'][0]), dict))
                    and (set(['prompt', 'answer']).issubset(
                        module.params['lines'][0]))):

                cmd = {
                    'command': commands,
                    'prompt': module.params['lines'][0]['prompt'],
                    'answer': module.params['lines'][0]['answer']
                }
                commands = [module.jsonify(cmd)]
            else:
                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)

            result['changed'] = True
            result['commands'] = commands
            result['updates'] = commands

    if module.params['save']:
        result['changed'] = True
        if not module.check_mode:
            cmd = {
                r'command': 'copy running-config startup-config',
                r'prompt': r'\[confirm yes/no\]:\s?$',
                'answer': 'yes'
            }
            run_commands(module, [cmd])
            result['saved'] = True
        else:
            module.warn('Skipping command `copy running-config startup-config`'
                        'due to check_mode.  Configuration not copied to '
                        'non-volatile storage')

    module.exit_json(**result)
Exemple #18
0
def main():
    """ main entry point for module execution
    """
    backup_spec = dict(filename=dict(), dir_path=dict(type='path'))

    argument_spec = dict(
        src=dict(type='path'),
        lines=dict(aliases=['commands'], type='list'),
        parents=dict(type='list'),
        before=dict(type='list'),
        after=dict(type='list'),
        match=dict(default='line', choices=['line', 'strict', 'exact',
                                            'none']),
        replace=dict(default='line', choices=['line', 'block']),
        running_config=dict(aliases=['config']),
        intended_config=dict(),
        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=['running', 'startup', 'intended']),
        diff_ignore_lines=dict(type='list'),
    )

    argument_spec.update(aoscx_argument_spec)

    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)

    warnings = list()
    aoscx_check_args(module, warnings)
    result = {'changed': False, 'warnings': warnings}

    config = None

    if module.params['diff_against'] is not None:
        module._diff = True

    if module.params['backup'] or (module._diff and
                                   module.params['diff_against'] == 'running'):
        contents = get_config(module)
        config = NetworkConfig(contents=contents)
        if module.params['backup']:
            result['__backup__'] = contents
            result['backup_options'] = module.params['backup_options']
            if module.params['backup_options']:
                if 'dir_path' in module.params['backup_options']:
                    dir_path = module.params['backup_options']['dir_path']
                else:
                    dir_path = ""
                if 'filename' in module.params['backup_options']:
                    filename = module.params['backup_options']['filename']
                else:
                    filename = "backup.cfg"

                with open(dir_path + '/' + filename, 'w') as backupfile:
                    backupfile.write(contents)
                    backupfile.write("\n")

    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 diff_ignore_lines is None:
        diff_ignore_lines = []

    diff_ignore_lines.append("Current configuration:")
    diff_ignore_lines.append("Startup configuration:")

    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(contents=output[0],
                                       ignore_lines=diff_ignore_lines)
        startup_config = NetworkConfig(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':
        if 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(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':
            with open(module.params['intended_config'], 'r') as intended_file:
                contents = intended_file.read()
        if contents is not None:
            base_config = NetworkConfig(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)
Exemple #19
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        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']),
        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'),

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

    # argument_spec.update(icx_argument_spec)

    mutually_exclusive = [('lines', 'src'), ('parents', '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
    run_commands(module, 'skip')
    diff_ignore_lines = module.params['diff_ignore_lines']
    config = None
    contents = None
    flags = None if module.params['defaults'] else []
    connection = get_connection(module)

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

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

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

        config_diff = response['config_diff']
        banner_diff = response['banner_diff']

        if config_diff or banner_diff:
            commands = config_diff.split('\n')

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

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

            result['commands'] = commands
            result['updates'] = commands
            result['banners'] = banner_diff

            # send the configuration commands to the device and merge
            # them with the current running config
            if not module.check_mode:
                if commands:
                    edit_config_or_macro(connection, commands)
                if banner_diff:
                    connection.edit_banner(candidate=json.dumps(banner_diff),
                                           multiline_delimiter=module.
                                           params['multiline_delimiter'])

            result['changed'] = True

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

    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 configuration'])

        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

        # 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 configuration')
                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 #20
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))

    argument_spec.update(dellos10_argument_spec)

    mutually_exclusive = [('lines', 'src'), ('parents', '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']:
        if not module.check_mode:
            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)
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        src=dict(type='path'),

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

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

        match=dict(default='line', choices=['line', 'none']),

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

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

        # save is deprecated as of 2.7, use save_when instead
        save=dict(type='bool', default=False, removed_in_version='2.11'),
        save_when=dict(choices=['always', 'never', 'changed'], default='never'),

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

    argument_spec.update(aireos_argument_spec)

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

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

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

        candidate = get_candidate(module)

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

    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'] == 'changed' and result['changed']:
        save_config(module, result)

    if module._diff:
        output = run_commands(module, 'show run-config commands')
        contents = output[0]

        # 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'] == '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 present(self):
        result = dict(changed=False)
        config = None
        contents = None

        if self.want.backup or (self.module._diff
                                and self.want.diff_against == 'running'):
            contents = self.read_current_from_device()
            config = NetworkConfig(indent=1, contents=contents)
            if self.want.backup:
                # The backup file is created in the bigip_imish_config action plugin. Refer
                # to that if you have questions. The key below is removed by the action plugin.
                result['__backup__'] = contents

        if any((self.want.src, self.want.lines)):
            match = self.want.match
            replace = self.want.replace

            candidate = self.get_candidate()
            running = self.get_running_config(contents)

            response = self.get_diff(
                candidate=candidate,
                running=running,
                diff_match=match,
                diff_ignore_lines=self.want.diff_ignore_lines,
                path=self.want.parents,
                diff_replace=replace)

            config_diff = response['config_diff']

            if config_diff:
                commands = config_diff.split('\n')

                if self.want.before:
                    commands[:0] = self.want.before

                if self.want.after:
                    commands.extend(self.want.after)

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

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

                result['changed'] = True

        running_config = self.want.running_config
        startup_config = None

        if self.want.save_when == 'always':
            self.save_config(result)
        elif self.want.save_when == 'modified':
            output = self.execute_show_commands(
                ['show running-config', 'show startup-config'])

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

            if running_config.sha1 != startup_config.sha1:
                self.save_config(result)
        elif self.want.save_when == 'changed' and result['changed']:
            self.save_on_device()

        if self.module._diff:
            if not running_config:
                output = self.execute_show_commands('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=self.want.diff_ignore_lines)

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

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

            elif self.want.diff_against == 'intended':
                contents = self.want.intended_config

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

                if running_config.sha1 != base_config.sha1:
                    if self.want.diff_against == 'intended':
                        before = running_config
                        after = base_config
                    elif self.want.diff_against in ('startup', 'running'):
                        before = base_config
                        after = running_config

                    result.update({
                        'changed': True,
                        'diff': {
                            'before': str(before),
                            'after': str(after)
                        }
                    })
        self.changes.update(result)
        return result['changed']
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
Exemple #24
0
def get_device_config(module):
    contents = get_config(module)
    return NetworkConfig(indent=4, contents=contents)
Exemple #25
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)
Exemple #26
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        src=dict(type='path'),
        lines=dict(aliases=['commands'], type='list'),
        parents=dict(type='list'),
        before=dict(type='list'),
        after=dict(type='list'),
        match=dict(default='line', choices=['line', 'strict', 'exact',
                                            'none']),
        replace=dict(default='line', choices=['line', 'block', 'config']),
        defaults=dict(type='bool', default=False),
        backup=dict(type='bool', default=False),
        save_when=dict(choices=['always', 'never', 'modified', 'changed'],
                       default='never'),
        diff_against=dict(
            choices=['startup', 'session', 'intended', 'running'],
            default='session'),
        diff_ignore_lines=dict(type='list'),
        running_config=dict(aliases=['config']),
        intended_config=dict(),

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

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

    argument_spec.update(eos_argument_spec)

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

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

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

    warnings = list()
    check_args(module, warnings)

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

    config = None

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

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

        candidate = get_candidate(module)

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

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

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

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

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

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

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

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

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

            result['changed'] = True

    running_config = None
    startup_config = None

    diff_ignore_lines = module.params['diff_ignore_lines']

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

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

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

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

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

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

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

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

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

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

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

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

    module.exit_json(**result)
Exemple #27
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 #28
0
def find_diff(module, runn_config_before_changes):
    diff_ignore_lines = module.params['diff_ignore_lines']
    running_config = module.params['running_config']
    startup_config = None

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

    else:
        contents = running_config

    # recreate the object in order to process diff_ignore_lines
    running_config = NetworkConfig(indent=CFG_FILE_SUBCONFIG_INDENT,
                                   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 = runn_config_before_changes.config_text

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

    elif module.params['diff_against'] == 'intended':
        contents = module.params['intended_config']
    result_diff = {}
    if contents is not None:
        base_config = NetworkConfig(indent=CFG_FILE_SUBCONFIG_INDENT,
                                    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_diff = {
                'changed': True,
                'diff': {
                    'before': str(before),
                    'after': str(after)
                }
            }
    return result_diff