Example #1
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)
Example #2
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)
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.iteritems():
        key = 'ansible_net_%s' % key
        ansible_facts[key] = value

    module.exit_json(ansible_facts=ansible_facts)
Example #4
0
    def excute_command(self, commands):
        """ excute_command"""

        output = ''
        runner = CommandRunner(self.module)
        for cmd in commands:
            try:
                runner.add_command(**cmd)
            except AddCommandError:
                self.module.fail_json(msg='duplicate command detected: %s' %
                                      cmd)

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

        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 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
Example #6
0
    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=get_cli_exception(exc))

        try:
            runner.run()
        except NetworkError:
            err = get_cli_exception()
            self.module.fail_json(msg=err)
    def excute_command(self, commands):
        """ Method to execute command """

        runner = CommandRunner(self.module)
        for cmd in commands:
            try:
                runner.add_command(**cmd)
            except AddCommandError:
                exc = get_exception()
                self.module.fail_json(msg=str(exc))

        try:
            runner.run()
        except NetworkError:
            err = get_cli_exception()
            self.module.fail_json(msg=err)

        output = []
        for cmd in commands:
            tmp = runner.get_command(cmd['command'], cmd.get('output'))
            output.append(tmp)
        return output
Example #8
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)
Example #9
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)
Example #10
0
def main():
    """ Module 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)

    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=get_cli_exception(exc), **exc.kwargs)

    try:
        for inst in instances:
            inst.populate()
            facts.update(inst.facts)
    except Exception:
        raise

    ansible_facts = dict()
    for key, value in iteritems(facts):
        if key.startswith('_'):
            ansible_facts[key[1:]] = value
        else:
            ansible_facts[key] = value

    module.exit_json(ansible_facts=ansible_facts)
Example #11
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)
Example #12
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)
def main():
    """ main """

    spec = dict(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)

    for cmd in commands:
        if module.check_mode and not cmd['command'].startswith('dis'):
            warnings.append('only display commands are supported when using '
                            'check mode, not executing `%s`' % cmd['command'])
        else:
            if cmd['command'].startswith('sys'):
                module.fail_json(
                    msg='Error: ce_command does not support running '
                    'config mode commands.  Please use '
                    'ce_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=get_cli_exception(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=get_cli_exception(exc),
                         failed_conditions=exc.failed_conditions)
    except FailedConditionalError:
        exc = get_exception()
        module.fail_json(msg=get_cli_exception(exc),
                         failed_conditional=exc.failed_conditional)
    except NetworkError:
        err = get_cli_exception()
        module.fail_json(msg=err)

    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)
Example #14
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:
        exc = get_exception()
        module.fail_json(msg='unknown failure', output=runner.items, exc=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)
Example #15
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)
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)
Example #17
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)
Example #18
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)
Example #19
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)