示例#1
0
def main():
    spec = dict(
        src=dict(type='path', required=True, aliases=['package']),
        version=dict(),
        reboot=dict(type='bool', default=True),
        no_copy=dict(default=False, type='bool'),
        force=dict(type='bool', default=False),
        transport=dict(default='netconf', choices=['netconf'])
    )

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

    if not HAS_SW:
        module.fail_json(msg='Missing jnpr.junos.utils.sw module')

    result = dict(changed=False)

    do_upgrade = module.params['force'] or False
    if not module.params['force']:
        has_ver = module.connection.get_facts().get('version')
        wants_ver = module.params['version']
        do_upgrade = has_ver != wants_ver

    if do_upgrade:
        if not module.check_mode:
            install_package(module)
        result['changed'] = True

    module.exit_json(**result)
示例#2
0
def main():
    """ Main entry point for AnsibleModule
    """
    spec = dict(
        config=dict(type='bool'),
        config_format=dict(default='text', choices=['xml', 'text']),
        transport=dict(default='netconf', choices=['netconf'])
    )

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

    result = dict(changed=False)

    facts = module.connection.get_facts()

    if '2RE' in facts:
        facts['has_2RE'] = facts['2RE']
        del facts['2RE']

    facts['version_info'] = dict(facts['version_info'])

    if module.params['config'] is True:
        config_format = module.params['config_format']
        resp_config = module.config.get_config(config_format=config_format)

        if config_format in ['text']:
            facts['config'] = resp_config
        elif config_format == "xml":
            facts['config'] = xml_to_string(resp_config)
            facts['config_json'] = xml_to_json(resp_config)

    result['ansible_facts'] = facts
    module.exit_json(**result)
示例#3
0
def main():
    spec = dict(
        commands=dict(type='list', required=True),
        wait_for=dict(type='list'),
        retries=dict(default=10, type='int'),
        interval=dict(default=1, type='int')
    )

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

    commands = module.params['commands']
    conditionals = module.params['wait_for'] or list()

    warnings = list()

    runner = CommandRunner(module)

    for cmd in commands:
        if module.check_mode and not cmd.startswith('show'):
            warnings.append('only show commands are supported when using '
                            'check mode, not executing `%s`' % cmd)
        else:
            if cmd.startswith('conf'):
                module.fail_json(msg='dellos10_command does not support running '
                                     'config mode commands.  Please use '
                                     'dellos10_config instead')
            runner.add_command(cmd)

    for item in conditionals:
        runner.add_conditional(item)

    runner.retries = module.params['retries']
    runner.interval = module.params['interval']

    try:
        runner.run()
    except FailedConditionsError:
        exc = get_exception()
        module.fail_json(msg=str(exc), failed_conditions=exc.failed_conditions)
    except NetworkError:
        exc = get_exception()
        module.fail_json(msg=str(exc))

    result = dict(changed=False)

    result['stdout'] = list()
    for cmd in commands:
        try:
            output = runner.get_command(cmd)
        except ValueError:
            output = 'command not executed due to check_mode, see warnings'
        result['stdout'].append(output)


    result['warnings'] = warnings
    result['stdout_lines'] = list(to_lines(result['stdout']))

    module.exit_json(**result)
示例#4
0
def main():
    """ main entry point for module execution
    """

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

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

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

    replace = module.params['replace']

    commands = list()
    running = None

    result = dict(changed=False)

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

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

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

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

    result['updates'] = commands
    module.exit_json(**result)
示例#5
0
def main():
    """ main entry point for module execution
    """

    argument_spec = dict(
        http=dict(aliases=['enable_http'], default=False, type='bool', setter='set_protocol_http'),
        http_port=dict(default=80, type='int', setter='set_protocol_http'),

        https=dict(aliases=['enable_https'], default=True, type='bool', setter='set_protocol_https'),
        https_port=dict(default=443, type='int', setter='set_protocol_https'),

        local_http=dict(aliases=['enable_local_http'], default=False, type='bool', setter='set_local_http'),
        local_http_port=dict(default=8080, type='int', setter='set_local_http'),

        socket=dict(aliases=['enable_socket'], default=False, type='bool'),

        vrf=dict(default='default'),

        config=dict(),

        # Only allow use of transport cli when configuring eAPI
        transport=dict(default='cli', choices=['cli']),

        state=dict(default='started', choices=['stopped', 'started']),
    )

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

    state = module.params['state']

    result = dict(changed=False)

    commands = list()
    instance = get_instance(module)

    invoke(state, module, instance, commands)

    try:
        load(module, instance, commands, result)
    except NetworkError:
        exc = get_exception()
        module.fail_json(msg=str(exc), **exc.kwargs)

    collect_facts(module, result)
    clean_result(result)

    module.exit_json(**result)
示例#6
0
def main():
    spec = dict(gather_subset=dict(default=["!config"], type="list"))
    module = NetworkModule(argument_spec=spec, supports_check_mode=True)

    gather_subset = module.params["gather_subset"]

    runable_subsets = set()
    exclude_subsets = set()

    for subset in gather_subset:
        if subset == "all":
            runable_subsets.update(VALID_SUBSETS)
            continue

        if subset.startswith("!"):
            subset = subset[1:]
            if subset == "all":
                exclude_subsets.update(VALID_SUBSETS)
                continue
            exclude = True
        else:
            exclude = False

        if subset not in VALID_SUBSETS:
            module.fail_json(msg="Bad subset")

        if exclude:
            exclude_subsets.add(subset)
        else:
            runable_subsets.add(subset)

    if not runable_subsets:
        runable_subsets.update(VALID_SUBSETS)

    runable_subsets.difference_update(exclude_subsets)
    runable_subsets.add("default")

    facts = dict()
    facts["gather_subset"] = list(runable_subsets)

    runner = CommandRunner(module)
    instances = list()
    for key in runable_subsets:
        instances.append(FACT_SUBSETS[key](runner))
    runner.run()

    try:
        for inst in instances:
            inst.populate()
            facts.update(inst.facts)
    except Exception:
        module.exit_json(out=module.from_json(runner.items))

    ansible_facts = dict()
    for key, value in facts.items():
        key = "ansible_net_%s" % key
        ansible_facts[key] = value

    module.exit_json(ansible_facts=ansible_facts)
示例#7
0
def main():

    argument_spec = dict(
        lines=dict(aliases=['commands'], required=True, type='list'),
        before=dict(type='list'),
        after=dict(type='list'),
        match=dict(default='line', choices=['line', 'strict', 'exact']),
        replace=dict(default='line', choices=['line', 'block']),
        force=dict(default=False, type='bool'),
        config=dict()
    )

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

    lines = module.params['lines']

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

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

    result = dict(changed=False)

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

    acl_name = parse_acl_name(module)

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

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

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

    result['updates'] = commands

    module.exit_json(**result)
示例#8
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=dict(),
        defaults=dict(type='bool', default=False),
        passwords=dict(type='bool', default=False),

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

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

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

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

    result = dict(changed=False)

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

    try:
        run(module, result)
    except NetworkError:
        exc = get_exception()
        module.fail_json(msg=str(exc), **exc.kwargs)

    module.exit_json(**result)
示例#9
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        lines=dict(type='list'),

        src=dict(type='path'),
        src_format=dict(choices=['xml', 'text', 'set', 'json']),

        # update operations
        replace=dict(default=False, type='bool'),
        confirm=dict(default=0, type='int'),
        comment=dict(default=DEFAULT_COMMENT),

        # config operations
        backup=dict(type='bool', default=False),
        rollback=dict(type='int'),
        zeroize=dict(default=False, type='bool'),

        transport=dict(default='netconf', choices=['netconf'])
    )

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

    required_if = [('replace', True, ['src'])]

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

    result = dict(changed=False)

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

    try:
        run(module, result)
    except NetworkError:
        exc = get_exception()
        module.fail_json(msg=str(exc), **exc.kwargs)

    module.exit_json(**result)
示例#10
0
def main():
    """ main entry point for module execution
    """

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

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

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

    result = dict(changed=False)

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

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

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

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

    result['updates'] = commands
    module.exit_json(**result)
示例#11
0
def main():
    """ main entry point for module execution
    """

    argument_spec = dict(
        src=dict(),
        force=dict(default=False, type='bool'),
        backup=dict(default=False, type='bool'),
        config=dict(),
    )
    mutually_exclusive = [('config', 'backup'), ('config', 'force')]

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

    result = dict(changed=False)
    candidate = Dellos6NetworkConfig(contents=module.params['src'], indent=0)

    contents = get_config(module)
    if contents:
        config = Dellos6NetworkConfig(contents=contents[0], indent=0)
        result['_backup'] = contents[0]
    commands = list()

    if not module.params['force']:
        commands = dumps(candidate.difference(config), 'commands')
    else:
        commands = str(candidate)

    if commands:
        commands = commands.split('\n')
        if not module.check_mode:
            response = module.config(commands)
            result['responses'] = response
        result['changed'] = True

    result['updates'] = commands
    module.exit_json(**result)
示例#12
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']),

        # this argument is deprecated in favor of setting match: none
        # it will be removed in a future version
        force=dict(default=False, type='bool'),
        config=dict(),
        defaults=dict(type='bool', default=False),
        backup=dict(type='bool', default=False),
        save=dict(type='bool', default=False),
    )

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

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

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

    if module.params['force'] is True:
        module.params['match'] = 'none'

    warnings = list()
    check_args(module, warnings)

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

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

    try:
        run(module, result)
    except NetworkError:
        exc = get_exception()
        module.fail_json(msg=str(exc), **exc.kwargs)

    module.exit_json(**result)
    def __init__(self, **kwargs):
        """ Class init """

        # module
        argument_spec = kwargs["argument_spec"]
        self.spec = argument_spec
        self.module = NetworkModule(
            argument_spec=self.spec, connect_on_load=False, supports_check_mode=True)

        # config
        self.cur_cfg = dict()

        # module args
        self.state = self.module.params['state']
        self.contact = self.module.params['contact']

        # state
        self.changed = False
        self.updates_cmd = list()
        self.results = dict()
        self.proposed = dict()
        self.existing = dict()
        self.end_state = dict()
示例#14
0
def main():

    argument_spec = dict(
        src=dict(required=True, type='path'),
        confirm=dict(default=0, type='int'),
        comment=dict(default=DEFAULT_COMMENT),
        action=dict(default='merge', choices=['merge', 'overwrite', 'replace']),
        config_format=dict(choices=['text', 'set', 'xml']),
        backup=dict(default=False, type='bool'),
        transport=dict(default='netconf', choices=['netconf'])
    )

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

    comment = module.params['comment']
    confirm = module.params['confirm']
    commit = not module.check_mode

    replace = False
    overwrite = False

    action = module.params['action']
    if action == 'overwrite':
        overwrite = True
    elif action == 'replace':
        replace = True

    src = module.params['src']
    fmt = module.params['config_format']

    if action == 'overwrite' and fmt == 'set':
        module.fail_json(msg="overwrite cannot be used when format is "
            "set per junos-pyez documentation")

    results = dict(changed=False)
    results['_backup'] = unicode(module.config.get_config()).strip()

    try:
        diff = module.config.load_config(src, commit=commit, replace=replace,
                confirm=confirm, comment=comment, config_format=fmt)

        if diff:
            results['changed'] = True
            results['diff'] = dict(prepared=diff)
    except NetworkError:
        exc = get_exception()
        module.fail_json(msg=str(exc), **exc.kwargs)

    module.exit_json(**results)
示例#15
0
def main():
    """ main entry point for module execution
    """

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

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

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

    replace = module.params['replace']

    commands = list()
    running = None

    result = dict(changed=False)

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

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

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

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

    result['updates'] = commands
    module.exit_json(**result)
示例#16
0
def main():
    """ main entry point for module execution
    """

    argument_spec = dict(
        http=dict(aliases=['enable_http'],
                  default=False,
                  type='bool',
                  setter='set_protocol_http'),
        http_port=dict(default=80, type='int', setter='set_protocol_http'),
        https=dict(aliases=['enable_https'],
                   default=True,
                   type='bool',
                   setter='set_protocol_https'),
        https_port=dict(default=443, type='int', setter='set_protocol_https'),
        local_http=dict(aliases=['enable_local_http'],
                        default=False,
                        type='bool',
                        setter='set_local_http'),
        local_http_port=dict(default=8080, type='int',
                             setter='set_local_http'),
        socket=dict(aliases=['enable_socket'], default=False, type='bool'),
        vrf=dict(default='default'),
        config=dict(),

        # Only allow use of transport cli when configuring eAPI
        transport=dict(default='cli', choices=['cli']),
        state=dict(default='started', choices=['stopped', 'started']),
    )

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

    state = module.params['state']

    result = dict(changed=False)

    commands = list()
    instance = get_instance(module)

    invoke(state, module, instance, commands)

    try:
        load(module, instance, commands, result)
    except NetworkError:
        exc = get_exception()
        module.fail_json(msg=str(exc), **exc.kwargs)

    collect_facts(module, result)
    clean_result(result)

    module.exit_json(**result)
示例#17
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=dict(),
        defaults=dict(type='bool', default=False),
        backup=dict(type='bool', default=False),
        save=dict(type='bool', default=False),
    )

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

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

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

    warnings = list()

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

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

    try:
        run(module, result)
    except NetworkError:
        exc = get_exception()
        config_fail(module, msg=get_cli_exception(exc), **exc.kwargs)

    config_exit(module, **result)
示例#18
0
def main():
    """main entry point for module execution
    """

    argument_spec = dict(netconf_port=dict(type='int',
                                           default=830,
                                           aliases=['listens_on']),
                         state=dict(default='present',
                                    choices=['present', 'absent']),
                         transport=dict(default='cli', choices=['cli']))

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

    state = module.params['state']
    port = module.params['netconf_port']

    result = dict(changed=False)

    instance = get_instance(module)

    if state == 'present' and instance.get('state') == 'absent':
        commands = 'set system services netconf ssh port %s' % port
    elif state == 'present' and port != instance.get('port'):
        commands = 'set system services netconf ssh port %s' % port
    elif state == 'absent' and instance.get('state') == 'present':
        commands = 'delete system services netconf'
    else:
        commands = None

    if commands:
        if not module.check_mode:
            try:
                comment = 'configuration updated by junos_netconf'
                module.config(commands, comment=comment)
            except NetworkError:
                exc = get_exception()
                module.fail_json(msg=str(exc), **exc.kwargs)
        result['changed'] = True
        result['commands'] = commands

    module.exit_json(**result)
示例#19
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        lines=dict(type='list'),

        src=dict(type='path'),
        src_format=dict(choices=['xml', 'text', 'set', 'json']),

        # update operations
        update=dict(default='merge', choices=['merge', 'overwrite', 'replace']),
        replace=dict(default=False, type='bool'),

        confirm=dict(default=0, type='int'),
        comment=dict(default=DEFAULT_COMMENT),

        # config operations
        backup=dict(type='bool', default=False),
        rollback=dict(type='int'),
        zeroize=dict(default=False, type='bool'),

        transport=dict(default='netconf', choices=['netconf'])
    )

    mutually_exclusive = [('lines', 'rollback'), ('lines', 'zeroize'),
                          ('rollback', 'zeroize'), ('lines', 'src'),
                          ('src', 'zeroize'), ('src', 'rollback'),
                          ('update', 'replace')]

    required_if = [('replace', True, ['src']),
                   ('update', 'merge', ['src', 'lines'], True),
                   ('update', 'overwrite', ['src', 'lines'], True),
                   ('update', 'replace', ['src', 'lines'], True)]

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

    result = dict(changed=False)

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

    try:
        run(module, result)
    except NetworkError:
        exc = get_exception()
        module.fail_json(msg=str(exc), **exc.kwargs)

    module.exit_json(**result)
示例#20
0
def main():

    argument_spec = dict(lines=dict(aliases=['commands'],
                                    required=True,
                                    type='list'),
                         before=dict(type='list'),
                         after=dict(type='list'),
                         match=dict(default='line',
                                    choices=['line', 'strict', 'exact']),
                         replace=dict(default='line',
                                      choices=['line', 'block']),
                         force=dict(default=False, type='bool'),
                         config=dict())

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

    lines = module.params['lines']

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

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

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

    module.filter = check_input_acl(lines, module)

    if not module.params['force']:
        contents = get_config(module)
        config = NetworkConfig(indent=1, contents=contents)
        commands = candidate.difference(config)
        commands = dumps(commands, 'commands').split('\n')
    else:
        commands = str(candidate).split('\n')

    if commands:
        if not module.check_mode:
            commands = [str(c) for c in commands if c]
            response = module.config(commands)
            result['responses'] = response
        result['changed'] = True

    result['updates'] = commands

    module.exit_json(**result)
示例#21
0
def main():
    """main entry point for module execution
    """

    argument_spec = dict(
        netconf_port=dict(type='int', default=830, aliases=['listens_on']),
        state=dict(default='present', choices=['present', 'absent']),
        transport=dict(default='cli', choices=['cli'])
    )

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

    state = module.params['state']
    port = module.params['netconf_port']

    result = dict(changed=False)

    instance = get_instance(module)

    if state == 'present' and instance.get('state') == 'absent':
        commands = 'set system services netconf ssh port %s' % port
    elif state == 'present' and port != instance.get('port'):
        commands = 'set system services netconf ssh port %s' % port
    elif state == 'absent' and instance.get('state') == 'present':
        commands = 'delete system services netconf'
    else:
        commands = None

    if commands:
        if not module.check_mode:
            try:
                comment = 'configuration updated by junos_netconf'
                module.config(commands, comment=comment)
            except NetworkError:
                exc = get_exception()
                module.fail_json(msg=str(exc), **exc.kwargs)
        result['changed'] = True
        result['commands'] = commands

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

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

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

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

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

    result = dict(changed=False)

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

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

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

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

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

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

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

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

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

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

        result['updates'] = commands

    module.exit_json(**result)
class EthTrunk(object):
    """
    Manages Eth-Trunk interfaces.
    """

    def __init__(self, argument_spec):
        self.spec = argument_spec
        self.module = None
        self.netconf = None
        self.__init_module__()

        # module input info
        self.trunk_id = self.module.params['trunk_id']
        self.mode = self.module.params['mode']
        self.min_links = self.module.params['min_links']
        self.hash_type = self.module.params['hash_type']
        self.members = self.module.params['members']
        self.state = self.module.params['state']
        self.force = self.module.params['force']

        # host info
        self.host = self.module.params['host']
        self.username = self.module.params['username']
        self.port = self.module.params['port']

        # state
        self.changed = False
        self.updates_cmd = list()
        self.results = dict()
        self.proposed = dict()
        self.existing = dict()
        self.end_state = dict()

        # interface info
        self.trunk_info = dict()

        # init netconf connect
        self.__init_netconf__()

    def __init_module__(self):
        """ init module """

        self.module = NetworkModule(
            argument_spec=self.spec, supports_check_mode=True)

    def __init_netconf__(self):
        """ init netconf """

        if not HAS_NCCLIENT:
            raise Exception("the ncclient library is required")

        self.netconf = get_netconf(host=self.host,
                                   port=self.port,
                                   username=self.username,
                                   password=self.module.params['password'])
        if not self.netconf:
            self.module.fail_json(msg='Error: netconf init failed')

    def check_response(self, con_obj, xml_name):
        """Check if response message is already succeed."""

        xml_str = con_obj.xml
        if "<ok/>" not in xml_str:
            self.module.fail_json(msg='Error: %s failed.' % xml_name)

    def netconf_get_config(self, xml_str):
        """ netconf get config """

        try:
            con_obj = self.netconf.get_config(filter=xml_str)
        except RPCError:
            err = sys.exc_info()[1]
            self.module.fail_json(msg='Error: %s' % err.message.replace("\r\n", ""))

        return con_obj

    def netconf_set_config(self, xml_str, xml_name):
        """ netconf set config """

        try:
            con_obj = self.netconf.set_config(config=xml_str)
            self.check_response(con_obj, xml_name)
        except RPCError:
            err = sys.exc_info()[1]
            self.module.fail_json(msg='Error: %s' % err.message.replace("\r\n", ""))

        return con_obj

    def netconf_set_action(self, xml_str, xml_name):
        """ netconf set config """

        try:
            con_obj = self.netconf.execute_action(action=xml_str)
            self.check_response(con_obj, xml_name)
        except RPCError:
            err = sys.exc_info()[1]
            self.module.fail_json(msg='Error: %s' % err.message.replace("\r\n", ""))

        return con_obj

    def get_trunk_dict(self, trunk_id):
        """ get one interface attributes dict."""

        trunk_info = dict()
        conf_str = CE_NC_GET_TRUNK % trunk_id
        con_obj = self.netconf_get_config(conf_str)

        if "<data/>" in con_obj.xml:
            return trunk_info

        # get trunk base info
        base = re.findall(
            r'.*<ifName>(.*)</ifName>.*\s*'
            r'<minUpNum>(.*)</minUpNum>.*\s*'
            r'<maxUpNum>(.*)</maxUpNum>.*\s*'
            r'<trunkType>(.*)</trunkType>.*\s*'
            r'<hashType>(.*)</hashType>.*\s*'
            r'<workMode>(.*)</workMode>.*\s*'
            r'<upMemberIfNum>(.*)</upMemberIfNum>.*\s*'
            r'<memberIfNum>(.*)</memberIfNum>.*', con_obj.xml)

        if base:
            trunk_info = dict(ifName=base[0][0],
                              trunkId=base[0][0].lower().replace("eth-trunk", "").replace(" ", ""),
                              minUpNum=base[0][1],
                              maxUpNum=base[0][2],
                              trunkType=base[0][3],
                              hashType=base[0][4],
                              workMode=base[0][5],
                              upMemberIfNum=base[0][6],
                              memberIfNum=base[0][7])

        # get trunk member interface info
        member = re.findall(
            r'.*<memberIfName>(.*)</memberIfName>.*\s*'
            r'<memberIfState>(.*)</memberIfState>.*', con_obj.xml)
        trunk_info["TrunkMemberIfs"] = list()

        for mem in member:
            trunk_info["TrunkMemberIfs"].append(
                dict(memberIfName=mem[0], memberIfState=mem[1]))

        return trunk_info

    def is_member_exist(self, ifname):
        """is trunk member exist"""

        if not self.trunk_info["TrunkMemberIfs"]:
            return False

        for mem in self.trunk_info["TrunkMemberIfs"]:
            if ifname.replace(" ", "").upper() == mem["memberIfName"].replace(" ", "").upper():
                return True

        return False

    def get_mode_xml_str(self):
        """trunk mode netconf xml fromat string"""

        return MODE_CLI2XML.get(self.mode)

    def get_hash_type_xml_str(self):
        """trunk hash type netconf xml format string"""

        return HASH_CLI2XML.get(self.hash_type)

    def create_eth_trunk(self):
        """Create Eth-Trunk interface"""

        xml_str = CE_NC_XML_CREATE_TRUNK % self.trunk_id
        self.updates_cmd.append("interface Eth-Trunk %s" % self.trunk_id)

        if self.hash_type:
            self.updates_cmd.append("load-balance %s" % self.hash_type)
            xml_str += CE_NC_XML_MERGE_HASHTYPE % (self.trunk_id, self.get_hash_type_xml_str())

        if self.mode:
            self.updates_cmd.append("mode %s" % self.mode)
            xml_str += CE_NC_XML_MERGE_WORKMODE % (self.trunk_id, self.get_mode_xml_str())

        if self.min_links:
            self.updates_cmd.append("least active-linknumber %s" % self.min_links)
            xml_str += CE_NC_XML_MERGE_MINUPNUM % (self.trunk_id, self.min_links)

        if self.members:
            mem_xml = ""
            for mem in self.members:
                mem_xml += CE_NC_XML_MERGE_MEMBER % mem.upper()
                self.updates_cmd.append("interface %s" % mem)
                self.updates_cmd.append("eth-trunk %s" % self.trunk_id)
            xml_str += CE_NC_XML_BUILD_MEMBER_CFG % (self.trunk_id, mem_xml)
        cfg_xml = CE_NC_XML_BUILD_TRUNK_CFG % xml_str
        self.netconf_set_config(cfg_xml, "CREATE_TRUNK")
        self.changed = True

    def delete_eth_trunk(self):
        """Delete Eth-Trunk interface and remove all member"""

        if not self.trunk_info:
            return

        xml_str = ""
        mem_str = ""
        if self.trunk_info["TrunkMemberIfs"]:
            for mem in self.trunk_info["TrunkMemberIfs"]:
                mem_str += CE_NC_XML_DELETE_MEMBER % mem["memberIfName"]
                self.updates_cmd.append("interface %s" % mem["memberIfName"])
                self.updates_cmd.append("undo eth-trunk")
            if mem_str:
                xml_str += CE_NC_XML_BUILD_MEMBER_CFG % (self.trunk_id, mem_str)

        xml_str += CE_NC_XML_DELETE_TRUNK % self.trunk_id
        self.updates_cmd.append("undo interface Eth-Trunk %s" % self.trunk_id)
        cfg_xml = CE_NC_XML_BUILD_TRUNK_CFG % xml_str
        self.netconf_set_config(cfg_xml, "DELETE_TRUNK")
        self.changed = True

    def remove_member(self):
        """delete trunk member"""

        if not self.members:
            return

        change = False
        mem_xml = ""
        xml_str = ""
        for mem in self.members:
            if self.is_member_exist(mem):
                mem_xml += CE_NC_XML_DELETE_MEMBER % mem.upper()
                self.updates_cmd.append("interface %s" % mem)
                self.updates_cmd.append("undo eth-trunk")
        if mem_xml:
            xml_str += CE_NC_XML_BUILD_MEMBER_CFG % (self.trunk_id, mem_xml)
            change = True

        if not change:
            return

        cfg_xml = CE_NC_XML_BUILD_TRUNK_CFG % xml_str
        self.netconf_set_config(cfg_xml, "REMOVE_TRUNK_MEMBER")
        self.changed = True

    def merge_eth_trunk(self):
        """Create or merge Eth-Trunk"""

        change = False
        xml_str = ""
        self.updates_cmd.append("interface Eth-Trunk %s" % self.trunk_id)
        if self.hash_type and self.get_hash_type_xml_str() != self.trunk_info["hashType"]:
            self.updates_cmd.append("load-balance %s" %
                                    self.hash_type)
            xml_str += CE_NC_XML_MERGE_HASHTYPE % (
                self.trunk_id, self.get_hash_type_xml_str())
            change = True
        if self.min_links and self.min_links != self.trunk_info["minUpNum"]:
            self.updates_cmd.append(
                "least active-linknumber %s" % self.min_links)
            xml_str += CE_NC_XML_MERGE_MINUPNUM % (
                self.trunk_id, self.min_links)
            change = True
        if self.mode and self.get_mode_xml_str() != self.trunk_info["workMode"]:
            self.updates_cmd.append("mode %s" % self.mode)
            xml_str += CE_NC_XML_MERGE_WORKMODE % (
                self.trunk_id, self.get_mode_xml_str())
            change = True

        if not change:
            self.updates_cmd.pop()   # remove 'interface Eth-Trunk' command

        # deal force:
        # When true it forces Eth-Trunk members to match
        # what is declared in the members param.
        if self.force == "true" and self.trunk_info["TrunkMemberIfs"]:
            mem_xml = ""
            for mem in self.trunk_info["TrunkMemberIfs"]:
                if not self.members or mem["memberIfName"].replace(" ", "").upper() not in self.members:
                    mem_xml += CE_NC_XML_DELETE_MEMBER % mem["memberIfName"]
                    self.updates_cmd.append("interface %s" % mem["memberIfName"])
                    self.updates_cmd.append("undo eth-trunk")
            if mem_xml:
                xml_str += CE_NC_XML_BUILD_MEMBER_CFG % (self.trunk_id, mem_xml)
                change = True

        if self.members:
            mem_xml = ""
            for mem in self.members:
                if not self.is_member_exist(mem):
                    mem_xml += CE_NC_XML_MERGE_MEMBER % mem.upper()
                    self.updates_cmd.append("interface %s" % mem)
                    self.updates_cmd.append("eth-trunk %s" % self.trunk_id)
            if mem_xml:
                xml_str += CE_NC_XML_BUILD_MEMBER_CFG % (
                    self.trunk_id, mem_xml)
                change = True

        if not change:
            return

        cfg_xml = CE_NC_XML_BUILD_TRUNK_CFG % xml_str
        self.netconf_set_config(cfg_xml, "MERGE_TRUNK")
        self.changed = True

    def check_params(self):
        """Check all input params"""

        # trunk_id check
        if not self.trunk_id.isdigit():
            self.module.fail_json(msg='The parameter of trunk_id is invalid.')

        # min_links check
        if self.min_links and not self.min_links.isdigit():
            self.module.fail_json(msg='The parameter of min_links is invalid.')

        # members check and convert members to upper
        if self.members:
            for mem in self.members:
                if not get_interface_type(mem.replace(" ", "")):
                    self.module.fail_json(
                        msg='The parameter of members is invalid.')

            for mem_id in range(len(self.members)):
                self.members[mem_id] = self.members[mem_id].replace(" ", "").upper()

    def get_proposed(self):
        """get proposed info"""

        self.proposed["trunk_id"] = self.trunk_id
        self.proposed["mode"] = self.mode
        if self.min_links:
            self.proposed["min_links"] = self.min_links
        self.proposed["hash_type"] = self.hash_type
        if self.members:
            self.proposed["members"] = self.members
        self.proposed["state"] = self.state
        self.proposed["force"] = self.force

    def get_existing(self):
        """get existing info"""

        if not self.trunk_info:
            return

        self.existing["trunk_id"] = self.trunk_info["trunkId"]
        self.existing["min_links"] = self.trunk_info["minUpNum"]
        self.existing["hash_type"] = hash_type_xml_to_cli_str(self.trunk_info["hashType"])
        self.existing["mode"] = mode_xml_to_cli_str(self.trunk_info["workMode"])
        self.existing["members_detail"] = self.trunk_info["TrunkMemberIfs"]

    def get_end_state(self):
        """get end state info"""

        trunk_info = self.get_trunk_dict(self.trunk_id)
        if not trunk_info:
            return

        self.end_state["trunk_id"] = trunk_info["trunkId"]
        self.end_state["min_links"] = trunk_info["minUpNum"]
        self.end_state["hash_type"] = hash_type_xml_to_cli_str(trunk_info["hashType"])
        self.end_state["mode"] = mode_xml_to_cli_str(trunk_info["workMode"])
        self.end_state["members_detail"] = trunk_info["TrunkMemberIfs"]

    def work(self):
        """worker"""

        self.check_params()
        self.trunk_info = self.get_trunk_dict(self.trunk_id)
        self.get_existing()
        self.get_proposed()

        # deal present or absent
        if self.state == "present":
            if not self.trunk_info:
                # create
                self.create_eth_trunk()
            else:
                # merge trunk
                self.merge_eth_trunk()
        else:
            if self.trunk_info:
                if not self.members:
                    # remove all members and delete trunk
                    self.delete_eth_trunk()
                else:
                    # remove some trunk members
                    self.remove_member()
            else:
                self.module.fail_json(msg='Error: Eth-Trunk does not exist.')

        self.get_end_state()
        self.results['changed'] = self.changed
        self.results['proposed'] = self.proposed
        self.results['existing'] = self.existing
        self.results['end_state'] = self.end_state
        if self.changed:
            self.results['updates'] = self.updates_cmd
        else:
            self.results['updates'] = list()

        self.module.exit_json(**self.results)
    def init_module(self):
        """init module"""

        self.module = NetworkModule(
            argument_spec=self.spec, connect_on_load=False, supports_check_mode=True)
class VxlanArp(object):
    """
    Manages arp attributes of VXLAN.
    """

    def __init__(self, argument_spec):
        self.spec = argument_spec
        self.module = None
        self.init_module()

        # module input info
        self.evn_bgp = self.module.params['evn_bgp']
        self.evn_source_ip = self.module.params['evn_source_ip']
        self.evn_peer_ip = self.module.params['evn_peer_ip']
        self.evn_server = self.module.params['evn_server']
        self.evn_reflect_client = self.module.params['evn_reflect_client']
        self.vbdif_name = self.module.params['vbdif_name']
        self.arp_collect_host = self.module.params['arp_collect_host']
        self.host_collect_protocol = self.module.params[
            'host_collect_protocol']
        self.bridge_domain_id = self.module.params['bridge_domain_id']
        self.arp_suppress = self.module.params['arp_suppress']
        self.state = self.module.params['state']

        # host info
        self.host = self.module.params['host']
        self.username = self.module.params['username']
        self.port = self.module.params['port']

        # state
        self.config = ""  # current config
        self.changed = False
        self.updates_cmd = list()
        self.commands = list()
        self.results = dict()
        self.proposed = dict()
        self.existing = dict()
        self.end_state = dict()

    def init_module(self):
        """init module"""

        self.module = NetworkModule(
            argument_spec=self.spec, connect_on_load=False, supports_check_mode=True)

    def cli_load_config(self, commands):
        """load config by cli"""
        if not self.module.check_mode:
            try:
                self.module.config.load_config(commands)
            except NetworkError:
                err = get_cli_exception()
                self.module.fail_json(msg=err)

    def get_current_config(self):
        """get current configuration"""
        config = ""

        exp = " | ignore-case section include evn bgp|host collect protocol bgp"
        if self.vbdif_name:
            exp += "|^interface %s$" % self.vbdif_name

        if self.bridge_domain_id:
            exp += "|^bridge-domain %s$" % self.bridge_domain_id

        config = self.module.config.get_config(
            include_defaults=False, regular=exp)

        return config

    def cli_add_command(self, command, undo=False):
        """add command to self.update_cmd and self.commands"""

        if undo and command.lower() not in ["quit", "return"]:
            cmd = "undo " + command
        else:
            cmd = command

        self.commands.append(cmd)          # set to device
        if command.lower() not in ["quit", "return"]:
            self.updates_cmd.append(cmd)   # show updates result

    def config_bridge_domain(self):
        """manage bridge domain configuration"""

        if not self.bridge_domain_id:
            return

        # bridge-domain bd-id
        # [undo] arp broadcast-suppress enable

        cmd = "bridge-domain %s" % self.bridge_domain_id
        if not is_config_exist(self.config, cmd):
            self.module.fail_json(msg="Error: Bridge domain is not exist.")

        cmd = "arp broadcast-suppress enable"
        exist = is_config_exist(self.config, cmd)
        if self.arp_suppress == "enable" and not exist:
            self.cli_add_command("bridge-domain %s" % self.bridge_domain_id)
            self.cli_add_command(cmd)
            self.cli_add_command("quit")
        elif self.arp_suppress == "disable" and exist:
            self.cli_add_command("bridge-domain %s" % self.bridge_domain_id)
            self.cli_add_command(cmd, undo=True)
            self.cli_add_command("quit")

    def config_evn_bgp(self):
        """enables EVN BGP and configure evn bgp command"""


        evn_bgp_view = False
        evn_bgp_enable = False

        cmd = "evn bgp"
        exist = is_config_exist(self.config, cmd)
        if self.evn_bgp == "enable" or exist:
            evn_bgp_enable = True

        # [undo] evn bgp
        if self.evn_bgp:
            if self.evn_bgp == "enable" and not exist:
                self.cli_add_command(cmd)
                evn_bgp_view = True
            elif self.evn_bgp == "disable" and exist:
                self.cli_add_command(cmd, undo=True)
                return

        # [undo] source-address ip-address
        if evn_bgp_enable and self.evn_source_ip:
            cmd = "source-address %s" % self.evn_source_ip
            exist = is_config_exist(self.config, cmd)
            if self.state == "present" and not exist:
                if not evn_bgp_view:
                    self.cli_add_command("evn bgp")
                    evn_bgp_view = True
                self.cli_add_command(cmd)
            elif self.state == "absent" and exist:
                if not evn_bgp_view:
                    self.cli_add_command("evn bgp")
                    evn_bgp_view = True
                self.cli_add_command(cmd, undo=True)

        # [undo] peer ip-address
        # [undo] peer ipv4-address reflect-client
        if evn_bgp_enable and self.evn_peer_ip:
            cmd = "peer %s" % self.evn_peer_ip
            exist = is_config_exist(self.config, cmd)
            if self.state == "present":
                if not exist:
                    if not evn_bgp_view:
                        self.cli_add_command("evn bgp")
                        evn_bgp_view = True
                    self.cli_add_command(cmd)
                    if self.evn_reflect_client == "true":
                        self.cli_add_command(
                            "peer %s reflect-client" % self.evn_peer_ip)
                else:
                    if self.evn_reflect_client:
                        cmd = "peer %s reflect-client" % self.evn_peer_ip
                        exist = is_config_exist(self.config, cmd)
                        if self.evn_reflect_client == "true" and not exist:
                            if not evn_bgp_view:
                                self.cli_add_command("evn bgp")
                                evn_bgp_view = True
                            self.cli_add_command(cmd)
                        elif self.evn_reflect_client == "false" and exist:
                            if not evn_bgp_view:
                                self.cli_add_command("evn bgp")
                                evn_bgp_view = True
                            self.cli_add_command(cmd, undo=True)
            else:
                if exist:
                    if not evn_bgp_view:
                        self.cli_add_command("evn bgp")
                        evn_bgp_view = True
                    self.cli_add_command(cmd, undo=True)

        # [undo] server enable
        if evn_bgp_enable and self.evn_server:
            cmd = "server enable"
            exist = is_config_exist(self.config, cmd)
            if self.evn_server == "enable" and not exist:
                if not evn_bgp_view:
                    self.cli_add_command("evn bgp")
                    evn_bgp_view = True
                self.cli_add_command(cmd)
            elif self.evn_server == "disable" and exist:
                if not evn_bgp_view:
                    self.cli_add_command("evn bgp")
                    evn_bgp_view = True
                self.cli_add_command(cmd, undo=True)

        if evn_bgp_view:
            self.cli_add_command("quit")

    def config_vbdif(self):
        """configure command at the VBDIF interface view"""

        # interface vbdif bd-id
        # [undo] arp collect host enable

        cmd = "interface %s" % self.vbdif_name.lower().capitalize()
        exist = is_config_exist(self.config, cmd)

        if not exist:
            self.module.fail_json(
                msg="Error: Interface %s is not exist." % self.vbdif_name)

        cmd = "arp collect host enable"
        exist = is_config_exist(self.config, cmd)
        if self.arp_collect_host == "enable" and not exist:
            self.cli_add_command("interface %s" %
                                 self.vbdif_name.lower().capitalize())
            self.cli_add_command(cmd)
            self.cli_add_command("quit")
        elif self.arp_collect_host == "disable" and exist:
            self.cli_add_command("interface %s" %
                                 self.vbdif_name.lower().capitalize())
            self.cli_add_command(cmd, undo=True)
            self.cli_add_command("quit")

    def config_host_collect_protocal(self):
        """Enable EVN BGP or BGP EVPN to advertise host information"""

        # [undo] host collect protocol bgp
        cmd = "host collect protocol bgp"
        exist = is_config_exist(self.config, cmd)

        if self.state == "present":
            if self.host_collect_protocol == "bgp" and not exist:
                self.cli_add_command(cmd)
            elif self.host_collect_protocol == "none" and exist:
                self.cli_add_command(cmd, undo=True)
        else:
            if self.host_collect_protocol == "bgp" and exist:
                self.cli_add_command(cmd, undo=True)

    def is_valid_vbdif(self, ifname):
        """check is interface vbdif is valid"""

        if not ifname.upper().startswith('VBDIF'):
            return False
        bdid = self.vbdif_name.replace(" ", "").upper().replace("VBDIF", "")
        if not bdid.isdigit():
            return False
        if int(bdid) < 1 or int(bdid) > 16777215:
            return False

        return True

    def check_params(self):
        """Check all input params"""

        # bridge domain id check
        if self.bridge_domain_id:
            if not self.bridge_domain_id.isdigit():
                self.module.fail_json(
                    msg="Error: Bridge domain id is not digit.")
            if int(self.bridge_domain_id) < 1 or int(self.bridge_domain_id) > 16777215:
                self.module.fail_json(
                    msg="Error: Bridge domain id is not in the range from 1 to 16777215.")

        # evn_source_ip check
        if self.evn_source_ip:
            if not is_valid_v4addr(self.evn_source_ip):
                self.module.fail_json(msg="Error: evn_source_ip is invalid.")

        # evn_peer_ip check
        if self.evn_peer_ip:
            if not is_valid_v4addr(self.evn_peer_ip):
                self.module.fail_json(msg="Error: evn_peer_ip is invalid.")

        # vbdif_name check
        if self.vbdif_name:
            self.vbdif_name = self.vbdif_name.replace(
                " ", "").lower().capitalize()
            if not self.is_valid_vbdif(self.vbdif_name):
                self.module.fail_json(msg="Error: vbdif_name is invalid.")

        # vbdif_name and arp_collect_host must set at the same time
        if bool(self.vbdif_name) != bool(self.arp_collect_host):
            self.module.fail_json(
                msg="Error: vbdif_name and arp_collect_host must set at the same time.")

        # bridge_domain_id and arp_suppress must set at the same time
        if bool(self.bridge_domain_id) != bool(self.arp_suppress):
            self.module.fail_json(
                msg="Error: bridge_domain_id and arp_suppress must set at the same time.")

        # evn_reflect_client and evn_peer_ip must set at the same time
        if self.evn_reflect_client and not self.evn_peer_ip:
            self.module.fail_json(
                msg="Error: evn_reflect_client and evn_peer_ip must set at the same time.")

        # evn_server and evn_reflect_client can not set at the same time
        if self.evn_server == "enable" and self.evn_reflect_client == "true":
            self.module.fail_json(
                msg="Error: evn_server and evn_reflect_client can not set at the same time.")

    def get_proposed(self):
        """get proposed info"""

        if self.evn_bgp:
            self.proposed["evn_bgp"] = self.evn_bgp
        if self.evn_source_ip:
            self.proposed["evn_source_ip"] = self.evn_source_ip
        if self.evn_peer_ip:
            self.proposed["evn_peer_ip"] = self.evn_peer_ip
        if self.evn_server:
            self.proposed["evn_server"] = self.evn_server
        if self.evn_reflect_client:
            self.proposed["evn_reflect_client"] = self.evn_reflect_client
        if self.arp_collect_host:
            self.proposed["arp_collect_host"] = self.arp_collect_host
        if self.host_collect_protocol:
            self.proposed["host_collect_protocol"] = self.host_collect_protocol
        if self.arp_suppress:
            self.proposed["arp_suppress"] = self.arp_suppress
        if self.vbdif_name:
            self.proposed["vbdif_name"] = self.evn_peer_ip
        if self.bridge_domain_id:
            self.proposed["bridge_domain_id"] = self.bridge_domain_id
        self.proposed["state"] = self.state

    def get_existing(self):
        """get existing info"""

        evn_bgp_exist = is_config_exist(self.config, "evn bgp")
        if evn_bgp_exist:
            self.existing["evn_bgp"] = "enable"
        else:
            self.existing["evn_bgp"] = "disable"

        if evn_bgp_exist:
            if is_config_exist(self.config, "server enable"):
                self.existing["evn_server"] = "enable"
            else:
                self.existing["evn_server"] = "disable"

            self.existing["evn_source_ip"] = get_evn_srouce(self.config)
            self.existing["evn_peer_ip"] = get_evn_peers(self.config)
            self.existing["evn_reflect_client"] = get_evn_reflect_client(
                self.config)

        if is_config_exist(self.config, "arp collect host enable"):
            self.existing["host_collect_protocol"] = "enable"
        else:
            self.existing["host_collect_protocol"] = "disable"

        if is_config_exist(self.config, "host collect protocol bgp"):
            self.existing["host_collect_protocol"] = "bgp"
        else:
            self.existing["host_collect_protocol"] = None

        if is_config_exist(self.config, "arp broadcast-suppress enable"):
            self.existing["arp_suppress"] = "enable"
        else:
            self.existing["arp_suppress"] = "disable"

    def get_end_state(self):
        """get end state info"""

        config = self.get_current_config()
        evn_bgp_exist = is_config_exist(config, "evn bgp")
        if evn_bgp_exist:
            self.end_state["evn_bgp"] = "enable"
        else:
            self.end_state["evn_bgp"] = "disable"

        if evn_bgp_exist:
            if is_config_exist(config, "server enable"):
                self.end_state["evn_server"] = "enable"
            else:
                self.end_state["evn_server"] = "disable"

            self.end_state["evn_source_ip"] = get_evn_srouce(config)
            self.end_state["evn_peer_ip"] = get_evn_peers(config)
            self.end_state[
                "evn_reflect_client"] = get_evn_reflect_client(config)

        if is_config_exist(config, "arp collect host enable"):
            self.end_state["host_collect_protocol"] = "enable"
        else:
            self.end_state["host_collect_protocol"] = "disable"

        if is_config_exist(config, "host collect protocol bgp"):
            self.end_state["host_collect_protocol"] = "bgp"
        else:
            self.end_state["host_collect_protocol"] = None

        if is_config_exist(config, "arp broadcast-suppress enable"):
            self.end_state["arp_suppress"] = "enable"
        else:
            self.end_state["arp_suppress"] = "disable"

    def work(self):
        """worker"""

        self.check_params()
        self.config = self.get_current_config()
        self.get_existing()
        self.get_proposed()

        # deal present or absent
        if self.evn_bgp or self.evn_server or self.evn_peer_ip or self.evn_source_ip:
            self.config_evn_bgp()

        if self.vbdif_name and self.arp_collect_host:
            self.config_vbdif()

        if self.host_collect_protocol:
            self.config_host_collect_protocal()

        if self.bridge_domain_id and self.arp_suppress:
            self.config_bridge_domain()

        if self.commands:
            self.cli_load_config(self.commands)
            self.changed = True

        self.get_end_state()
        self.results['changed'] = self.changed
        self.results['proposed'] = self.proposed
        self.results['existing'] = self.existing
        self.results['end_state'] = self.end_state
        if self.changed:
            self.results['updates'] = self.updates_cmd
        else:
            self.results['updates'] = list()

        self.module.exit_json(**self.results)
示例#26
0
def main():
    spec = dict(
        gather_subset=dict(default=['!config'], type='list')
    )

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

    gather_subset = module.params['gather_subset']

    runable_subsets = set()
    exclude_subsets = set()

    for subset in gather_subset:
        if subset == 'all':
            runable_subsets.update(VALID_SUBSETS)
            continue

        if subset.startswith('!'):
            subset = subset[1:]
            if subset == 'all':
                exclude_subsets.update(VALID_SUBSETS)
                continue
            exclude = True
        else:
            exclude = False

        if subset not in VALID_SUBSETS:
            module.fail_json(msg='Bad subset')

        if exclude:
            exclude_subsets.add(subset)
        else:
            runable_subsets.add(subset)

    if not runable_subsets:
        runable_subsets.update(VALID_SUBSETS)

    runable_subsets.difference_update(exclude_subsets)
    runable_subsets.add('default')

    facts = dict()
    facts['gather_subset'] = list(runable_subsets)

    runner = CommandRunner(module)

    instances = list()
    for key in runable_subsets:
        instances.append(FACT_SUBSETS[key](module, runner))

    try:
        runner.run()
    except NetworkError:
        exc = get_exception()
        module.fail_json(msg=str(exc), **exc.kwargs)

    try:
        for inst in instances:
            inst.populate()
            facts.update(inst.facts)
    except Exception:
        raise
        module.exit_json(out=module.from_json(runner.items))

    ansible_facts = dict()
    for key, value in iteritems(facts):
        # this is to maintain capability with nxos_facts 2.1
        if key.startswith('_'):
            ansible_facts[key[1:]] = value
        else:
            key = 'ansible_net_%s' % key
            ansible_facts[key] = value

    module.exit_json(ansible_facts=ansible_facts)
示例#27
0
class Dldp(object):
    """Manage global dldp configration"""
    def __init__(self, argument_spec):
        self.spec = argument_spec
        self.module = None
        self.netconf = None
        self.init_module()

        # dldp global configration info
        self.enable = self.module.params['enable'] or None
        self.work_mode = self.module.params['work_mode'] or None
        self.internal = self.module.params['time_interval'] or None
        self.reset = self.module.params['reset'] or None
        self.auth_mode = self.module.params['auth_mode']
        self.auth_pwd = self.module.params['auth_pwd']

        self.dldp_conf = dict()
        self.same_conf = False

        # host info
        self.host = self.module.params['host']
        self.username = self.module.params['username']
        self.port = self.module.params['port']

        # state
        self.changed = False
        self.updates_cmd = list()
        self.results = dict()
        self.proposed = dict()
        self.existing = list()
        self.end_state = list()

        # init netconf connect
        self.init_netconf()

    def check_config_if_same(self):
        """judge whether current config is the same as what we excepted"""

        if self.enable and self.enable != self.dldp_conf['dldpEnable']:
            return False

        if self.internal and self.internal != self.dldp_conf['dldpInterval']:
            return False

        work_mode = 'normal'
        if self.dldp_conf['dldpWorkMode'] == 'dldpEnhance':
            work_mode = 'enhance'
        if self.work_mode and self.work_mode != work_mode:
            return False

        if self.auth_mode:
            if self.auth_mode != 'none':
                return False

            if self.auth_mode == 'none' and self.dldp_conf[
                    'dldpAuthMode'] != 'dldpAuthNone':
                return False

        if self.reset and self.reset == 'true':
            return False

        return True

    def check_params(self):
        """Check all input params"""

        if (self.auth_mode and self.auth_mode != 'none' and not self.auth_pwd) \
                or (self.auth_pwd and not self.auth_mode):
            self.module.fail_json(
                msg=
                "Error: auth_mode and auth_pwd must both exist or not exist.")

        if self.dldp_conf['dldpEnable'] == 'false' and not self.enable:
            if self.work_mode or self.reset or self.internal or self.auth_mode:
                self.module.fail_json(
                    msg="Error: when DLDP is already disabled globally, "
                    "work_mode, time_internal auth_mode and reset parameters are not "
                    "expected to configure.")

        if self.enable == 'false' and (self.work_mode or self.internal
                                       or self.reset or self.auth_mode):
            self.module.fail_json(
                msg="Error: when using enable=false, work_mode, "
                "time_internal auth_mode and reset parameters are not expected "
                "to configure.")

        if self.internal:
            if not self.internal.isdigit():
                self.module.fail_json(
                    msg='Error: time_interval must be digit.')

            if int(self.internal) < 1 or int(self.internal) > 100:
                self.module.fail_json(
                    msg=
                    'Error: The value of time_internal should be between 1 and 100.'
                )

        if self.auth_pwd:
            if '?' in self.auth_pwd:
                self.module.fail_json(
                    msg=
                    'Error: The auth_pwd string excludes a question mark (?).')
            if (len(self.auth_pwd) != 24) and (len(self.auth_pwd) != 32) and (len(self.auth_pwd) != 48) and \
                    (len(self.auth_pwd) != 108) and (len(self.auth_pwd) != 128):
                if (len(self.auth_pwd) < 1) or (len(self.auth_pwd) > 16):
                    self.module.fail_json(
                        msg=
                        'Error: The value is a string of 1 to 16 case-sensitive plaintexts or 24/32/48/108/128 '
                        'case-sensitive encrypted characters.')

    def init_module(self):
        """init module object"""
        self.module = NetworkModule(argument_spec=self.spec,
                                    supports_check_mode=True)

    def init_netconf(self):
        """init netconf interface"""

        if HAS_NCCLIENT:
            self.netconf = get_netconf(host=self.host,
                                       port=self.port,
                                       username=self.username,
                                       password=self.module.params['password'])
            if not self.netconf:
                self.module.fail_json(msg='Error: netconf init failed')
        else:
            self.module.fail_json(
                msg='Error: No ncclient package, please install it.')

    def check_response(self, con_obj, xml_name):
        """Check if response message is already succeed"""

        xml_str = con_obj.xml
        if "<ok/>" not in xml_str:
            self.module.fail_json(msg='Error: %s failed.' % xml_name)

    def netconf_get_config(self, xml_str):
        """netconf get config"""

        try:
            con_obj = self.netconf.get_config(filter=xml_str)
        except RPCError:
            err = sys.exc_info()[1]
            self.module.fail_json(msg='Error: %s' %
                                  err.message.replace("\r\n", ""))

        return con_obj

    def netconf_set_config(self, xml_str, xml_name):
        """netconf set config"""

        try:
            con_obj = self.netconf.set_config(config=xml_str)
            self.check_response(con_obj, xml_name)
        except RPCError:
            err = sys.exc_info()[1]
            self.module.fail_json(msg='Error: %s' %
                                  err.message.replace("\r\n", ""))

        return con_obj

    def netconf_set_action(self, xml_str, xml_name):
        """netconf set action"""

        try:
            con_obj = self.netconf.execute_action(action=xml_str)
            self.check_response(con_obj, xml_name)
        except RPCError:
            err = sys.exc_info()[1]
            self.module.fail_json(msg='Error: %s' %
                                  err.message.replace("\r\n", ""))

        return con_obj

    def get_dldp_exist_config(self):
        """get current dldp existed configuration"""
        dldp_conf = dict()
        xml_str = CE_NC_GET_GLOBAL_DLDP_CONFIG
        con_obj = self.netconf_get_config(xml_str)
        if "<data/>" in con_obj.xml:
            return dldp_conf

        xml_str = con_obj.xml.replace('\r', '').replace('\n', '').\
            replace('xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"', "").\
            replace('xmlns="http://www.huawei.com/netconf/vrp"', "")

        # get global dldp info
        root = ElementTree.fromstring(xml_str)
        topo = root.find("data/dldp/dldpSys")
        if not topo:
            self.module.fail_json(
                msg="Error: Get current DLDP configration failed.")

        for eles in topo:
            if eles.tag in [
                    "dldpEnable", "dldpInterval", "dldpWorkMode",
                    "dldpAuthMode"
            ]:
                dldp_conf[eles.tag] = eles.text

        return dldp_conf

    def config_global_dldp(self):
        """config global dldp"""
        if self.same_conf:
            return

        enable = self.enable
        if not self.enable:
            enable = self.dldp_conf['dldpEnable']

        internal = self.internal
        if not self.internal:
            internal = self.dldp_conf['dldpInterval']

        work_mode = self.work_mode
        if not self.work_mode:
            work_mode = self.dldp_conf['dldpWorkMode']

        if work_mode == 'enhance' or work_mode == 'dldpEnhance':
            work_mode = 'dldpEnhance'
        else:
            work_mode = 'dldpNormal'

        auth_mode = self.auth_mode
        if not self.auth_mode:
            auth_mode = self.dldp_conf['dldpAuthMode']
        if auth_mode == 'md5':
            auth_mode = 'dldpAuthMD5'
        elif auth_mode == 'simple':
            auth_mode = 'dldpAuthSimple'
        elif auth_mode == 'sha':
            auth_mode = 'dldpAuthSHA'
        elif auth_mode == 'hmac-sha256':
            auth_mode = 'dldpAuthHMAC-SHA256'
        elif auth_mode == 'none':
            auth_mode = 'dldpAuthNone'

        xml_str = CE_NC_MERGE_DLDP_GLOBAL_CONFIG_HEAD % (enable, internal,
                                                         work_mode)
        if self.auth_mode:
            if self.auth_mode == 'none':
                xml_str += "<dldpAuthMode>dldpAuthNone</dldpAuthMode>"
            else:
                xml_str += "<dldpAuthMode>%s</dldpAuthMode>" % auth_mode
                xml_str += "<dldpPasswords>%s</dldpPasswords>" % self.auth_pwd

        xml_str += CE_NC_MERGE_DLDP_GLOBAL_CONFIG_TAIL
        self.netconf_set_config(xml_str, "MERGE_DLDP_GLOBAL_CONFIG")

        if self.reset == 'true':
            xml_str = CE_NC_ACTION_RESET_DLDP
            self.netconf_set_action(xml_str, "ACTION_RESET_DLDP")

        self.changed = True

    def get_existing(self):
        """get existing info"""
        dldp_conf = dict()

        dldp_conf['enable'] = self.dldp_conf.get('dldpEnable', None)
        dldp_conf['time_interval'] = self.dldp_conf.get('dldpInterval', None)
        work_mode = self.dldp_conf.get('dldpWorkMode', None)
        if work_mode == 'dldpEnhance':
            dldp_conf['work_mode'] = 'enhance'
        else:
            dldp_conf['work_mode'] = 'normal'

        auth_mode = self.dldp_conf.get('dldpAuthMode', None)
        if auth_mode == 'dldpAuthNone':
            dldp_conf['auth_mode'] = 'none'
        elif auth_mode == 'dldpAuthSimple':
            dldp_conf['auth_mode'] = 'simple'
        elif auth_mode == 'dldpAuthMD5':
            dldp_conf['auth_mode'] = 'md5'
        elif auth_mode == 'dldpAuthSHA':
            dldp_conf['auth_mode'] = 'sha'
        else:
            dldp_conf['auth_mode'] = 'hmac-sha256'

        dldp_conf['reset'] = 'false'

        self.existing = copy.deepcopy(dldp_conf)

    def get_proposed(self):
        """get proposed result"""

        self.proposed = dict(enable=self.enable,
                             work_mode=self.work_mode,
                             time_interval=self.internal,
                             reset=self.reset,
                             auth_mode=self.auth_mode,
                             auth_pwd=self.auth_pwd)

    def get_update_cmd(self):
        """get update commands"""
        if self.same_conf:
            return

        if self.enable and self.enable != self.dldp_conf['dldpEnable']:
            if self.enable == 'true':
                self.updates_cmd.append("dldp enable")
            elif self.enable == 'false':
                self.updates_cmd.append("undo dldp enable")
                return

        work_mode = 'normal'
        if self.dldp_conf['dldpWorkMode'] == 'dldpEnhance':
            work_mode = 'enhance'
        if self.work_mode and self.work_mode != work_mode:
            if self.work_mode == 'enhance':
                self.updates_cmd.append("dldp work-mode enhance")
            else:
                self.updates_cmd.append("dldp work-mode normal")

        if self.internal and self.internal != self.dldp_conf['dldpInterval']:
            self.updates_cmd.append("dldp interval %s" % self.internal)

        if self.auth_mode:
            if self.auth_mode == 'none':
                self.updates_cmd.append("undo dldp authentication-mode")
            else:
                self.updates_cmd.append("dldp authentication-mode %s %s" %
                                        (self.auth_mode, self.auth_pwd))

        if self.reset and self.reset == 'true':
            self.updates_cmd.append('dldp reset')

    def get_end_state(self):
        """get end state info"""
        dldp_conf = dict()
        self.dldp_conf = self.get_dldp_exist_config()

        dldp_conf['enable'] = self.dldp_conf.get('dldpEnable', None)
        dldp_conf['time_interval'] = self.dldp_conf.get('dldpInterval', None)
        work_mode = self.dldp_conf.get('dldpWorkMode', None)
        if work_mode == 'dldpEnhance':
            dldp_conf['work_mode'] = 'enhance'
        else:
            dldp_conf['work_mode'] = 'normal'

        auth_mode = self.dldp_conf.get('dldpAuthMode', None)
        if auth_mode == 'dldpAuthNone':
            dldp_conf['auth_mode'] = 'none'
        elif auth_mode == 'dldpAuthSimple':
            dldp_conf['auth_mode'] = 'simple'
        elif auth_mode == 'dldpAuthMD5':
            dldp_conf['auth_mode'] = 'md5'
        elif auth_mode == 'dldpAuthSHA':
            dldp_conf['auth_mode'] = 'sha'
        else:
            dldp_conf['auth_mode'] = 'hmac-sha256'

        dldp_conf['reset'] = 'false'
        if self.reset == 'true':
            dldp_conf['reset'] = 'true'
        self.end_state = copy.deepcopy(dldp_conf)

    def show_result(self):
        """show result"""
        self.results['changed'] = self.changed
        self.results['proposed'] = self.proposed
        self.results['existing'] = self.existing
        self.results['end_state'] = self.end_state
        if self.changed:
            self.results['updates'] = self.updates_cmd
        else:
            self.results['updates'] = list()

        self.module.exit_json(**self.results)

    def work(self):
        """worker"""
        self.dldp_conf = self.get_dldp_exist_config()
        self.check_params()
        self.same_conf = self.check_config_if_same()
        self.get_existing()
        self.get_proposed()
        self.config_global_dldp()
        self.get_update_cmd()
        self.get_end_state()
        self.show_result()
示例#28
0
    def init_module(self):
        """ init_module"""

        self.module = NetworkModule(
            argument_spec=self.spec, supports_check_mode=True)
示例#29
0
def main():
    """main entry point for Ansible module
    """

    spec = dict(
        commands=dict(type="list"),
        rpcs=dict(type="list"),
        display=dict(default="xml", choices=["text", "xml"], aliases=["format", "output"]),
        wait_for=dict(type="list", aliases=["waitfor"]),
        match=dict(default="all", choices=["all", "any"]),
        retries=dict(default=10, type="int"),
        interval=dict(default=1, type="int"),
        transport=dict(default="netconf", choices=["netconf"]),
    )

    mutually_exclusive = [("commands", "rpcs")]

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

    commands = list()
    for key in VALID_KEYS.keys():
        commands.extend(list(parse(module, key)))

    conditionals = module.params["wait_for"] or list()

    warnings = list()

    runner = CommandRunner(module)

    for cmd in commands:
        if module.check_mode and not cmd["command"].startswith("show"):
            warnings.append(
                "only show commands are supported when using " "check mode, not executing `%s`" % cmd["command"]
            )
        else:
            if cmd["command"].startswith("co"):
                module.fail_json(
                    msg="junos_command does not support running "
                    "config mode commands.  Please use "
                    "junos_config instead"
                )
            try:
                runner.add_command(**cmd)
            except AddCommandError:
                exc = get_exception()
                warnings.append("duplicate command detected: %s" % cmd)

    try:
        for item in conditionals:
            runner.add_conditional(item)
    except (ValueError, AddConditionError):
        exc = get_exception()
        module.fail_json(msg=str(exc), condition=exc.condition)

    runner.retries = module.params["retries"]
    runner.interval = module.params["interval"]
    runner.match = module.params["match"]

    try:
        runner.run()
    except FailedConditionsError:
        exc = get_exception()
        module.fail_json(msg=str(exc), failed_conditions=exc.failed_conditions)
    except FailedConditionalError:
        exc = get_exception()
        module.fail_json(msg=str(exc), failed_conditional=exc.failed_conditional)
    except NetworkError:
        exc = get_exception()
        module.fail_json(msg=str(exc))

    result = dict(changed=False, stdout=list())

    for cmd in commands:
        try:
            output = runner.get_command(cmd["command"], cmd.get("output"))
        except ValueError:
            output = "command not executed due to check_mode, see warnings"
        result["stdout"].append(output)

    result["warnings"] = warnings
    result["stdout_lines"] = list(to_lines(result["stdout"]))

    module.exit_json(**result)
示例#30
0
def main():
    """main entry point for Ansible module
    """

    spec = dict(
        commands=dict(type='list'),
        rpcs=dict(type='list'),

        display=dict(default='xml', choices=['text', 'xml'],
                     aliases=['format', 'output']),

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

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

        transport=dict(default='netconf', choices=['netconf'])
    )

    mutually_exclusive = [('commands', 'rpcs')]

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

    commands = list()
    for key in VALID_KEYS.keys():
        commands.extend(list(parse(module, key)))

    conditionals = module.params['wait_for'] or list()

    warnings = list()

    runner = CommandRunner(module)

    for cmd in commands:
        if module.check_mode and not cmd['command'].startswith('show'):
            warnings.append('only show commands are supported when using '
                            'check mode, not executing `%s`' % cmd['command'])
        else:
            if cmd['command'].startswith('co'):
                module.fail_json(msg='junos_command does not support running '
                                     'config mode commands.  Please use '
                                     'junos_config instead')
            try:
                runner.add_command(**cmd)
            except AddCommandError:
                exc = get_exception()
                warnings.append('duplicate command detected: %s' % cmd)

    try:
        for item in conditionals:
            runner.add_conditional(item)
    except (ValueError, AddConditionError):
        exc = get_exception()
        module.fail_json(msg=str(exc), condition=exc.condition)

    runner.retries = module.params['retries']
    runner.interval = module.params['interval']
    runner.match = module.params['match']

    try:
        runner.run()
    except FailedConditionsError:
        exc = get_exception()
        module.fail_json(msg=str(exc), failed_conditions=exc.failed_conditions)
    except FailedConditionalError:
        exc = get_exception()
        module.fail_json(msg=str(exc), failed_conditional=exc.failed_conditional)
    except NetworkError:
        exc = get_exception()
        module.fail_json(msg=str(exc))

    result = dict(changed=False, stdout=list())

    for cmd in commands:
        try:
            output = runner.get_command(cmd['command'], cmd.get('output'))
        except ValueError:
            output = 'command not executed due to check_mode, see warnings'
        result['stdout'].append(output)

    result['warnings'] = warnings
    result['stdout_lines'] = list(to_lines(result['stdout']))

    module.exit_json(**result)
示例#31
0
    def init_module(self):
        """ init_module"""

        self.module = NetworkModule(argument_spec=self.spec, supports_check_mode=True,
                                    mutually_exclusive=self.mutually_exclusive)
示例#32
0
def main():
    spec = dict(commands=dict(type='list', required=True),
                wait_for=dict(type='list'),
                retries=dict(default=10, type='int'),
                interval=dict(default=1, type='int'))

    module = NetworkModule(argument_spec=spec,
                           connect_on_load=False,
                           supports_check_mode=True)
    commands = list(parse_commands(module))
    conditionals = module.params['wait_for'] or list()

    warnings = list()

    runner = CommandRunner(module)

    for cmd in commands:
        if module.check_mode and not cmd['command'].startswith('show'):
            warnings.append('only show commands are supported when using '
                            'check mode, not executing `%s`' % cmd)
        else:
            if cmd['command'].startswith('conf'):
                module.fail_json(
                    msg='dellos6_command does not support running '
                    'config mode commands.  Please use '
                    'dellos6_config instead')
            try:
                runner.add_command(**cmd)
            except AddCommandError:
                exc = get_exception()
                warnings.append('duplicate command detected: %s' % cmd)

    for item in conditionals:
        runner.add_conditional(item)

    runner.retries = module.params['retries']
    runner.interval = module.params['interval']

    try:
        runner.run()
    except FailedConditionsError:
        exc = get_exception()
        module.fail_json(msg=str(exc), failed_conditions=exc.failed_conditions)
    except NetworkError:
        exc = get_exception()
        module.fail_json(msg=str(exc))

    result = dict(changed=False)

    result['stdout'] = list()
    for cmd in commands:
        try:
            output = runner.get_command(cmd['command'])
        except ValueError:
            output = 'command not executed due to check_mode, see warnings'
        result['stdout'].append(output)

    result['warnings'] = warnings
    result['stdout_lines'] = list(to_lines(result['stdout']))

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

    spec = dict(
        commands=dict(type='list'),
        rpcs=dict(type='list'),

        display=dict(default='xml', choices=['text', 'xml'],
                     aliases=['format', 'output']),

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

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

        transport=dict(default='netconf', choices=['netconf'])
    )

    mutually_exclusive = [('commands', 'rpcs')]

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

    commands = list()
    for key in VALID_KEYS.keys():
        commands.extend(list(parse(module, key)))

    conditionals = module.params['wait_for'] or list()

    warnings = list()

    runner = CommandRunner(module)

    for cmd in commands:
        if module.check_mode and not cmd['command'].startswith('show'):
            warnings.append('only show commands are supported when using '
                            'check mode, not executing `%s`' % cmd['command'])
        else:
            if cmd['command'].startswith('co'):
                module.fail_json(msg='junos_command does not support running '
                                     'config mode commands.  Please use '
                                     'junos_config instead')
            try:
                runner.add_command(**cmd)
            except AddCommandError:
                exc = get_exception()
                warnings.append('duplicate command detected: %s' % cmd)

    try:
        for item in conditionals:
            runner.add_conditional(item)
    except (ValueError, AddConditionError):
        exc = get_exception()
        module.fail_json(msg=str(exc), condition=exc.condition)

    runner.retries = module.params['retries']
    runner.interval = module.params['interval']
    runner.match = module.params['match']

    try:
        runner.run()
    except FailedConditionsError:
        exc = get_exception()
        module.fail_json(msg=str(exc), failed_conditions=exc.failed_conditions)
    except FailedConditionalError:
        exc = get_exception()
        module.fail_json(msg=str(exc), failed_conditional=exc.failed_conditional)
    except NetworkError:
        exc = get_exception()
        module.fail_json(msg=str(exc))

    result = dict(changed=False, stdout=list())

    for cmd in commands:
        try:
            output = runner.get_command(cmd['command'], cmd.get('output'))
        except ValueError:
            output = 'command not executed due to check_mode, see warnings'
        result['stdout'].append(output)

    result['warnings'] = warnings
    result['stdout_lines'] = list(to_lines(result['stdout']))

    module.exit_json(**result)
示例#34
0
class CE_Interface(object):
    """CE_Interface"""
    def __init__(
        self,
        argument_spec,
    ):
        self.start_time = datetime.datetime.now()
        self.end_time = None
        self.spec = argument_spec
        self.module = None
        self.nc = None
        self.init_module()

        # interface info
        self.interface = self.module.params['interface']
        self.interface_type = self.module.params['interface_type']
        self.admin_state = self.module.params['admin_state']
        self.description = self.module.params['description']
        self.mode = self.module.params['mode']
        self.state = self.module.params['state']

        # host info
        self.host = self.module.params['host']
        self.username = self.module.params['username']
        self.password = self.module.params['password']
        self.port = self.module.params['port']

        # state
        self.changed = False
        self.updates_cmd = list()
        self.results = dict()
        self.proposed = dict()
        self.existing = dict()
        self.end_state = dict()
        self.intfs_info = dict()  # all type interface info
        self.intf_info = dict()  # one interface info
        self.intf_type = None  # loopback tunnel ...

        # init netconf connect
        self.init_netconf()

    def init_module(self):
        """init_module"""

        self.module = NetworkModule(argument_spec=self.spec,
                                    supports_check_mode=True)

    def init_netconf(self):
        """init_netconf"""

        if not HAS_NCCLIENT:
            raise Exception("the ncclient library is required")

        self.nc = get_netconf(host=self.host,
                              port=self.port,
                              username=self.username,
                              password=self.password)
        if not self.nc:
            self.module.fail_json(msg='Error: netconf init failed')

    def check_response(self, con_obj, xml_name):
        """Check if response message is already succeed."""

        xml_str = con_obj.xml
        if "<ok/>" not in xml_str:
            self.module.fail_json(msg='Error: %s failed.' % xml_name)

    def build_config_xml(self, xmlstr):
        """build_config_xml"""

        return '<config> ' + xmlstr + ' </config>'

    def get_interfaces_dict(self):
        """ get interfaces attributes dict."""

        intfs_info = dict()
        conf_str = CE_NC_GET_INTFS
        try:
            con_obj = self.nc.get_config(filter=conf_str)
        except RPCError as e:
            self.module.fail_json(msg='Error: %s' % e.message)

        if "<data/>" in con_obj.xml:
            return intfs_info

        intf = re.findall(
            r'.*<ifName>(.*)</ifName>.*\s*<ifPhyType>(.*)</ifPhyType>.*\s*'
            r'<ifNumber>(.*)</ifNumber>.*\s*<ifDescr>(.*)</ifDescr>.*\s*'
            r'<isL2SwitchPort>(.*)</isL2SwitchPort>.*\s*<ifAdminStatus>'
            r'(.*)</ifAdminStatus>.*\s*<ifMtu>(.*)</ifMtu>.*', con_obj.xml)

        for i in range(len(intf)):
            if intf[i][1]:
                if not intfs_info.get(intf[i][1].lower()):
                    # new interface type list
                    intfs_info[intf[i][1].lower()] = list()
                intfs_info[intf[i][1].lower()].append\
                    (dict(ifName=intf[i][0], ifPhyType=intf[i][1],
                          ifNumber=intf[i][2], ifDescr=intf[i][3],
                          isL2SwitchPort=intf[i][4],
                          ifAdminStatus=intf[i][5],
                          ifMtu=intf[i][6]))

        return intfs_info

    def get_interface_dict(self, ifname):
        """ get one interface attributes dict."""

        intf_info = dict()
        conf_str = CE_NC_GET_INTF % ifname
        try:
            con_obj = self.nc.get_config(filter=conf_str)
        except RPCError as e:
            self.module.fail_json(msg='Error: %s' % e.message)

        if "<data/>" in con_obj.xml:
            return intf_info

        intf = re.findall(
            r'.*<ifName>(.*)</ifName>.*\s*'
            r'<ifPhyType>(.*)</ifPhyType>.*\s*'
            r'<ifNumber>(.*)</ifNumber>.*\s*'
            r'<ifDescr>(.*)</ifDescr>.*\s*'
            r'<isL2SwitchPort>(.*)</isL2SwitchPort>.*\s*'
            r'<ifAdminStatus>(.*)</ifAdminStatus>.*\s*'
            r'<ifMtu>(.*)</ifMtu>.*', con_obj.xml)

        if intf:
            intf_info = dict(ifName=intf[0][0],
                             ifPhyType=intf[0][1],
                             ifNumber=intf[0][2],
                             ifDescr=intf[0][3],
                             isL2SwitchPort=intf[0][4],
                             ifAdminStatus=intf[0][5],
                             ifMtu=intf[0][6])

        return intf_info

    def get_interface_type(self, interface):
        """Gets the type of interface, such as 10GE, ETH-TRUNK, VLANIF..."""

        if interface is None:
            return None

        iftype = None

        if interface.upper().startswith('GE'):
            iftype = 'ge'
        elif interface.upper().startswith('10GE'):
            iftype = '10ge'
        elif interface.upper().startswith('25GE'):
            iftype = '25ge'
        elif interface.upper().startswith('4X10GE'):
            iftype = '4x10ge'
        elif interface.upper().startswith('40GE'):
            iftype = '40ge'
        elif interface.upper().startswith('100GE'):
            iftype = '100ge'
        elif interface.upper().startswith('VLANIF'):
            iftype = 'vlanif'
        elif interface.upper().startswith('LOOPBACK'):
            iftype = 'loopback'
        elif interface.upper().startswith('METH'):
            iftype = 'meth'
        elif interface.upper().startswith('ETH-TRUNK'):
            iftype = 'eth-trunk'
        elif interface.upper().startswith('VBDIF'):
            iftype = 'vbdif'
        elif interface.upper().startswith('NVE'):
            iftype = 'nve'
        elif interface.upper().startswith('TUNNEL'):
            iftype = 'tunnel'
        elif interface.upper().startswith('ETHERNET'):
            iftype = 'ethernet'
        elif interface.upper().startswith('FCOE-PORT'):
            iftype = 'fcoe-port'
        elif interface.upper().startswith('FABRIC-PORT'):
            iftype = 'fabric-port'
        elif interface.upper().startswith('STACK-PORT'):
            iftype = 'stack-Port'
        elif interface.upper().startswith('NULL'):
            iftype = 'null'
        else:
            return None

        return iftype.lower()

    def is_admin_state_enable(self, iftype):
        """admin state disable: loopback nve"""

        if iftype in admin_state_type:
            return True
        else:
            return False

    def is_portswitch_enalbe(self, iftype):
        """"is portswitch? """

        if iftype in switch_port_type:
            return True
        else:
            return False

    def is_create_enalbe(self, iftype):
        """is_create_enalbe"""

        return True

    def is_delete_enable(self, iftype):
        """is_delete_enable"""

        return True

    def create_interface(self, ifname, descritption, admin_state, mode):
        """Create interface."""

        self.updates_cmd.append("interface %s" % ifname)
        if not descritption:
            descritption = ''
        else:
            self.updates_cmd.append("descritption %s" % descritption)

        xmlstr = CE_NC_XML_CREATE_INTF % (ifname, descritption)
        if admin_state and self.is_admin_state_enable(self.intf_type):
            xmlstr += CE_NC_XML_MERGE_INTF_STATUS % (ifname, admin_state)
            if admin_state == 'up':
                self.updates_cmd.append("undo shutdown")
            else:
                self.updates_cmd.append("shutdown")
        if mode and self.is_portswitch_enalbe(self.intf_type):
            if mode == "layer2":
                xmlstr += CE_NC_XML_MERGE_INTF_L2ENABLE % (ifname, 'enable')
                self.updates_cmd.append('portswitch')
            elif mode == "layer3":
                xmlstr += CE_NC_XML_MERGE_INTF_L2ENABLE % (ifname, 'disable')
                self.updates_cmd.append('undo portswitch')

        conf_str = self.build_config_xml(xmlstr)
        try:
            con_obj = self.nc.set_config(config=conf_str)
            self.check_response(con_obj, "CREATE_INTF")
            self.changed = True
        except RPCError as e:
            self.module.fail_json(msg='Error: %s' % e.message)

    def delete_interface(self, ifname):
        """ Delete interface."""

        xmlstr = CE_NC_XML_DELETE_INTF % ifname
        conf_str = self.build_config_xml(xmlstr)
        self.updates_cmd.append('undo interface %s' % ifname)

        try:
            con_obj = self.nc.set_config(config=conf_str)
            self.check_response(con_obj, "DELETE_INTF")
            self.changed = True
        except RPCError as e:
            self.module.fail_json(msg='Error: %s' % e.message)

    def delete_interfaces(self, iftype):
        """ Delete interfaces with type."""

        xmlstr = ''
        intfs_list = self.intfs_info.get(iftype.lower())
        if not intfs_list:
            return

        for i in range(len(intfs_list)):
            xmlstr += CE_NC_XML_DELETE_INTF % intfs_list[i]['ifName']
            self.updates_cmd.append('undo interface %s' %
                                    intfs_list[i]['ifName'])

        conf_str = self.build_config_xml(xmlstr)
        try:
            con_obj = self.nc.set_config(config=conf_str)
            self.check_response(con_obj, "DELETE_INTFS")
            self.changed = True
        except RPCError as e:
            self.module.fail_json(msg='Error: %s' % e.message)

    def merge_interface(self, ifname, descritption, admin_state, mode):
        """ Merge interface attributes."""

        xmlstr = ''
        change = False
        self.updates_cmd.append("interface %s" % ifname)
        if descritption and self.intf_info["ifDescr"] != descritption:
            xmlstr += CE_NC_XML_MERGE_INTF_DES % (ifname, descritption)
            self.updates_cmd.append("descritption %s" % descritption)
            change = True

        if admin_state and self.is_admin_state_enable(self.intf_type) \
                and self.intf_info["ifAdminStatus"] != admin_state:
            xmlstr += CE_NC_XML_MERGE_INTF_STATUS % (ifname, admin_state)
            change = True
            if admin_state == "up":
                self.updates_cmd.append("undo shutdown")
            else:
                self.updates_cmd.append("shutdown")

        if self.is_portswitch_enalbe(self.intf_type):
            if mode == "layer2" and self.intf_info["isL2SwitchPort"] != "true":
                xmlstr += CE_NC_XML_MERGE_INTF_L2ENABLE % (ifname, 'enable')
                self.updates_cmd.append("portswitch")
                change = True
            elif mode == "layer3" \
                    and self.intf_info["isL2SwitchPort"] != "false":
                xmlstr += CE_NC_XML_MERGE_INTF_L2ENABLE % (ifname, 'disable')
                self.updates_cmd.append("undo portswitch")
                change = True

        if not change:
            return

        conf_str = self.build_config_xml(xmlstr)

        try:
            con_obj = self.nc.set_config(config=conf_str)
            self.check_response(con_obj, "MERGE_INTF_ATTR")
            self.changed = True
        except RPCError as e:
            self.module.fail_json(msg='Error: %s' % e.message)

    def merge_interfaces(self, iftype, descritption, admin_state, mode):
        """ Merge interface attributes by type."""

        xmlstr = ''
        change = False
        intfs_list = self.intfs_info.get(iftype.lower())
        if not intfs_list:
            return

        for i in range(len(intfs_list)):
            if_change = False
            self.updates_cmd.append("interface %s" % intfs_list[i]['ifName'])
            if descritption and intfs_list[i]["ifDescr"] != descritption:
                xmlstr += CE_NC_XML_MERGE_INTF_DES % (intfs_list[i]['ifName'],
                                                      descritption)
                self.updates_cmd.append("descritption %s" % descritption)
                if_change = True
            if admin_state and self.is_admin_state_enable(self.intf_type)\
                    and intfs_list[i]["ifAdminStatus"] != admin_state:
                xmlstr += CE_NC_XML_MERGE_INTF_STATUS % (
                    intfs_list[i]['ifName'], admin_state)
                if_change = True
                if admin_state == "up":
                    self.updates_cmd.append("undo shutdown")
                else:
                    self.updates_cmd.append("shutdown")

            if self.is_portswitch_enalbe(self.intf_type):
                if mode == "layer2" \
                        and intfs_list[i]["isL2SwitchPort"] != "true":
                    xmlstr += CE_NC_XML_MERGE_INTF_L2ENABLE % (
                        intfs_list[i]['ifName'], 'enable')
                    self.updates_cmd.append("portswitch")
                    if_change = True
                elif mode == "layer3" \
                        and intfs_list[i]["isL2SwitchPort"] != "false":
                    xmlstr += CE_NC_XML_MERGE_INTF_L2ENABLE % (
                        intfs_list[i]['ifName'], 'disable')
                    self.updates_cmd.append("undo portswitch")
                    if_change = True

            if if_change:
                change = True
            else:
                self.updates_cmd.pop()

        if not change:
            return

        conf_str = self.build_config_xml(xmlstr)

        try:
            con_obj = self.nc.set_config(config=conf_str)
            self.check_response(con_obj, "MERGE_INTFS_ATTR")
            self.changed = True
        except RPCError as e:
            self.module.fail_json(msg='Error: %s' % e.message)

    def default_interface(self, ifname, default_all=False):
        """default_interface"""

        change = False
        xmlstr = ""
        self.updates_cmd.append("interface %s" % ifname)
        # set descritption default
        if self.intf_info["ifDescr"]:
            xmlstr += CE_NC_XML_MERGE_INTF_DES % (ifname, '')
            self.updates_cmd.append("undo descritption")
            change = True

        # set admin_status default
        if self.is_admin_state_enable(self.intf_type) \
                and self.intf_info["ifAdminStatus"] != 'up':
            xmlstr += CE_NC_XML_MERGE_INTF_STATUS % (ifname, 'up')
            self.updates_cmd.append("undo shutdown")
            change = True

        # set portswitch default
        if self.is_portswitch_enalbe(self.intf_type) \
                and self.intf_info["isL2SwitchPort"] != "true":
            xmlstr += CE_NC_XML_MERGE_INTF_L2ENABLE % (ifname, 'enable')
            self.updates_cmd.append("portswitch")
            change = True

        if not change:
            return

        conf_str = self.build_config_xml(xmlstr)
        try:
            con_obj = self.nc.set_config(config=conf_str)
            self.check_response(con_obj, "SET_INTF_DEFAULT")
            self.changed = True
        except RPCError as e:
            self.module.fail_json(msg='Error: %s' % e.message)

    def default_interfaces(self, iftype, default_all=False):
        """ Set interface config to default by type."""

        change = False
        xmlstr = ''
        intfs_list = self.intfs_info.get(iftype.lower())
        if not intfs_list:
            return

        for i in range(len(intfs_list)):
            if_change = False
            self.updates_cmd.append("interface %s" % intfs_list[i]['ifName'])

            # set descritption default
            if intfs_list[i]['ifDescr']:
                xmlstr += CE_NC_XML_MERGE_INTF_DES % (intfs_list[i]['ifName'],
                                                      '')
                self.updates_cmd.append("undo descritption")
                if_change = True

            # set admin_status default
            if self.is_admin_state_enable(self.intf_type) \
                    and intfs_list[i]["ifAdminStatus"] != 'up':
                xmlstr += CE_NC_XML_MERGE_INTF_STATUS % (
                    intfs_list[i]['ifName'], 'up')
                self.updates_cmd.append("undo shutdown")
                if_change = True

            # set portswitch default
            if self.is_portswitch_enalbe(self.intf_type) \
                    and intfs_list[i]["isL2SwitchPort"] != "true":
                xmlstr += CE_NC_XML_MERGE_INTF_L2ENABLE % (
                    intfs_list[i]['ifName'], 'enable')
                self.updates_cmd.append("portswitch")
                if_change = True

            if if_change:
                change = True
            else:
                self.updates_cmd.pop()

        if not change:
            return

        conf_str = self.build_config_xml(xmlstr)
        try:
            con_obj = self.nc.set_config(config=conf_str)
            self.check_response(con_obj, "SET_INTFS_DEFAULT")
            self.changed = True
        except RPCError as e:
            self.module.fail_json(msg='Error: %s' % e.message)

    def check_params(self):
        """Check all input params"""

        if not self.interface and not self.interface_type:
            self.module.fail_json(
                msg='Error: Interface or interface_type must be set.')
        if self.interface and self.interface_type:
            self.module.fail_json(msg='Error: Interface or interface_type'
                                  ' can not be set at the same time.')

        # interface type check
        if self.interface:
            self.intf_type = self.get_interface_type(self.interface)
            if not self.intf_type:
                self.module.fail_json(msg='Error: interface name of %s'
                                      ' is error.' % self.interface)

        elif self.interface_type:
            self.intf_type = self.get_interface_type(self.interface_type)
            if not self.intf_type or self.intf_type != self.interface_type.replace(
                    " ", "").lower():
                self.module.fail_json(msg='Error: interface type of %s'
                                      ' is error.' % self.interface_type)

        if not self.intf_type:
            self.module.fail_json(
                msg='Error: interface or interface type %s is error.')

        # shutdown check
        if not self.is_admin_state_enable(self.intf_type) \
                and self.state == "present" and self.admin_state == "down":
            self.module.fail_json(msg='Error: The %s interface can not'
                                  ' be shutdown.' % self.intf_type)

        # absent check
        if not self.is_delete_enable(
                self.intf_type) and self.state == "absent":
            self.module.fail_json(msg='Error: The %s interface can not'
                                  ' be delete.' % self.intf_type)

        # port switch mode check
        if not self.is_portswitch_enalbe(self.intf_type)\
                and self.mode and self.state == "present":
            self.module.fail_json(msg='Error: The %s interface can not manage'
                                  ' Layer 2 or Layer 3 state.' %
                                  self.intf_type)

        # check description len
        if self.description:
            if len(self.description) > 242 \
                    or len(self.description.replace(' ', '')) < 1:
                self.module.fail_json(msg='Error: interface description '
                                      'is not in the range from 1 to 242.')

    def get_proposed(self):
        """get_proposed"""

        self.proposed['state'] = self.state
        if self.interface:
            self.proposed["interface"] = self.interface
        if self.interface_type:
            self.proposed["interface_type"] = self.interface_type

        if self.state == 'present':
            if self.description:
                self.proposed["description"] = self.description
            if self.mode:
                self.proposed["mode"] = self.mode
            if self.admin_state:
                self.proposed["admin_state"] = self.admin_state

        elif self.state == 'default':
            if self.description:
                self.proposed["description"] = ""
            if self.is_admin_state_enable(self.intf_type) and self.admin_state:
                self.proposed["admin_state"] = self.admin_state
            if self.is_portswitch_enalbe(self.intf_type) and self.mode:
                self.proposed["mode"] = self.mode

    def get_existing(self):
        """get_existing"""

        if self.intf_info:
            self.existing["interface"] = self.intf_info["ifName"]
            if self.is_admin_state_enable(self.intf_type):
                self.existing["admin_state"] = self.intf_info["ifAdminStatus"]
            self.existing["description"] = self.intf_info["ifDescr"]
            if self.is_portswitch_enalbe(self.intf_type):
                if self.intf_info["isL2SwitchPort"] == "true":
                    self.existing["mode"] = "layer2"
                else:
                    self.existing["mode"] = "layer3"

    def get_end_state(self):
        """get_end_state"""

        if self.intf_info:
            end_info = self.get_interface_dict(self.interface)
            if end_info:
                self.end_state["interface"] = end_info["ifName"]
                if self.is_admin_state_enable(self.intf_type):
                    self.end_state["admin_state"] = end_info["ifAdminStatus"]
                self.end_state["description"] = end_info["ifDescr"]
                if self.is_portswitch_enalbe(self.intf_type):
                    if end_info["isL2SwitchPort"] == "true":
                        self.end_state["mode"] = "layer2"
                    else:
                        self.end_state["mode"] = "layer3"

    def work(self):
        """worker"""

        self.check_params()

        # single interface config
        if self.interface:
            self.intf_info = self.get_interface_dict(self.interface)
            self.get_existing()
            if self.state == 'present':
                if not self.intf_info:
                    # create interface
                    self.create_interface\
                        (self.interface,
                         self.description,
                         self.admin_state,
                         self.mode)
                else:
                    # merge interface
                    if self.description or self.admin_state or self.mode:
                        self.merge_interface\
                            (self.interface,
                             self.description,
                             self.admin_state,
                             self.mode)

            elif self.state == 'absent':
                if self.intf_info:
                    # delete interface
                    self.delete_interface(self.interface)
                else:
                    # interface does not exists
                    self.module.fail_json(
                        msg='Error: interface does not exists.')

            else:  # default
                if not self.intf_info:
                    # error, interface does not exists
                    self.module.fail_json(
                        msg='Error: interface does not exists.')
                else:
                    self.default_interface(self.interface)

        # interface type config
        else:
            self.intfs_info = self.get_interfaces_dict()
            self.get_existing()
            if self.state == 'present':
                if self.intfs_info.get(self.intf_type.lower()):
                    if self.description or self.admin_state or self.mode:
                        self.merge_interfaces\
                            (self.intf_type,
                             self.description,
                             self.admin_state,
                             self.mode)
            elif self.state == 'absent':
                # delete all interface of this type
                if self.intfs_info.get(self.intf_type.lower()):
                    self.delete_interfaces(self.intf_type)

            else:
                # set interfaces config to default
                if self.intfs_info.get(self.intf_type.lower()):
                    self.default_interfaces(self.intf_type)
                else:
                    self.module.fail_json(
                        msg='Error: no interface in this type.')

        self.get_proposed()
        self.get_end_state()
        self.results['changed'] = self.changed
        self.results['proposed'] = self.proposed
        self.results['existing'] = self.existing
        self.results['end_state'] = self.end_state
        if self.changed:
            self.results['updates'] = self.updates_cmd
        else:
            self.results['updates'] = list()

        self.end_time = datetime.datetime.now()
        self.results['execute_time'] = str(self.end_time - self.start_time)

        self.module.exit_json(**self.results)
示例#35
0
def main():
    spec = dict(
        gather_subset=dict(default=['!config'], type='list')
    )

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

    gather_subset = module.params['gather_subset']

    runable_subsets = set()
    exclude_subsets = set()

    for subset in gather_subset:
        if subset == 'all':
            runable_subsets.update(VALID_SUBSETS)
            continue

        if subset.startswith('!'):
            subset = subset[1:]
            if subset == 'all':
                exclude_subsets.update(VALID_SUBSETS)
                continue
            exclude = True
        else:
            exclude = False

        if subset not in VALID_SUBSETS:
            module.fail_json(msg='Bad subset')

        if exclude:
            exclude_subsets.add(subset)
        else:
            runable_subsets.add(subset)

    if not runable_subsets:
        runable_subsets.update(VALID_SUBSETS)

    runable_subsets.difference_update(exclude_subsets)
    runable_subsets.add('default')

    facts = dict()
    facts['gather_subset'] = list(runable_subsets)

    instances = list()
    for key in runable_subsets:
        instances.append(FACT_SUBSETS[key](module))

    failed_commands = list()

    try:
        for inst in instances:
            inst.populate()
            failed_commands.extend(inst.failed_commands)
            facts.update(inst.facts)
    except Exception:
        exc = get_exception()
        module.fail_json(msg=str(exc))

    ansible_facts = dict()
    for key, value in iteritems(facts):
        key = 'ansible_net_%s' % key
        ansible_facts[key] = value

    module.exit_json(ansible_facts=ansible_facts, failed_commands=failed_commands)
示例#36
0
def main():
    spec = dict(
        # { command: <str>, output: <str>, prompt: <str>, response: <str> }
        commands=dict(type='list', required=True),

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

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

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

    commands = list(parse_commands(module))
    conditionals = module.params['wait_for'] or list()

    warnings = list()

    runner = CommandRunner(module)

    try:
        # This tries to detect command mode.
        runner.add_command('tmsh')
        runner.run()
        shell = "bash"
    except NetworkError:
        shell = "tmsh"

    # Resets the runner because raised exceptions do not remove the
    # erroneous commands
    module.disconnect()
    runner.commands = []
    runner.module.cli._commands = []


    for cmd in commands:
        cmd = strip_tmsh_prefix(cmd)

        if module.check_mode and not is_config_mode_command(cmd):
            warnings.append('only show or list commands are supported when '
                            'using check mode, not executing `%s`'
                            % cmd['command'])
        else:
            if is_config_mode_command(cmd):
                module.fail_json(msg='bigip_command does not support running '
                                     'config mode commands. Please use '
                                     'bigip_config instead')
            try:
                if shell == 'tmsh':
                    disable_pager = dict(
                        output=None,
                        command='modify cli preference pager disabled'
                    )
                    runner.add_command(**disable_pager)
                    runner.add_command(**cmd)
                else:
                    disable_pager = dict(
                        output=None,
                        command='tmsh modify cli preference pager disabled'
                    )
                    cmd['command'] = 'tmsh ' + cmd['command']
                    runner.add_command(**disable_pager)
                    runner.add_command(**cmd)
            except AddCommandError:
                exc = get_exception()
                warnings.append('duplicate command detected: %s' % cmd)

    try:
        for item in conditionals:
            runner.add_conditional(item)
    except AddConditionError:
        exc = get_exception()
        module.fail_json(msg=str(exc), condition=exc.condition)

    runner.retries = module.params['retries']
    runner.interval = module.params['interval']
    runner.match = module.params['match']

    try:
        runner.run()
    except FailedConditionsError:
        exc = get_exception()
        module.fail_json(msg=str(exc), failed_conditions=exc.failed_conditions)
    except FailedConditionalError:
        exc = get_exception()
        module.fail_json(msg=str(exc), failed_conditional=exc.failed_conditional)
    except NetworkError:
        exc = get_exception()
        module.fail_json(msg=str(exc), **exc.kwargs)

    result = dict(changed=False)

    result['stdout'] = list()
    for cmd in commands:
        try:
            output = runner.get_command(cmd['command'], cmd.get('output'))
        except ValueError:
            output = 'command not executed due to check_mode, see warnings'
        result['stdout'].append(output)

    result['warnings'] = warnings
    result['stdout_lines'] = list(to_lines(result['stdout']))

    module.exit_json(**result)
示例#37
0
def main():
    spec = dict(gather_subset=dict(default=['!config'], type='list'))

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

    gather_subset = module.params['gather_subset']

    runable_subsets = set()
    exclude_subsets = set()

    for subset in gather_subset:
        if subset == 'all':
            runable_subsets.update(VALID_SUBSETS)
            continue

        if subset.startswith('!'):
            subset = subset[1:]
            if subset == 'all':
                exclude_subsets.update(VALID_SUBSETS)
                continue
            exclude = True
        else:
            exclude = False

        if subset not in VALID_SUBSETS:
            module.fail_json(msg='Bad subset')

        if exclude:
            exclude_subsets.add(subset)
        else:
            runable_subsets.add(subset)

    if not runable_subsets:
        runable_subsets.update(VALID_SUBSETS)

    runable_subsets.difference_update(exclude_subsets)
    runable_subsets.add('default')

    facts = dict()
    facts['gather_subset'] = list(runable_subsets)

    runner = CommandRunner(module)

    instances = list()
    for key in runable_subsets:
        runs = FACT_SUBSETS[key](runner)
        instances.append(runs)

    runner.run()

    try:
        for inst in instances:
            inst.populate()
            facts.update(inst.facts)
    except Exception:
        module.exit_json(out=module.from_json(runner.items))

    ansible_facts = dict()
    for key, value in facts.iteritems():
        key = 'ansible_net_%s' % key
        ansible_facts[key] = value

    module.exit_json(ansible_facts=ansible_facts)
示例#38
0
class CE_MTU(object):
    """ CE_MTU"""

    def __init__(self, argument_spec, ):
        self.start_time = datetime.datetime.now()
        self.end_time = None
        self.spec = argument_spec
        self.module = None
        self.nc = None
        self.init_module()

        # interface info
        self.interface = self.module.params['interface']
        self.mtu = self.module.params['mtu']
        self.state = self.module.params['state']
        self.jbfMax = self.module.params['jumbo_max'] or None
        self.jbfMin = self.module.params['jumbo_min'] or None
        self.jbfConfig = list()

        # host info
        self.host = self.module.params['host']
        self.username = self.module.params['username']
        self.port = self.module.params['port']

        # state
        self.changed = False
        self.updates_cmd = list()
        self.results = dict()
        self.proposed = dict()
        self.existing = dict()
        self.end_state = dict()
        self.intf_info = dict()         # one interface info
        self.intf_type = None           # loopback tunnel ...

        # init netconf connect
        self.init_netconf()

    def init_module(self):
        """ init_module"""

        self.module = NetworkModule(
            argument_spec=self.spec, supports_check_mode=True)

    def init_netconf(self):
        """ init_netconf"""

        if HAS_NCCLIENT:
            self.nc = get_netconf(host=self.host, port=self.port,
                                  username=self.username,
                                  password=self.module.params['password'])
        else:
            self.module.fail_json(
                msg='Error: No ncclient package, please install it.')

    def check_response(self, con_obj, xml_name):
        """Check if response message is already succeed."""

        xml_str = con_obj.xml
        if "<ok/>" not in xml_str:
            self.module.fail_json(msg='Error: %s failed.' % xml_name)

    def build_config_xml(self, xmlstr):
        """ build_config_xml"""

        return '<config> ' + xmlstr + ' </config>'

    def get_interface_dict(self, ifname):
        """ get one interface attributes dict."""
        intf_info = dict()
        conf_str = CE_NC_GET_INTF % ifname
        try:
            con_obj = self.nc.get_config(filter=conf_str)
        except RPCError as e:
            self.module.fail_json(msg='Error: %s' % e.message)

        if "<data/>" in con_obj.xml:
            return intf_info

        intf = re.findall(
            r'.*<ifName>(.*)</ifName>.*\s*'
            r'<isL2SwitchPort>(.*)</isL2SwitchPort>.*\s*'
            r'<ifMtu>(.*)</ifMtu>.*', con_obj.xml)

        if intf:
            intf_info = dict(ifName=intf[0][0],
                             isL2SwitchPort=intf[0][1],
                             ifMtu=intf[0][2])

        return intf_info

    def get_interface_type(self, interface):
        """Gets the type of interface, such as 10GE, ETH-TRUNK, VLANIF..."""

        if interface is None:
            return None

        iftype = None

        if interface.upper().startswith('GE'):
            iftype = 'ge'
        elif interface.upper().startswith('10GE'):
            iftype = '10ge'
        elif interface.upper().startswith('25GE'):
            iftype = '25ge'
        elif interface.upper().startswith('4X10GE'):
            iftype = '4x10ge'
        elif interface.upper().startswith('40GE'):
            iftype = '40ge'
        elif interface.upper().startswith('100GE'):
            iftype = '100ge'
        elif interface.upper().startswith('VLANIF'):
            iftype = 'vlanif'
        elif interface.upper().startswith('LOOPBACK'):
            iftype = 'loopback'
        elif interface.upper().startswith('METH'):
            iftype = 'meth'
        elif interface.upper().startswith('ETH-TRUNK'):
            iftype = 'eth-trunk'
        elif interface.upper().startswith('VBDIF'):
            iftype = 'vbdif'
        elif interface.upper().startswith('NVE'):
            iftype = 'nve'
        elif interface.upper().startswith('TUNNEL'):
            iftype = 'tunnel'
        elif interface.upper().startswith('ETHERNET'):
            iftype = 'ethernet'
        elif interface.upper().startswith('FCOE-PORT'):
            iftype = 'fcoe-port'
        elif interface.upper().startswith('FABRIC-PORT'):
            iftype = 'fabric-port'
        elif interface.upper().startswith('STACK-PORT'):
            iftype = 'stack-Port'
        elif interface.upper().startswith('NULL'):
            iftype = 'null'
        else:
            return None

        return iftype.lower()

    def is_portswitch_enalbe(self, iftype):
        """"[undo] portswitch"""

        type_list = ['ge', '10ge', '25ge',
                     '4x10ge', '40ge', '100ge', 'eth-trunk']
        if iftype in type_list:
            return True
        else:
            return False

    def prase_jumboframe_para(self, configStr):
        """ prase_jumboframe_para"""

        interface_cli = "interface %s" % self.interface
        if configStr.find(interface_cli) == -1:
            self.module.fail_json(
                    msg='Interface does not exist.')
        npos1 = configStr.index(interface_cli)

        npos2 = configStr.index('#', npos1)
        configStrTmp = configStr[npos1:npos2]
        try:
            npos3 = configStrTmp.index('jumboframe enable')
        except ValueError:
            # return default vale
            return [9216, 1518]
        npos4 = configStrTmp.index('\n', npos3)

        configStrTmp = configStrTmp[npos3:npos4]
        return re.findall(r'([0-9]+)', configStrTmp)

    def excute_command(self, commands):
        """ excute_command"""

        runner = CommandRunner(self.module)
        for cmd in commands:
            try:
                runner.add_command(**cmd)
            except AddCommandError:
                exc = get_exception()
                self.module.fail_json(
                    msg='duplicate command detected: %s' % cmd)
        runner.retries = self.module.params['retries']
        runner.interval = self.module.params['interval']
        runner.match = self.module.params['match']

        try:
            runner.run()
        except FailedConditionsError:
            exc = get_exception()
            self.module.fail_json(
                msg=str(exc), failed_conditions=exc.failed_conditions)
        except FailedConditionalError:
            exc = get_exception()
            self.module.fail_json(
                msg=str(exc), failed_conditional=exc.failed_conditional)
        except NetworkError:
            exc = get_exception()
            self.module.fail_json(msg=str(exc), **exc.kwargs)

        for cmd in commands:
            try:
                output = runner.get_command(cmd['command'], cmd.get('output'))
            except ValueError:
                self.module.fail_json(
                    msg='command not executed due to check_mode, see warnings')
        return output

    def get_jumboframe_config(self):
        """ get_jumboframe_config"""

        commands = list()
        cmd = {'output': None, 'command': 'display current-configuration'}
        commands.append(cmd)
        output = self.excute_command(commands)
        return self.prase_jumboframe_para(output)

    def set_jumboframe(self):
        """ set_jumboframe"""

        if self.state == "present":
            if not self.jbfMax or not self.jbfMin:
                return

            jbfValue = self.get_jumboframe_config()
            self.jbfConfig = copy.deepcopy(jbfValue)
            if len(jbfValue) == 1:
                jbfValue.append("1518")
                self.jbfConfig.append("1518")
            if not self.jbfMax:
                return

            if (len(jbfValue) > 2) or (len(jbfValue) == 0):
                self.module.fail_json(
                    msg='Error: Get jubmoframe config value num error.')
            if (self.jbfMin is None):
                if (jbfValue[0] == self.jbfMax):
                    return
            else:
                if (jbfValue[0] == self.jbfMax) \
                        and (jbfValue[1] == self.jbfMin):
                    return
            if (jbfValue[0] != self.jbfMax):
                jbfValue[0] = self.jbfMax
            if (jbfValue[1] != self.jbfMin) and (self.jbfMin is not None):
                jbfValue[1] = self.jbfMin
            else:
                jbfValue.pop(1)
        else:
            jbfValue = self.get_jumboframe_config()
            self.jbfConfig = copy.deepcopy(jbfValue)
            if (jbfValue == [9216, 1518]):
                return
            jbfValue = [9216, 1518]

        # excute commands
        commands = list()
        cmd1 = {'output': None, 'command': 'system-view'}
        commands.append(cmd1)

        cmd2 = {'output': None, 'command': ''}
        cmd2['command'] = "interface %s" % self.interface
        commands.append(cmd2)

        if len(jbfValue) == 2:
            self.jbf_cli = "jumboframe enable %s %s" % (
                jbfValue[0], jbfValue[1])
        else:
            self.jbf_cli = "jumboframe enable %s" % (jbfValue[0])
        cmd3 = {'output': None, 'command': ''}
        cmd3['command'] = self.jbf_cli
        commands.append(cmd3)

        cmd4 = {'output': None, 'command': ''}
        cmd4['command'] = 'commit'
        commands.append(cmd4)
        self.excute_command(commands)

        self.changed = True
        if self.state == "present":
            if self.jbfMin:
                self.updates_cmd.append(
                    "jumboframe enable %s %s" % (self.jbfMax, self.jbfMin))
            else:
                self.updates_cmd.append("jumboframe enable %s" % (self.jbfMax))
        else:
            self.updates_cmd.append("undo jumboframe enable")

        return

    def merge_interface(self, ifname, mtu):
        """ Merge interface mtu."""

        xmlstr = ''
        change = False
        self.updates_cmd.append("interface %s" % ifname)
        if self.state == "present":
            if mtu and self.intf_info["ifMtu"] != mtu:
                xmlstr += CE_NC_XML_MERGE_INTF_MTU % (ifname, mtu)
                self.updates_cmd.append("mtu %s" % mtu)
                change = True
        else:
            if self.intf_info["ifMtu"] != '1500':
                xmlstr += CE_NC_XML_MERGE_INTF_MTU % (ifname, '1500')
                self.updates_cmd.append("undo mtu")
                change = True

        if not change:
            return

        conf_str = self.build_config_xml(xmlstr)

        try:
            con_obj = self.nc.set_config(config=conf_str)
            self.check_response(con_obj, "MERGE_INTF_MTU")
            self.changed = True
        except RPCError as e:
            self.module.fail_json(msg='Error: %s' % e.message)

    def IsInterfaceSupportSetJumboframe(self, interface):
        if interface is None:
            return False
        support_flag = False
        if interface.upper().startswith('GE'):
            support_flag = True
        elif interface.upper().startswith('10GE'):
            support_flag = True
        elif interface.upper().startswith('25GE'):
            support_flag = True
        elif interface.upper().startswith('4X10GE'):
            support_flag = True
        elif interface.upper().startswith('40GE'):
            support_flag = True
        elif interface.upper().startswith('100GE'):
            support_flag = True
        else:
            support_flag = False
        return support_flag

    def check_params(self):
        """Check all input params"""

        # interface type check
        if self.interface:
            self.intf_type = self.get_interface_type(self.interface)
            if not self.intf_type:
                self.module.fail_json(
                    msg='Error: Interface name of %s '
                        'is error.' % self.interface)

        if not self.intf_type:
            self.module.fail_json(
                msg='Error: Interface %s is error.')

        # mtu check mtu
        if self.mtu:
            if not self.mtu.isdigit():
                self.module.fail_json(msg='Error: Mtu is invalid.')
            # check mtu range
            if int(self.mtu) < 46 or int(self.mtu) > 9600:
                self.module.fail_json(
                    msg='Error: Mtu is not in the range from 46 to 9600.')
        # get interface info
        self.intf_info = self.get_interface_dict(self.interface)
        if not self.intf_info:
            self.module.fail_json(msg='Error: interface does not exists.')

        # check interface
        if self.intf_info['isL2SwitchPort'] == 'true':
            self.module.fail_json(msg='Error: L2Switch Port can not set mtu.')

        # check interface can set jumbo frame
        if self.state == 'present':
            if self.jbfMax:
                if not self.IsInterfaceSupportSetJumboframe(self.interface):
                    self.module.fail_json(
                        msg='Error: Interface %s does not support jumboframe set.' % self.interface)
                if not self.jbfMax.isdigit():
                    self.module.fail_json(msg='Error: Max jumboframe is not digit.')
                if (int(self.jbfMax) > 12288) or (int(self.jbfMax) < 1536):
                    self.module.fail_json(
                        msg='Error: Max jumboframe is between 1536 to 12288.')

            if self.jbfMin:
                if not self.jbfMin.isdigit():
                    self.module.fail_json(
                        msg='Error: Min jumboframe is not digit.')
                if not self.jbfMax:
                    self.module.fail_json(
                        msg='Error: please specify max jumboframe value.')
                if (int(self.jbfMin) > self.jbfMax) or (int(self.jbfMin) < 1518):
                    self.module.fail_json(
                        msg='Error: Min jumboframe is between '
                            '1518 to jumboframe max value.')

            if self.jbfMin is not None:
                if self.jbfMax is None:
                    self.module.fail_json(
                        msg='Error: please input MAX jumboframe '
                            'value.')


    def get_proposed(self):
        """ get_proposed"""

        self.proposed['state'] = self.state
        if self.interface:
            self.proposed["interface"] = self.interface

        if self.state == 'present':
            if self.mtu:
                self.proposed["mtu"] = self.mtu
            if self.jbfMax:
                if self.jbfMin:
                    self.proposed["jumboframe"] = "jumboframe enable %s %s" % (
                        self.jbfMax, self.jbfMin)
                else:
                    self.proposed[
                        "jumboframe"] = "jumboframe enable %s %s" % (self.jbfMax, 1518)

    def get_existing(self):
        """ get_existing"""

        if self.intf_info:
            self.existing["interface"] = self.intf_info["ifName"]
            self.existing["mtu"] = self.intf_info["ifMtu"]

        if self.intf_info:
            if not self.existing["interface"]:
                self.existing["interface"] = self.interface

            if len(self.jbfConfig) != 2:
                return

            self.existing["jumboframe"] = "jumboframe enable %s %s" % (
                self.jbfConfig[0], self.jbfConfig[1])

    def get_end_state(self):
        """ get_end_state"""

        if self.intf_info:
            end_info = self.get_interface_dict(self.interface)
            if end_info:
                self.end_state["interface"] = end_info["ifName"]
                self.end_state["mtu"] = end_info["ifMtu"]
        if self.intf_info:
            if not self.end_state["interface"]:
                self.end_state["interface"] = self.interface

            if self.state == 'absent':
                self.end_state["jumboframe"] = "jumboframe enable %s %s" % (
                    9216, 1518)
            elif not self.jbfMax and not self.jbfMin:
                if len(self.jbfConfig) != 2:
                    return
                self.end_state["jumboframe"] = "jumboframe enable %s %s" % (
                    self.jbfConfig[0], self.jbfConfig[1])
            elif self.jbfMin:
                self.end_state["jumboframe"] = "jumboframe enable %s %s" % (
                    self.jbfMax, self.jbfMin)
            else:
                self.end_state[
                    "jumboframe"] = "jumboframe enable %s %s" % (self.jbfMax, 1518)

    def work(self):
        """worker"""
        self.check_params()

        self.get_proposed()

        self.merge_interface(self.interface, self.mtu)
        self.set_jumboframe()

        self.get_existing()
        self.get_end_state()
        self.results['changed'] = self.changed
        self.results['proposed'] = self.proposed
        self.results['existing'] = self.existing
        self.results['end_state'] = self.end_state
        if self.changed:
            self.results['updates'] = self.updates_cmd
        else:
            self.results['updates'] = list()

        self.end_time = datetime.datetime.now()
        self.results['execute_time'] = str(self.end_time - self.start_time)

        self.module.exit_json(**self.results)
示例#39
0
def main():
    """ Module main function """

    argument_spec = dict(
        state=dict(choices=['present', 'absent'], default='present'),
        acl_number=dict(type='str'),
        usm_user_name=dict(type='str'),
        remote_engine_id=dict(type='str'),
        user_group=dict(type='str'),
        auth_protocol=dict(choices=['noAuth', 'md5', 'sha']),
        auth_key=dict(type='str', no_log=True),
        priv_protocol=dict(choices=[
            'noPriv', 'des56', '3des168', 'aes128', 'aes192', 'aes256'
        ]),
        priv_key=dict(type='str', no_log=True),
        aaa_local_user=dict(type='str'))

    if not HAS_NCCLIENT:
        raise Exception("the ncclient library is required")

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

    changed = False
    proposed = dict()
    existing = dict()
    end_state = dict()
    updates = []

    state = module.params['state']
    host = module.params['host']
    port = module.params['port']
    username = module.params['username']
    password = module.params['password']
    acl_number = module.params['acl_number']
    usm_user_name = module.params['usm_user_name']
    remote_engine_id = module.params['remote_engine_id']
    user_group = module.params['user_group']
    auth_protocol = module.params['auth_protocol']
    auth_key = module.params['auth_key']
    priv_protocol = module.params['priv_protocol']
    priv_key = module.params['priv_key']
    aaa_local_user = module.params['aaa_local_user']

    snmp_user_obj = SnmpUser(host=host,
                             port=port,
                             username=username,
                             password=password)

    if not snmp_user_obj:
        module.fail_json(msg='Error: Init module failed.')

    # get proposed
    proposed["state"] = state
    if acl_number:
        proposed["acl_number"] = acl_number
    if usm_user_name:
        proposed["usm_user_name"] = usm_user_name
    if remote_engine_id:
        proposed["remote_engine_id"] = remote_engine_id
    if user_group:
        proposed["user_group"] = user_group
    if auth_protocol:
        proposed["auth_protocol"] = auth_protocol
    if auth_key:
        proposed["auth_key"] = auth_key
    if priv_protocol:
        proposed["priv_protocol"] = priv_protocol
    if priv_key:
        proposed["priv_key"] = priv_key
    if aaa_local_user:
        proposed["aaa_local_user"] = aaa_local_user

    snmp_v3_usm_user_rst = snmp_user_obj.check_snmp_v3_usm_user_args(
        module=module)
    snmp_v3_local_user_rst = snmp_user_obj.check_snmp_v3_local_user_args(
        module=module)

    snmp_user_obj.get_snmp_local_engine(module=module)

    # state exist snmp v3 user config
    exist_tmp = dict()
    for item in snmp_v3_usm_user_rst:
        if item != "need_cfg":
            exist_tmp[item] = snmp_v3_usm_user_rst[item]
    if exist_tmp:
        existing["snmp usm user"] = exist_tmp

    exist_tmp = dict()
    for item in snmp_v3_local_user_rst:
        if item != "need_cfg":
            exist_tmp[item] = snmp_v3_local_user_rst[item]
    if exist_tmp:
        existing["snmp local user"] = exist_tmp

    if state == "present":
        if snmp_v3_usm_user_rst["need_cfg"]:
            if len(snmp_v3_usm_user_rst["usm_user_info"]) != 0:
                cmd = snmp_user_obj.merge_snmp_v3_usm_user(module=module)
                changed = True
                updates.append(cmd)
            else:
                cmd = snmp_user_obj.create_snmp_v3_usm_user(module=module)
                changed = True
                updates.append(cmd)

        if snmp_v3_local_user_rst["need_cfg"]:
            if len(snmp_v3_local_user_rst["local_user_info"]) != 0:
                cmd = snmp_user_obj.merge_snmp_v3_local_user(module=module)
                changed = True
                updates.append(cmd)
            else:
                cmd = snmp_user_obj.create_snmp_v3_local_user(module=module)
                changed = True
                updates.append(cmd)

    else:
        if snmp_v3_usm_user_rst["need_cfg"]:
            cmd = snmp_user_obj.delete_snmp_v3_usm_user(module=module)
            changed = True
            updates.append(cmd)
        if snmp_v3_local_user_rst["need_cfg"]:
            cmd = snmp_user_obj.delete_snmp_v3_local_user(module=module)
            changed = True
            updates.append(cmd)

    # state exist snmp v3 user config
    snmp_v3_usm_user_rst = snmp_user_obj.check_snmp_v3_usm_user_args(
        module=module)
    end_tmp = dict()
    for item in snmp_v3_usm_user_rst:
        if item != "need_cfg":
            end_tmp[item] = snmp_v3_usm_user_rst[item]
    if end_tmp:
        end_state["snmp usm user"] = end_tmp

    snmp_v3_local_user_rst = snmp_user_obj.check_snmp_v3_local_user_args(
        module=module)
    end_tmp = dict()
    for item in snmp_v3_local_user_rst:
        if item != "need_cfg":
            end_tmp[item] = snmp_v3_local_user_rst[item]
    if end_tmp:
        end_state["snmp local user"] = end_tmp

    results = dict()
    results['proposed'] = proposed
    results['existing'] = existing
    results['changed'] = changed
    results['end_state'] = end_state
    results['updates'] = updates

    module.exit_json(**results)
示例#40
0
def main():
    spec = dict(
        # { command: <str>, output: <str>, prompt: <str>, response: <str> }
        commands=dict(type='list', required=True),

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

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

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

    commands = list(parse_commands(module))
    conditionals = module.params['wait_for'] or list()

    warnings = list()

    runner = CommandRunner(module)

    for cmd in commands:
        if module.check_mode and not cmd['command'].startswith('show'):
            warnings.append('only show commands are supported when using '
                            'check mode, not executing `%s`' % cmd['command'])
        else:
            if cmd['command'].startswith('conf'):
                module.fail_json(msg='eos_command does not support running '
                                     'config mode commands.  Please use '
                                     'eos_config instead')
            try:
                runner.add_command(**cmd)
            except AddCommandError:
                exc = get_exception()
                warnings.append('duplicate command detected: %s' % cmd)

    try:
        for item in conditionals:
            runner.add_conditional(item)
    except AddConditionError:
        exc = get_exception()
        module.fail_json(msg=str(exc), condition=exc.condition)


    runner.retries = module.params['retries']
    runner.interval = module.params['interval']
    runner.match = module.params['match']

    try:
        runner.run()
    except FailedConditionsError:
        exc = get_exception()
        module.fail_json(msg=str(exc), failed_conditions=exc.failed_conditions)
    except FailedConditionalError:
        exc = get_exception()
        module.fail_json(msg=str(exc), failed_conditional=exc.failed_conditional)
    except NetworkError:
        exc = get_exception()
        module.fail_json(msg=str(exc), **exc.kwargs)

    result = dict(changed=False, stdout=list())

    for cmd in commands:
        try:
            output = runner.get_command(cmd['command'], cmd.get('output'))
        except ValueError:
            output = 'command not executed due to check_mode, see warnings'
        result['stdout'].append(output)

    result['warnings'] = warnings
    result['stdout_lines'] = list(to_lines(result['stdout']))

    module.exit_json(**result)
def main():
    spec = dict(gather_subset=dict(default=['!config'], type='list'))

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

    gather_subset = module.params['gather_subset']

    runable_subsets = set()
    exclude_subsets = set()

    for subset in gather_subset:
        if subset == 'all':
            runable_subsets.update(VALID_SUBSETS)
            continue

        if subset.startswith('!'):
            subset = subset[1:]
            if subset == 'all':
                exclude_subsets.update(VALID_SUBSETS)
                continue
            exclude = True
        else:
            exclude = False

        if subset not in VALID_SUBSETS:
            module.fail_json(msg='Bad subset')

        if exclude:
            exclude_subsets.add(subset)
        else:
            runable_subsets.add(subset)

    if not runable_subsets:
        runable_subsets.update(VALID_SUBSETS)

    runable_subsets.difference_update(exclude_subsets)
    runable_subsets.add('default')

    facts = dict()
    facts['gather_subset'] = list(runable_subsets)

    instances = list()
    for key in runable_subsets:
        instances.append(FACT_SUBSETS[key](module))

    failed_commands = list()

    try:
        for inst in instances:
            inst.populate()
            failed_commands.extend(inst.failed_commands)
            facts.update(inst.facts)
    except Exception as exc:
        module.fail_json(msg=to_native(exc), exception=traceback.format_exc())

    ansible_facts = dict()
    for key, value in iteritems(facts):
        key = 'ansible_net_%s' % key
        ansible_facts[key] = value

    module.exit_json(ansible_facts=ansible_facts,
                     failed_commands=failed_commands)
示例#42
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_config=dict(type='bool', default=False),
                         backup_config=dict(type='bool', default=False))
    argument_spec.update(ios_argument_spec)

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

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

    module.check_mode = not module.params['update_config']

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

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

    warnings = list()
    invoke('check_args', module, warnings)

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

    candidate = get_candidate(module)

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

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

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

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

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

        if not module.check_mode:
            response = load_config(module, commands, nodiff=True)
            result.update(**response)

        result['changed'] = True

    result['updates'] = commands
    result['connected'] = module.connected

    module.exit_json(**result)
示例#43
0
def main():

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

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

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

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

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

    candidate = get_candidate(module)

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

    else:
        configobjs = candidate.items

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

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

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

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

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

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

        result['changed'] = True

    result['updates'] = commands

    module.exit_json(**result)
示例#44
0
def main():
    spec = dict(
        # { command: <str>, output: <str>, prompt: <str>, response: <str> }
        commands=dict(type='list', required=True),

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

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

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

    commands = list(parse_commands(module))
    conditionals = module.params['wait_for'] or list()

    warnings = list()

    runner = CommandRunner(module)

    try:
        # This tries to detect command mode.
        runner.add_command('tmsh')
        runner.run()
        shell = "bash"
    except NetworkError:
        shell = "tmsh"

    # Resets the runner because raised exceptions do not remove the
    # erroneous commands
    module.disconnect()
    runner.commands = []
    runner.module.cli._commands = []

    for cmd in commands:
        cmd = strip_tmsh_prefix(cmd)

        if module.check_mode and not is_config_mode_command(cmd):
            warnings.append('only show or list commands are supported when '
                            'using check mode, not executing `%s`'
                            % cmd['command'])
        else:
            if is_config_mode_command(cmd):
                module.fail_json(msg='bigip_command does not support running '
                                     'config mode commands. Please use '
                                     'bigip_config instead')
            try:
                if shell == 'tmsh':
                    disable_pager = dict(
                        output=None,
                        command='modify cli preference pager disabled'
                    )
                    runner.add_command(**disable_pager)
                    runner.add_command(**cmd)
                else:
                    disable_pager = dict(
                        output=None,
                        command='tmsh modify cli preference pager disabled'
                    )
                    cmd['command'] = 'tmsh ' + cmd['command']
                    runner.add_command(**disable_pager)
                    runner.add_command(**cmd)
            except AddCommandError:
                warnings.append('Duplicate command detected: %s' % cmd)

    try:
        for item in conditionals:
            runner.add_conditional(item)
    except AddConditionError:
        exc = get_exception()
        module.fail_json(msg=str(exc), condition=exc.condition)

    runner.retries = module.params['retries']
    runner.interval = module.params['interval']
    runner.match = module.params['match']

    try:
        runner.run()
    except FailedConditionsError:
        exc = get_exception()
        module.fail_json(msg=str(exc), failed_conditions=exc.failed_conditions)
    except FailedConditionalError:
        exc = get_exception()
        module.fail_json(msg=str(exc), failed_conditional=exc.failed_conditional)
    except NetworkError:
        exc = get_exception()
        module.fail_json(msg=str(exc), **exc.kwargs)

    result = dict(changed=False)

    result['stdout'] = list()
    for cmd in commands:
        try:
            output = runner.get_command(cmd['command'], cmd.get('output'))
        except ValueError:
            output = 'command not executed due to check_mode, see warnings'
        result['stdout'].append(output)

    result['warnings'] = warnings
    result['stdout_lines'] = list(to_lines(result['stdout']))

    module.exit_json(**result)
示例#45
0
def main():
    """ main entry point for module execution
    """

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

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

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

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

    result = dict(changed=False)

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

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

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

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

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

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

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

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

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

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

        result['updates'] = commands

    module.exit_json(**result)
示例#46
0
def main():
    spec = dict(
        gather_subset=dict(default=['!config'], type='list'),

        # the next two arguments are legacy from pre 2.2 ops_facts
        # these will be deprecated and ultimately removed
        config=dict(default=False, type='bool'),
        endpoints=dict(type='list'),

        transport=dict(default='cli', choices=['cli', 'rest'])
    )

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

    gather_subset = module.params['gather_subset']

    warnings = list()
    check_args(module, warnings)

    runable_subsets = set()
    exclude_subsets = set()

    for subset in gather_subset:
        if subset == 'all':
            runable_subsets.update(VALID_SUBSETS)
            continue

        if subset.startswith('!'):
            subset = subset[1:]
            if subset == 'all':
                exclude_subsets.update(VALID_SUBSETS)
                continue
            exclude = True
        else:
            exclude = False

        if subset not in VALID_SUBSETS:
            module.fail_json(msg='Bad subset')

        if exclude:
            exclude_subsets.add(subset)
        else:
            runable_subsets.add(subset)

    if not runable_subsets:
        runable_subsets.update(VALID_SUBSETS)

    runable_subsets.difference_update(exclude_subsets)
    runable_subsets.add('default')
    runable_subsets.add('legacy')

    facts = dict()
    facts['gather_subset'] = list(runable_subsets)

    runner = CommandRunner(module)

    instances = list()
    for key in runable_subsets:
        instances.append(FACT_SUBSETS[key](module, runner))

    if module.params['transport'] == 'cli':
        runner.run()

    try:
        for inst in instances:
            inst.populate()
            facts.update(inst.facts)
    except Exception:
        module.exit_json(out=module.from_json(runner.items))

    ansible_facts = dict()
    for key, value in iteritems(facts):
        # this is to maintain capability with ops_facts 2.1
        if key.startswith('_'):
            ansible_facts[key[1:]] = value
        else:
            key = 'ansible_net_%s' % key
            ansible_facts[key] = value

    module.exit_json(ansible_facts=ansible_facts, warnings=warnings)
class EvpnBgpRr(object):
    """Manange RR in BGP-EVPN address family view"""
    def __init__(self, argument_spec):
        self.spec = argument_spec
        self.module = None
        self.__init_module__()

        # RR configuration parameters
        self.as_number = self.module.params['as_number']
        self.bgp_instance = self.module.params['bgp_instance']
        self.peer_type = self.module.params['peer_type']
        self.peer = self.module.params['peer']
        self.bgp_evpn_enable = self.module.params['bgp_evpn_enable']
        self.reflect_client = self.module.params['reflect_client']
        self.policy_vpn_target = self.module.params['policy_vpn_target']

        self.commands = list()
        self.config = None
        self.bgp_evpn_config = ""
        self.cur_config = dict()
        self.conf_exist = False

        # host info
        self.host = self.module.params['host']
        self.username = self.module.params['username']
        self.password = self.module.params['password']
        self.port = self.module.params['port']

        # state
        self.changed = False
        self.updates_cmd = list()
        self.results = dict()
        self.proposed = dict()
        self.existing = dict()
        self.end_state = dict()

    def __init_module__(self):
        """init module"""

        self.module = NetworkModule(argument_spec=self.spec,
                                    connect_on_load=False,
                                    supports_check_mode=True)

    def cli_load_config(self, commands):
        """load config by cli"""

        if not self.module.check_mode:
            try:
                self.module.config.load_config(commands)
            except NetworkError:
                err = get_cli_exception()
                self.module.fail_json(msg=err)

    def is_bgp_view_exist(self):
        """judge whether BGP view has existed"""

        if self.bgp_instance:
            view_cmd = "bgp %s instance %s" % (self.as_number,
                                               self.bgp_instance)
        else:
            view_cmd = "bgp %s" % self.as_number

        return is_config_exist(self.config, view_cmd)

    def is_l2vpn_family_evpn_exist(self):
        """judge whether BGP-EVPN address family view has existed"""

        view_cmd = "l2vpn-family evpn"
        return is_config_exist(self.config, view_cmd)

    def is_reflect_client_exist(self):
        """judge whether reflect client is configured"""

        view_cmd = "peer %s reflect-client" % self.peer
        return is_config_exist(self.bgp_evpn_config, view_cmd)

    def is_policy_vpn_target_exist(self):
        """judge whether the VPN-Target filtering is enabled"""

        view_cmd = "undo policy vpn-target"
        if is_config_exist(self.bgp_evpn_config, view_cmd):
            return False
        else:
            return True

    def get_config_in_bgp_view(self):
        """get configuration in BGP view"""

        exp = " | section include"
        if self.as_number:
            if self.bgp_instance:
                exp += " bgp %s instance %s" % (self.as_number,
                                                self.bgp_instance)
            else:
                exp += " bgp %s" % self.as_number

        return self.module.config.get_config(include_defaults=False,
                                             regular=exp)

    def get_config_in_bgp_evpn_view(self):
        """get configuration in BGP_EVPN view"""

        self.bgp_evpn_config = ""
        if not self.config:
            return ""

        index = self.config.find("l2vpn-family evpn")
        if index == -1:
            return ""

        return self.config[index:]

    def get_current_config(self):
        """get current configuration"""

        if not self.as_number:
            self.module.fail_json(
                msg='Error: The value of as-number cannot be empty.')

        self.cur_config['bgp_exist'] = False
        self.cur_config['bgp_evpn_enable'] = 'false'
        self.cur_config['reflect_client'] = 'false'
        self.cur_config['policy_vpn_target'] = 'false'
        self.cur_config['peer_type'] = None
        self.cur_config['peer'] = None

        self.config = self.get_config_in_bgp_view()

        if not self.is_bgp_view_exist():
            return
        self.cur_config['bgp_exist'] = True

        if not self.is_l2vpn_family_evpn_exist():
            return
        self.cur_config['bgp_evpn_enable'] = 'true'

        self.bgp_evpn_config = self.get_config_in_bgp_evpn_view()
        if self.is_reflect_client_exist():
            self.cur_config['reflect_client'] = 'true'
            self.cur_config['peer_type'] = self.peer_type
            self.cur_config['peer'] = self.peer

        if self.is_policy_vpn_target_exist():
            self.cur_config['policy_vpn_target'] = 'true'

    def get_existing(self):
        """get existing config"""

        self.existing = dict(
            as_number=self.as_number,
            bgp_instance=self.bgp_instance,
            peer_type=self.cur_config['peer_type'],
            peer=self.cur_config['peer'],
            bgp_evpn_enable=self.cur_config['bgp_evpn_enable'],
            reflect_client=self.cur_config['reflect_client'],
            policy_vpn_target=self.cur_config['policy_vpn_target'])

    def get_proposed(self):
        """get proposed config"""

        self.proposed = dict(as_number=self.as_number,
                             bgp_instance=self.bgp_instance,
                             peer_type=self.peer_type,
                             peer=self.peer,
                             bgp_evpn_enable=self.bgp_evpn_enable,
                             reflect_client=self.reflect_client,
                             policy_vpn_target=self.policy_vpn_target)

    def get_end_state(self):
        """get end config"""

        self.get_current_config()
        self.end_state = dict(
            as_number=self.as_number,
            bgp_instance=self.bgp_instance,
            peer_type=self.cur_config['peer_type'],
            peer=self.cur_config['peer'],
            bgp_evpn_enable=self.cur_config['bgp_evpn_enable'],
            reflect_client=self.cur_config['reflect_client'],
            policy_vpn_target=self.cur_config['policy_vpn_target'])

    def show_result(self):
        """ show result"""

        self.results['changed'] = self.changed
        self.results['proposed'] = self.proposed
        self.results['existing'] = self.existing
        self.results['end_state'] = self.end_state
        if self.changed:
            self.results['updates'] = self.updates_cmd
        else:
            self.results['updates'] = list()

        self.module.exit_json(**self.results)

    def judge_if_config_exist(self):
        """ judge whether configuration has existed"""

        if self.bgp_evpn_enable and self.bgp_evpn_enable != self.cur_config[
                'bgp_evpn_enable']:
            return False

        if self.bgp_evpn_enable == 'false' and self.cur_config[
                'bgp_evpn_enable'] == 'false':
            return True

        if self.reflect_client and self.reflect_client == 'true':
            if self.peer_type and self.peer_type != self.cur_config[
                    'peer_type']:
                return False
            if self.peer and self.peer != self.cur_config['peer']:
                return False
        if self.reflect_client and self.reflect_client != self.cur_config[
                'reflect_client']:
            return False

        if self.policy_vpn_target and self.policy_vpn_target != self.cur_config[
                'policy_vpn_target']:
            return False

        return True

    def cli_add_command(self, command, undo=False):
        """add command to self.update_cmd and self.commands"""

        if undo and command.lower() not in ["quit", "return"]:
            cmd = "undo " + command
        else:
            cmd = command

        self.commands.append(cmd)  # set to device
        if command.lower() not in ["quit", "return"]:
            self.updates_cmd.append(cmd)  # show updates result

    def config_rr(self):
        """configure RR"""

        if self.conf_exist:
            return

        if self.bgp_instance:
            view_cmd = "bgp %s instance %s" % (self.as_number,
                                               self.bgp_instance)
        else:
            view_cmd = "bgp %s" % self.as_number
        self.cli_add_command(view_cmd)

        if self.bgp_evpn_enable == 'false':
            self.cli_add_command("  undo l2vpn-family evpn")
        else:
            self.cli_add_command("  l2vpn-family evpn")
            if self.reflect_client and self.reflect_client != self.cur_config[
                    'reflect_client']:
                if self.reflect_client == 'true':
                    self.cli_add_command("    peer %s enable" % self.peer)
                    self.cli_add_command("    peer %s reflect-client" %
                                         self.peer)
                else:
                    self.cli_add_command("    undo peer %s reflect-client" %
                                         self.peer)
                    self.cli_add_command("    undo peer %s enable" % self.peer)
            if self.cur_config['bgp_evpn_enable'] == 'true':
                if self.policy_vpn_target and self.policy_vpn_target != self.cur_config[
                        'policy_vpn_target']:
                    if self.policy_vpn_target == 'true':
                        self.cli_add_command("    policy vpn-target")
                    else:
                        self.cli_add_command("    undo policy vpn-target")
            else:
                if self.policy_vpn_target and self.policy_vpn_target == 'false':
                    self.cli_add_command("    undo policy vpn-target")

        if self.commands:
            self.cli_load_config(self.commands)
            self.changed = True

    def check_is_ipv4_addr(self):
        """check ipaddress validate"""

        rule1 = r'(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.'
        rule2 = r'(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])'
        ipv4_regex = '%s%s%s%s%s%s' % ('^', rule1, rule1, rule1, rule2, '$')

        return bool(re.match(ipv4_regex, self.peer))

    def check_params(self):
        """Check all input params"""

        if self.cur_config['bgp_exist'] == 'false':
            self.module.fail_json(msg="Error: BGP view doesnot exist.")

        if self.bgp_instance:
            if len(self.bgp_instance) < 1 or len(self.bgp_instance) > 31:
                self.module.fail_json(
                    msg=
                    "Error: The length of BGP instance-name must be between 1 or a string of 1 to and 31."
                )

        if self.as_number:
            if len(self.as_number) > 11 or len(self.as_number) == 0:
                self.module.fail_json(
                    msg='Error: The len of as_number %s is out of [1 - 11].' %
                    self.as_number)

        tmp_dict1 = dict(peer_type=self.peer_type,
                         peer=self.peer,
                         reflect_client=self.reflect_client)
        tmp_dict2 = dict((k, v) for k, v in tmp_dict1.items() if v is not None)
        if len(tmp_dict2) != 0 and len(tmp_dict2) != 3:
            self.module.fail_json(
                msg=
                'Error: The peer, peer_type, and reflect_client arguments must all exist or not exist.'
            )

        if self.peer_type:
            if self.peer_type == 'ipv4_address' and not self.check_is_ipv4_addr(
            ):
                self.module.fail_json(msg='Error: Illegal IPv4 address.')
            elif self.peer_type == 'group_name' and self.check_is_ipv4_addr():
                self.module.fail_json(
                    msg='Error: Ip address cannot be configured as group-name.'
                )

    def work(self):
        """excute task"""

        self.get_current_config()
        self.check_params()
        self.get_existing()
        self.get_proposed()
        self.conf_exist = self.judge_if_config_exist()

        self.config_rr()

        self.get_end_state()
        self.show_result()
示例#48
0
class Ntp(object):
    """ntp class"""

    def __init__(self, argument_spec):
        self.start_time = datetime.datetime.now()
        self.end_time = None
        self.spec = argument_spec
        self.module = None
        self.netconf = None
        self.mutually_exclusive = [('server', 'peer')]
        self.init_module()

        # ntp configration info
        self.server = self.module.params['server'] or None
        self.peer = self.module.params['peer'] or None
        self.key_id = self.module.params['key_id']
        self.is_preferred = self.module.params['is_preferred']
        self.vpn_name = self.module.params['vpn_name']
        self.interface = self.module.params['source_int'] or ""
        self.state = self.module.params['state']
        self.ntp_conf = dict()
        self.conf_exsit = False
        self.ip_ver = 'IPv4'

        # host info
        self.host = self.module.params['host']
        self.username = self.module.params['username']
        self.port = self.module.params['port']

        if self.server:
            self.peer_type = 'Server'
            self.address = self.server
        elif self.peer:
            self.peer_type = 'Peer'
            self.address = self.peer
        else:
            self.peer_type = None
            self.address = None

        self.check_params()

        # state
        self.changed = False
        self.updates_cmd = list()
        self.results = dict()
        self.proposed = dict()
        self.existing = list()
        self.end_state = list()

        # init netconf connect
        self.init_netconf()
        self.init_data()

    def init_data(self):
        """ init_data"""
        if self.interface is not None:
            self.interface = self.interface.lower()

        if not self.key_id:
            self.key_id = ""

        if not self.is_preferred:
            self.is_preferred = 'false'

    def init_module(self):
        """ init_module"""

        self.module = NetworkModule(argument_spec=self.spec, supports_check_mode=True,
                                    mutually_exclusive=self.mutually_exclusive)

    def init_netconf(self):
        """ init_netconf"""

        if HAS_NCCLIENT:
            self.netconf = get_netconf(host=self.host, port=self.port,
                                       username=self.username,
                                       password=self.module.params['password'])
        else:
            self.module.fail_json(
                msg='Error: No ncclient package, please install it.')

    def check_ipaddr_validate(self):
        """ check_ipaddr_validate"""
        rule1 = r'(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.'
        rule2 = r'(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])'
        ipv4_regex = '%s%s%s%s%s%s' % ('^', rule1, rule1, rule1, rule2, '$')
        ipv6_regex = '^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$'

        flag = False
        if bool(re.match(ipv4_regex, self.address)):
            flag = True
            self.ip_ver = "IPv4"
            if not self.ntp_ucast_ipv4_validate():
                flag = False
        elif bool(re.match(ipv6_regex, self.address)):
            flag = True
            self.ip_ver = "IPv6"
        else:
            flag = True
            self.ip_ver = "IPv6"

        if not flag:
            if self.peer_type == "Server":
                self.module.fail_json(msg='Illegal server ip-address.')
            else:
                self.module.fail_json(msg='Illegal peer ip-address.')

    def ntp_ucast_ipv4_validate(self):
        """ntp_ucast_ipv4_validate"""
        addr_list = re.findall(r'(.*)\.(.*)\.(.*)\.(.*)', self.address)
        if not addr_list:
            self.module.fail_json(msg='Match ip-address fail.')

        value = ((long(addr_list[0][0])) * 0x1000000) + (long(addr_list[0][1])\
                * 0x10000) + (long(addr_list[0][2]) * 0x100) + (long(addr_list[0][3]))
        if (value & (0xff000000) == 0x7f000000) or (value & (0xF0000000) == 0xF0000000) \
                or (value & (0xF0000000) == 0xE0000000) or (value == 0):
            return False
        return True

    def check_params(self):
        """Check all input params"""
        # check interface type
        if self.interface:
            intf_type = get_interface_type(self.interface)
            if not intf_type:
                self.module.fail_json(
                    msg='Error: Interface name of %s '
                        'is error.' % self.interface)

        if not self.server and not self.peer:
            self.module.fail_json(
                msg='Please supply the server or peer parameter')

        if self.vpn_name:
            if (len(self.vpn_name) < 1) or (len(self.vpn_name) > 31):
                self.module.fail_json(
                    msg='VPN name length is beetween 1 and 31.')

        if self.address:
            self.check_ipaddr_validate()

    def check_response(self, con_obj, xml_name):
        """Check if response message is already succeed."""

        xml_str = con_obj.xml
        if "<ok/>" not in xml_str:
            self.module.fail_json(msg='Error: %s failed.' % xml_name)

    def netconf_get_config(self, xml_str):
        """ netconf get config """

        try:
            con_obj = self.netconf.get_config(filter=xml_str)
        except RPCError:
            err = sys.exc_info()[1]
            self.module.fail_json(msg='Error: %s' % err.message.replace("\r\n", ""))

        return con_obj

    def netconf_set_config(self, xml_str, xml_name):
        """ netconf set config """

        try:
            con_obj = self.netconf.set_config(config=xml_str)
            self.check_response(con_obj, xml_name)
        except RPCError:
            err = sys.exc_info()[1]
            self.module.fail_json(msg='Error: %s' % err.message.replace("\r\n", ""))

        return con_obj

    def set_ntp(self, *args):
        """configure ntp parameters"""

        if self.state == 'present':
            if self.ip_ver == 'IPv4':
                xml_str = CE_NC_MERGE_NTP_CONFIG % (
                    args[0], args[1], '::', args[2], args[3], args[4], args[5], args[6])
            elif self.ip_ver == 'IPv6':
                xml_str = CE_NC_MERGE_NTP_CONFIG % (
                    args[0], '0.0.0.0', args[1], args[2], args[3], args[4], args[5], args[6])
            self.netconf_set_config(xml_str, "NTP_CORE_CONFIG")
        else:
            if self.ip_ver == 'IPv4':
                xml_str = CE_NC_DELETE_NTP_CONFIG % (
                    args[0], args[1], '::', args[2], args[3])
            elif self.ip_ver == 'IPv6':
                xml_str = CE_NC_DELETE_NTP_CONFIG % (
                    args[0], '0.0.0.0', args[1], args[2], args[3])
            self.netconf_set_config(xml_str, "UNDO_NTP_CORE_CONFIG")

    def config_ntp(self):
        """config ntp"""
        if self.state == "present":
            if self.address and not self.conf_exsit:
                self.set_ntp(self.ip_ver, self.address, self.peer_type,
                             self.vpn_name, self.key_id, self.is_preferred, self.interface)
                self.changed = True
        else:
            if self.address:
                self.set_ntp(self.ip_ver, self.address,
                             self.peer_type, self.vpn_name, '', '', '')
                self.changed = True

    def show_result(self):
        """show_result"""
        self.results['changed'] = self.changed
        self.results['proposed'] = self.proposed
        self.results['existing'] = self.existing
        self.results['end_state'] = self.end_state
        if self.changed:
            self.results['updates'] = self.updates_cmd
        else:
            self.results['updates'] = list()

        self.end_time = datetime.datetime.now()
        self.results['execute_time'] = str(self.end_time - self.start_time)

        self.module.exit_json(**self.results)

    def get_ntp_exist_config(self):
        """get ntp existed config"""
        ntp_config = list()
        conf_str = CE_NC_GET_NTP_CONFIG
        con_obj = self.netconf_get_config(conf_str)

        if "<data/>" in con_obj.xml:
            return ntp_config

        xml_str = con_obj.xml.replace('\r', '').replace('\n', '').\
            replace('xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"', "").\
            replace('xmlns="http://www.huawei.com/netconf/vrp"', "")

        # get all ntp config info
        root = ElementTree.fromstring(xml_str)
        ntpsite = root.findall("data/ntp/ntpUCastCfgs/ntpUCastCfg")
        for nexthop in ntpsite:
            ntp_dict = dict()
            for ele in nexthop:
                if ele.tag in ["addrFamily", "vpnName", "ifName", "ipv4Addr",
                               "ipv6Addr", "type", "isPreferred", "keyId"]:
                    ntp_dict[ele.tag] = ele.text

            ip_addr = ntp_dict['ipv6Addr']
            if ntp_dict['addrFamily'] == "IPv4":
                ip_addr = ntp_dict['ipv4Addr']
            if ntp_dict['ifName'] is None:
                ntp_dict['ifName'] = ""

            if self.state == "present":
                key_id = ntp_dict['keyId'] or ""
                cur_ntp_cfg = dict(vpn_name=ntp_dict['vpnName'], source_int=ntp_dict['ifName'].lower(), address=ip_addr,
                                   peer_type=ntp_dict['type'], prefer=ntp_dict['isPreferred'], key_id=key_id)
                exp_ntp_cfg = dict(vpn_name=self.vpn_name, source_int=self.interface.lower(), address=self.address,
                                   peer_type=self.peer_type, prefer=self.is_preferred, key_id=self.key_id)
                if cmp(cur_ntp_cfg, exp_ntp_cfg) == 0:
                    self.conf_exsit = True

            vpn_name = ntp_dict['vpnName']
            if ntp_dict['vpnName'] == "_public_":
                vpn_name = None

            if_name = ntp_dict['ifName']
            if if_name == "":
                if_name = None
            if self.peer_type == 'Server':
                ntp_config.append(dict(vpn_name=vpn_name,
                                       source_int=if_name, server=ip_addr,
                                       is_preferred=ntp_dict['isPreferred'], key_id=ntp_dict['keyId']))
            else:
                ntp_config.append(dict(vpn_name=vpn_name,
                                       source_int=if_name, peer=ip_addr,
                                       is_preferred=ntp_dict['isPreferred'], key_id=ntp_dict['keyId']))

        return ntp_config

    def get_existing(self):
        """get existing info"""
        if self.address:
            self.existing = self.get_ntp_exist_config()

    def get_proposed(self):
        """get proposed info"""
        if self.address:
            vpn_name = self.vpn_name
            if vpn_name == "_public_":
                vpn_name = None

            if_name = self.interface
            if if_name == "":
                if_name = None

            key_id = self.key_id
            if key_id == "":
                key_id = None
            if self.peer_type == 'Server':
                self.proposed = dict(state=self.state, vpn_name=vpn_name,
                                     source_int=if_name, server=self.address,
                                     is_preferred=self.is_preferred, key_id=key_id)
            else:
                self.proposed = dict(state=self.state, vpn_name=vpn_name,
                                     source_int=if_name, peer=self.address,
                                     is_preferred=self.is_preferred, key_id=key_id)

    def get_end_state(self):
        """get end state info"""
        if self.address:
            self.end_state = self.get_ntp_exist_config()

    def get_update_cmd(self):
        """get_update_cmd"""
        if self.conf_exsit:
            return

        cli_str = ""
        if self.state == "present":
            if self.address:
                if self.peer_type == 'Server':
                    if self.ip_ver == "IPv4":
                        cli_str = "%s %s" % (
                            "ntp unicast-server", self.address)
                    else:
                        cli_str = "%s %s" % (
                            "ntp unicast-server ipv6", self.address)
                elif self.peer_type == 'Peer':
                    if self.ip_ver == "IPv4":
                        cli_str = "%s %s" % ("ntp unicast-peer", self.address)
                    else:
                        cli_str = "%s %s" % (
                            "ntp unicast-peer ipv6", self.address)

                if self.key_id:
                    cli_str = "%s %s %s" % (
                        cli_str, "authentication-keyid", self.key_id)
                if self.interface:
                    cli_str = "%s %s %s" % (
                        cli_str, "source-interface", self.interface)
                if (self.vpn_name) and (self.vpn_name != '_public_'):
                    cli_str = "%s %s %s" % (
                        cli_str, "vpn-instance", self.vpn_name)
                if self.is_preferred == "true":
                    cli_str = "%s %s" % (cli_str, "preferred")
        else:
            if self.address:
                if self.peer_type == 'Server':
                    if self.ip_ver == "IPv4":
                        cli_str = "%s %s" % (
                            "undo ntp unicast-server", self.address)
                    else:
                        cli_str = "%s %s" % (
                            "undo ntp unicast-server ipv6", self.address)
                elif self.peer_type == 'Peer':
                    if self.ip_ver == "IPv4":
                        cli_str = "%s %s" % (
                            "undo ntp unicast-peer", self.address)
                    else:
                        cli_str = "%s %s" % (
                            "undo ntp unicast-peer ipv6", self.address)
                if (self.vpn_name) and (self.vpn_name != '_public_'):
                    cli_str = "%s %s" % (cli_str, self.vpn_name)

        self.updates_cmd.append(cli_str)

    def work(self):
        """work"""
        self.get_existing()
        self.get_proposed()

        self.config_ntp()

        self.get_update_cmd()
        self.get_end_state()
        self.show_result()
示例#49
0
def main():

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

        src=dict(type='path'),

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

        match=dict(default='line',
                   choices=['line', 'strict', 'exact', 'none']),
        replace=dict(default='line', choices=['line', 'block']),
        update=dict(choices=['merge', 'check'], default='merge'),
        save=dict(type='bool', default=False),
        config=dict(),
        backup=dict(type='bool', default=False)
    )

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

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

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

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

    if match != 'none':
        config = get_config(module)
        if parents:
            config = get_sublevel_config(config, module)
        configobjs = candidate.difference(config, match=match, replace=replace)
    else:
        configobjs = candidate.items

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

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

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

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

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

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

        result['changed'] = True

    result['updates'] = commands

    module.exit_json(**result)
示例#50
0
def get_network_module(**kwargs):
    try:
        return get_module(**kwargs)
    except NameError:
        return NetworkModule(**kwargs)
class SnmpLocation(object):
    """ Manages SNMP location configuration """
    def __init__(self, **kwargs):
        """ Class init """

        # module
        argument_spec = kwargs["argument_spec"]
        self.spec = argument_spec
        self.module = NetworkModule(argument_spec=self.spec,
                                    connect_on_load=False,
                                    supports_check_mode=True)

        # config
        self.cur_cfg = dict()

        # module args
        self.state = self.module.params['state']
        self.location = self.module.params['location']

        # state
        self.changed = False
        self.updates_cmd = list()
        self.results = dict()
        self.proposed = dict()
        self.existing = dict()
        self.end_state = dict()

    def check_args(self):
        """ Check invalid args """

        if self.location:
            if len(self.location) > 255 or len(self.location) < 1:
                self.module.fail_json(
                    msg='Error: The len of location %s is out of [1 - 255].' %
                    self.location)
        else:
            self.module.fail_json(msg='Error: The len of location is 0.')

    def get_proposed(self):
        """ Get proposed state """

        self.proposed["state"] = self.state

        if self.location:
            self.proposed["location"] = self.location

    def get_existing(self):
        """ Get existing state """

        tmp_cfg = self.cli_get_config()
        if tmp_cfg:
            temp_data = tmp_cfg.split(r"location ")
            self.cur_cfg["location"] = temp_data[1]
            self.existing["location"] = temp_data[1]

    def get_end_state(self):
        """ Get end state """

        tmp_cfg = self.cli_get_config()
        if tmp_cfg:
            temp_data = tmp_cfg.split(r"location ")
            self.end_state["location"] = temp_data[1]

    def cli_load_config(self, commands):
        """ Load config by cli """

        if not self.module.check_mode:
            try:
                self.module.config.load_config(commands)
            except NetworkError:
                err = get_cli_exception()
                self.module.fail_json(msg=err)

    def cli_get_config(self):
        """ Get config by cli """

        regular = "| include snmp | include location"
        tmp_cfg = self.module.config.get_config(include_all=True,
                                                regular=regular)

        return tmp_cfg

    def set_config(self):
        """ Set configure by cli """

        cmd = "snmp-agent sys-info location %s" % self.location
        self.updates_cmd.append(cmd)

        self.cli_load_config(cmd)
        self.changed = True

    def undo_config(self):
        """ Undo configure by cli """

        cmd = "undo snmp-agent sys-info location"
        self.updates_cmd.append(cmd)

        self.cli_load_config(cmd)
        self.changed = True

    def work(self):
        """ Main work function """

        self.check_args()
        self.get_proposed()
        self.get_existing()

        if self.state == "present":
            if "location" in self.cur_cfg.keys(
            ) and self.location == self.cur_cfg["location"]:
                pass
            else:
                self.set_config()
        else:
            if "location" in self.cur_cfg.keys(
            ) and self.location == self.cur_cfg["location"]:
                self.undo_config()

        self.get_end_state()

        self.results['changed'] = self.changed
        self.results['proposed'] = self.proposed
        self.results['existing'] = self.existing
        self.results['end_state'] = self.end_state
        self.results['updates'] = self.updates_cmd

        self.module.exit_json(**self.results)