Esempio n. 1
0
def test_play_ds_positive():
    """ Test _play_ds"""
    adhoc_cli = AdHocCLI(args=['/bin/ansible', 'localhost', '-m', 'command'])
    adhoc_cli.parse()
    ret = adhoc_cli._play_ds('command', 10, 2)
    assert ret['name'] == 'Ansible Ad-Hoc'
    assert ret['tasks'] == [{'action': {'module': 'command', 'args': {}}, 'async_val': 10, 'poll': 2, 'timeout': 0}]
Esempio n. 2
0
def test_play_ds_with_include_role():
    """ Test include_role command with poll"""
    adhoc_cli = AdHocCLI(args=['/bin/ansible', 'localhost', '-m', 'include_role'])
    adhoc_cli.parse()
    ret = adhoc_cli._play_ds('include_role', None, 2)
    assert ret['name'] == 'Ansible Ad-Hoc'
    assert ret['gather_facts'] == 'no'
Esempio n. 3
0
def test_no_argument():
    """ Test no argument command"""
    adhoc_cli = AdHocCLI(['/bin/ansible', '-m', 'command', 'localhost'])
    adhoc_cli.parse()
    with pytest.raises(AnsibleOptionsError) as exec_info:
        adhoc_cli.run()
    assert 'No argument passed to command module' == str(exec_info.value)
Esempio n. 4
0
def test_did_you_mean_playbook():
    """ Test adhoc with yml file as argument parameter"""
    adhoc_cli = AdHocCLI(['/bin/ansible', '-m', 'command', 'localhost.yml'])
    adhoc_cli.parse()
    with pytest.raises(AnsibleOptionsError) as exec_info:
        adhoc_cli.run()
    assert 'No argument passed to command module (did you mean to run ansible-playbook?)' == str(exec_info.value)
Esempio n. 5
0
def test_with_command():
    """ Test simple adhoc command"""
    module_name = 'command'
    adhoc_cli = AdHocCLI(args=['-m', module_name, '-vv'])
    adhoc_cli.parse()
    assert adhoc_cli.options.module_name == module_name
    assert display.verbosity == 2
Esempio n. 6
0
def test_with_command():
    """ Test simple adhoc command"""
    module_name = 'command'
    adhoc_cli = AdHocCLI(args=['ansible', '-m', module_name, '-vv', 'localhost'])
    adhoc_cli.parse()
    assert context.CLIARGS['module_name'] == module_name
    assert display.verbosity == 2
Esempio n. 7
0
def test_simple_command():
    """ Test valid command and its run"""
    adhoc_cli = AdHocCLI(
        ['/bin/ansible', '-m', 'command', 'localhost', '-a', 'echo "hi"'])
    adhoc_cli.parse()
    ret = adhoc_cli.run()
    assert ret == 0
Esempio n. 8
0
def test_simple_command():
    """ Test valid command and its run"""
    adhoc_cli = AdHocCLI(['/bin/ansible', '-m', 'command', 'localhost'])
    adhoc_cli.parse()
    adhoc_cli.options.module_args = "echo 'hi'"
    ret = adhoc_cli.run()
    assert ret == 0
Esempio n. 9
0
def test_parse():
    """ Test adhoc parse"""
    with pytest.raises(ValueError, match='A non-empty list for args is required'):
        adhoc_cli = AdHocCLI([])

    adhoc_cli = AdHocCLI(['ansibletest'])
    with pytest.raises(SystemExit):
        adhoc_cli.parse()
Esempio n. 10
0
def test_run_import_playbook():
    """ Test import_playbook which is not allowed with ad-hoc command"""
    import_playbook = 'import_playbook'
    adhoc_cli = AdHocCLI(args=['/bin/ansible', '-m', import_playbook, 'localhost'])
    adhoc_cli.parse()
    with pytest.raises(AnsibleOptionsError) as exec_info:
        adhoc_cli.run()
    assert context.CLIARGS['module_name'] == import_playbook
    assert "'%s' is not a valid action for ad-hoc commands" % import_playbook == str(exec_info.value)
Esempio n. 11
0
 def _set_inventory(self, inventory_path=None):
     """Use the Ansible framework to return an inventory object"""
     helper = AdHocCLI(['ansible', '--list-hosts', 'all'])
     if inventory_path:
         helper.args += ['-i', inventory_path]
     helper.parse()
     loader, inventory, vm = helper._play_prereqs(helper.options)
     self.inventory_file = inventory_path
     self.inventory = inventory
Esempio n. 12
0
 def test(self, target):
     os.chdir(self.wd)
     # need to chdir before importing!
     from ansible.cli.adhoc import AdHocCLI
     cli = AdHocCLI(
         [
             sys.argv[0],
             '-i', 'inventory',
             target,
             '-m', 'ping',
             '-o'
         ]
     )
     cli.parse()
     exit = cli.run()
     os.chdir(self.pwd)
     return exit == 0
Esempio n. 13
0
    def _run(self, *module_args, **complex_args):
        """Execute an ansible adhoc command returning the result in a AdhocResult object."""
        # Assemble module argument string
        if module_args:
            complex_args.update(dict(_raw_params=' '.join(module_args)))

        # Assert hosts matching the provided pattern exist
        hosts = self.options['inventory_manager'].list_hosts()
        no_hosts = False
        if len(hosts) == 0:
            no_hosts = True
            warnings.warn("provided hosts list is empty, only localhost is available")

        self.options['inventory_manager'].subset(self.options.get('subset'))
        hosts = self.options['inventory_manager'].list_hosts(self.options['host_pattern'])
        if len(hosts) == 0 and not no_hosts:
            raise ansible.errors.AnsibleError("Specified hosts and/or --limit does not match any hosts")

        # Log the module and parameters
        log.debug("[%s] %s: %s" % (self.options['host_pattern'], self.options['module_name'], complex_args))

        # Pass along cli options
        args = ['pytest-ansible', '-vvvvv', self.options['host_pattern']]
        for argument in ('connection', 'user', 'become', 'become_method', 'become_user', 'module_path'):
            arg_value = self.options.get(argument)
            argument = argument.replace('_', '-')

            if arg_value in (None, False):
                continue

            if arg_value is True:
                args.append('--{0}'.format(argument))
            else:
                args.append('--{0}={1}'.format(argument, arg_value))

        # Use Ansible's own adhoc cli to parse the fake command line we created and then save it
        # into Ansible's global context
        adhoc = AdHocCLI(args)
        adhoc.parse()

        # And now we'll never speak of this again
        del adhoc

        # Initialize callback to capture module JSON responses
        cb = ResultAccumulator()

        kwargs = dict(
            inventory=self.options['inventory_manager'],
            variable_manager=self.options['variable_manager'],
            loader=self.options['loader'],
            stdout_callback=cb,
            passwords=dict(conn_pass=None, become_pass=None),
        )

        # create a pseudo-play to execute the specified module via a single task
        play_ds = dict(
            name="pytest-ansible",
            hosts=self.options['host_pattern'],
            gather_facts='no',
            tasks=[
                dict(
                    action=dict(
                        module=self.options['module_name'], args=complex_args
                    ),
                ),
            ]
        )
        log.debug("Play(%s)", play_ds)
        play = Play().load(play_ds, variable_manager=self.options['variable_manager'], loader=self.options['loader'])

        # now create a task queue manager to execute the play
        tqm = None
        try:
            log.debug("TaskQueueManager(%s)", kwargs)
            tqm = TaskQueueManager(**kwargs)
            tqm.run(play)
        finally:
            if tqm:
                tqm.cleanup()

        # Log the results
        log.debug(cb.results)

        # Raise exception if host(s) unreachable
        # FIXME - if multiple hosts were involved, should an exception be raised?
        if cb.unreachable:
            raise AnsibleConnectionFailure("Host unreachable", dark=cb.unreachable, contacted=cb.contacted)

        # Success!
        return AdHocResult(contacted=cb.contacted)
Esempio n. 14
0
def test_parse():
    """ Test adhoc parse"""
    adhoc_cli = AdHocCLI([])
    with pytest.raises(SystemExit) as exec_info:
        adhoc_cli.parse()
Esempio n. 15
0
def test_with_extra_parameters():
    """ Test extra parameters"""
    adhoc_cli = AdHocCLI(args=['-m', 'command', 'extra_parameters'])
    with pytest.raises(AnsibleOptionsError) as exec_info:
        adhoc_cli.parse()
    assert "Extraneous options or arguments" == str(exec_info.value)
Esempio n. 16
0
def test_run_no_extra_vars():
    adhoc_cli = AdHocCLI(args=['/bin/ansible', 'localhost', '-e'])
    with pytest.raises(SystemExit) as exec_info:
        adhoc_cli.parse()
    assert exec_info.value.code == 2
Esempio n. 17
0
    def _run(self, *module_args, **complex_args):
        """Execute an ansible adhoc command returning the result in a AdhocResult object."""
        # Assemble module argument string
        if module_args:
            complex_args.update(dict(_raw_params=' '.join(module_args)))

        # Assert hosts matching the provided pattern exist
        hosts = self.options['inventory_manager'].list_hosts()
        no_hosts = False
        if len(hosts) == 0:
            no_hosts = True
            warnings.warn(
                "provided hosts list is empty, only localhost is available")

        self.options['inventory_manager'].subset(self.options.get('subset'))
        hosts = self.options['inventory_manager'].list_hosts(
            self.options['host_pattern'])
        if len(hosts) == 0 and not no_hosts:
            raise ansible.errors.AnsibleError(
                "Specified hosts and/or --limit does not match any hosts")

        # Log the module and parameters
        log.debug("[%s] %s: %s" % (self.options['host_pattern'],
                                   self.options['module_name'], complex_args))

        # Pass along cli options
        args = ['pytest-ansible', '-vvvvv', self.options['host_pattern']]
        for argument in ('connection', 'user', 'become', 'become_method',
                         'become_user', 'module_path'):
            arg_value = self.options.get(argument)
            argument = argument.replace('_', '-')

            if arg_value in (None, False):
                continue

            if arg_value is True:
                args.append('--{0}'.format(argument))
            else:
                args.append('--{0}={1}'.format(argument, arg_value))

        # Use Ansible's own adhoc cli to parse the fake command line we created and then save it
        # into Ansible's global context
        adhoc = AdHocCLI(args)
        adhoc.parse()

        # And now we'll never speak of this again
        del adhoc

        # Initialize callback to capture module JSON responses
        cb = ResultAccumulator()

        kwargs = dict(
            inventory=self.options['inventory_manager'],
            variable_manager=self.options['variable_manager'],
            loader=self.options['loader'],
            stdout_callback=cb,
            passwords=dict(conn_pass=None, become_pass=None),
        )

        # create a pseudo-play to execute the specified module via a single task
        play_ds = dict(name="pytest-ansible",
                       hosts=self.options['host_pattern'],
                       become=self.options['become'],
                       become_user=self.options['become_user'],
                       gather_facts='no',
                       tasks=[
                           dict(action=dict(module=self.options['module_name'],
                                            args=complex_args), ),
                       ])
        log.debug("Play(%s)", play_ds)
        play = Play().load(play_ds,
                           variable_manager=self.options['variable_manager'],
                           loader=self.options['loader'])

        # now create a task queue manager to execute the play
        tqm = None
        try:
            log.debug("TaskQueueManager(%s)", kwargs)
            tqm = TaskQueueManager(**kwargs)
            tqm.run(play)
        finally:
            if tqm:
                tqm.cleanup()

        # Log the results
        log.debug(cb.results)

        # Raise exception if host(s) unreachable
        # FIXME - if multiple hosts were involved, should an exception be raised?
        if cb.unreachable:
            raise AnsibleConnectionFailure("Host unreachable",
                                           dark=cb.unreachable,
                                           contacted=cb.contacted)

        # Success!
        return AdHocResult(contacted=cb.contacted)
Esempio n. 18
0
def test_parse():
    """ Test adhoc parse"""
    adhoc_cli = AdHocCLI([])
    with pytest.raises(AnsibleOptionsError) as exec_info:
        adhoc_cli.parse()
    assert "Missing target hosts" == str(exec_info.value)