예제 #1
0
    def init_module(self):
        """
        init ansilbe NetworkModule.
        """

        self.module = NetworkModule(
            argument_spec=self.spec, supports_check_mode=True)
예제 #2
0
    def __init__(self, **kwargs):
        """ Class init """

        # argument spec
        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()
        self.cur_cfg["acl interface"] = []

        # module args
        self.state = self.module.params['state']
        self.acl_name = self.module.params['acl_name']
        self.interface = self.module.params['interface']
        self.direction = self.module.params['direction']

        # state
        self.changed = False
        self.updates_cmd = list()
        self.results = dict()
        self.proposed = dict()
        self.existing = dict()
        self.end_state = dict()
예제 #3
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)
예제 #4
0
    def init_module(self):
        """ init_module"""
        self.mutually_exclusive = [('server', 'peer')]

        self.module = NetworkModule(argument_spec=self.spec,
                                    supports_check_mode=True,
                                    mutually_exclusive=self.mutually_exclusive)
예제 #5
0
def main():
    spec = dict(
        # { command: <str>, prompt: <str>, response: <str> }
        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='dellos9_command does not support running '
                    'config mode commands.  Please use '
                    'dellos9_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['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)
예제 #6
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)
예제 #7
0
    def __init__(self, **kwargs):
        """ Netstream template module 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)

        # netstream config
        self.netstream_cfg = None

        # module args
        self.state = self.module.params['state'] or None
        self.type = self.module.params['type'] or None
        self.record_name = self.module.params['record_name'] or None
        self.match = self.module.params['match'] or None
        self.collect_counter = self.module.params['collect_counter'] or None
        self.collect_interface = self.module.params['collect_interface'] or None
        self.description = self.module.params['description'] or None

        # state
        self.changed = False
        self.updates_cmd = list()
        self.results = dict()
        self.proposed = dict()
        self.existing = dict()
        self.end_state = dict()
예제 #8
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)
예제 #9
0
def main():
    """ main entry point for module execution
    """

    argument_spec = dict(
        src=dict(type='path'),

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

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

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

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

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

    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.disconnect()
        module.fail_json(msg=str(exc))

    module.disconnect()
    module.exit_json(**result)
예제 #10
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)
예제 #11
0
    def __init__(self, **kwargs):
        """ Class init """

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

        # module args
        self.state = self.module.params['state']
        self.host = self.module.params['host']
        self.port = self.module.params['port']
        self.username = self.module.params['username']
        self.password = self.module.params['password']
        self.acl_name = self.module.params['acl_name'] or None
        self.acl_num = self.module.params['acl_num'] or None
        self.acl_type = None
        self.acl_step = self.module.params['acl_step'] or None
        self.acl_description = self.module.params['acl_description'] or None
        self.rule_name = self.module.params['rule_name'] or None
        self.rule_id = self.module.params['rule_id'] or None
        self.rule_action = self.module.params['rule_action'] or None
        self.source_ip = self.module.params['source_ip'] or None
        self.src_mask = self.module.params['src_mask'] or None
        self.src_wild = None
        self.frag_type = self.module.params['frag_type'] or None
        self.vrf_name = self.module.params['vrf_name'] or None
        self.time_range = self.module.params['time_range'] or None
        self.rule_description = self.module.params['rule_description'] or None
        self.log_flag = self.module.params['log_flag'] or None

        # cur config
        self.cur_acl_cfg = dict()
        self.cur_base_rule_cfg = dict()

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

        # netconf
        if not HAS_NCCLIENT:
            raise Exception("Error: The ncclient library is required.")

        self.netconf = get_netconf(host=self.host,
                                   port=self.port,
                                   username=self.username,
                                   password=self.password)
        if not self.netconf:
            self.module.fail_json(msg='Error: netconf init failed.')
예제 #12
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)
예제 #13
0
    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)

        # module args
        self.state = self.module.params['state']
        self.host = self.module.params['host']
        self.port = self.module.params['port']
        self.username = self.module.params['username']
        self.password = self.module.params['password']
        self.version = self.module.params['version']
        self.connect_port = self.module.params['connect_port']
        self.host_name = self.module.params['host_name']
        self.domain = "snmpUDPDomain"
        self.address = self.module.params['address']
        self.notify_type = self.module.params['notify_type']
        self.vpn_name = self.module.params['vpn_name']
        self.recv_port = self.module.params['recv_port']
        self.security_model = self.module.params['security_model']
        self.security_name = self.module.params['security_name']
        self.security_name_v3 = self.module.params['security_name_v3']
        self.security_level = self.module.params['security_level']
        self.is_public_net = self.module.params['is_public_net']
        self.interface_name = self.module.params['interface_name']

        # config
        self.cur_cli_cfg = dict()
        self.cur_netconf_cfg = dict()
        self.end_netconf_cfg = dict()

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

        # 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')
예제 #14
0
def main():
    spec = dict(
        host=dict(required=False),
        vlan_id=dict(required=True, type='str'),
        name=dict(required=False),
        state=dict(choices=['present', 'absent'], default='present', required=False)
    )

    module = NetworkModule(argument_spec=spec)

    module.exit_json({changed: False, "huvs": "nivs"})
예제 #15
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)
예제 #16
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)
예제 #17
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)
    def __init__(self, **kwargs):
        """ Init function """

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

        # module args
        self.state = self.module.params['state']
        self.host = self.module.params['host']
        self.port = self.module.params['port']
        self.username = self.module.params['username']
        self.password = self.module.params['password']
        self.trap_time_stamp = self.module.params['trap_time_stamp'] or None
        self.trap_buff_enable = self.module.params['trap_buff_enable'] or None
        self.trap_buff_size = self.module.params['trap_buff_size'] or None
        self.module_name = self.module.params['module_name'] or None
        self.channel_id = self.module.params['channel_id'] or None
        self.trap_enable = self.module.params['trap_enable'] or None
        self.trap_level = self.module.params['trap_level'] or None

        # cur config
        self.cur_global_cfg = dict()
        self.cur_source_cfg = dict()

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

        # netconf
        if not HAS_NCCLIENT:
            raise Exception("Error: The ncclient library is required")

        self.netconf = get_netconf(host=self.host,
                                   port=self.port,
                                   username=self.username,
                                   password=self.password)
        if not self.netconf:
            self.module.fail_json(msg='Error: netconf init failed')
예제 #19
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 as e:
        module.fail_json(msg=to_native(e),
                         exception=traceback.format_exc(),
                         **e.kwargs)

    module.exit_json(**result)
예제 #20
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)
예제 #21
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 = NetworkConfig(contents=module.params['src'], indent=1)

    contents = get_config(module)

    if contents:
        config = NetworkConfig(contents=contents[0], indent=1)
        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)
예제 #22
0
    def __init__(self, **kwargs):
        """ Stp module 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()
        self.stp_cfg = None
        self.interface_stp_cfg = None

        # module args
        self.state = self.module.params['state'] or None
        self.stp_mode = self.module.params['stp_mode'] or None
        self.stp_enable = self.module.params['stp_enable'] or None
        self.stp_converge = self.module.params['stp_converge'] or None
        self.interface = self.module.params['interface'] or None
        self.edged_port = self.module.params['edged_port'] or None
        self.bpdu_filter = self.module.params['bpdu_filter'] or None
        self.cost = self.module.params['cost'] or None
        self.bpdu_protection = self.module.params['bpdu_protection'] or None
        self.tc_protection = self.module.params['tc_protection'] or None
        self.tc_protection_interval = self.module.params[
            'tc_protection_interval'] or None
        self.tc_protection_threshold = self.module.params[
            'tc_protection_threshold'] or None
        self.root_protection = self.module.params['root_protection'] or None
        self.loop_protection = self.module.params['loop_protection'] or None

        # state
        self.changed = False
        self.updates_cmd = list()
        self.results = dict()
        self.proposed = dict()
        self.existing = dict()
        self.end_state = dict()
예제 #23
0
    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()
        self.cur_cfg["snmp-agent trap"] = []
        self.cur_cfg["undo snmp-agent trap"] = []

        # module args
        self.state = self.module.params['state']
        self.feature_name = self.module.params['feature_name']
        self.trap_name = self.module.params['trap_name']
        self.interface_type = self.module.params['interface_type']
        self.interface_number = self.module.params['interface_number']
        self.port_number = self.module.params['port_number']

        # state
        self.changed = False
        self.updates_cmd = list()
        self.results = dict()
        self.proposed = dict()
        self.existing = dict()
        self.existing["snmp-agent trap"] = []
        self.existing["undo snmp-agent trap"] = []
        self.end_state = dict()
        self.end_state["snmp-agent trap"] = []
        self.end_state["undo snmp-agent trap"] = []

        commands = list()
        cmd1 = {'output': 'text', 'command': 'display interface brief'}
        commands.append(cmd1)
        self.interface = self.excute_command(commands)
    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()
예제 #25
0
def get_network_module(**kwargs):
    try:
        return get_module(**kwargs)
    except NameError:
        return NetworkModule(**kwargs)
예제 #26
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)
예제 #27
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)
예제 #28
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)
예제 #29
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)
예제 #30
0
    def __init_module__(self):
        """ init module """

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