Exemplo 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
    }]
Exemplo n.º 2
0
 def _extract_from_cli(self):
     # pylint: disable=protected-access,
     result = {}
     clis = {
         "module": AdHocCLI(args=["", "all"]),
         "playbook": PlaybookCLI(args=["", "none.yml"])
     }
     for cli_name in clis:
         cli = clis[cli_name]
         cli.parse()
         cli_result = {}
         for option in cli.parser._get_all_options():
             for name in option._long_opts:
                 name = name[2:]
                 if name in self._EXCLUDE_ARGS:
                     continue
                 shortopts = []
                 for opt in option._short_opts:
                     shortopts.append(opt[1:])
                 cli_result[name] = {
                     "type": option.type,
                     "help": option.help,
                     "shortopts": shortopts
                 }
         result[cli_name] = cli_result
     result['module']['group'] = {"type": "string", "help": ""}
     result['periodic_playbook'] = result['playbook']
     result['periodic_module'] = result['module']
     return result
Exemplo n.º 3
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
Exemplo n.º 4
0
    def clis(self):
        '''
        Ansible cli objects

        :return: dict with cli objects
        '''
        return {
            "module": AdHocCLI(args=["", "all"]),
            "playbook": PlaybookCLI(args=["", "none.yml"])
        }
Exemplo n.º 5
0
def test_ansible_version(capsys, mocker):
    adhoc_cli = AdHocCLI(args=['/bin/ansible', '--version'])
    with pytest.raises(SystemExit):
        adhoc_cli.run()
    version = capsys.readouterr()
    try:
        version_lines = version.out.splitlines()
    except AttributeError:
        # Python 2.6 does return a named tuple, so get the first item
        version_lines = version[0].splitlines()

    assert len(version_lines) == 7, 'Incorrect number of lines in "ansible --version" output'
    assert re.match('ansible [0-9.a-z]+$', version_lines[0]), 'Incorrect ansible version line in "ansible --version" output'
    assert re.match('  config file = .*$', version_lines[1]), 'Incorrect config file line in "ansible --version" output'
    assert re.match('  configured module search path = .*$', version_lines[2]), 'Incorrect module search path in "ansible --version" output'
    assert re.match('  ansible python module location = .*$', version_lines[3]), 'Incorrect python module location in "ansible --version" output'
    assert re.match('  ansible collection location = .*$', version_lines[4]), 'Incorrect collection location in "ansible --version" output'
    assert re.match('  executable location = .*$', version_lines[5]), 'Incorrect executable locaction in "ansible --version" output'
    assert re.match('  python version = .*$', version_lines[6]), 'Incorrect python version in "ansible --version" output'
Exemplo n.º 6
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)
Exemplo n.º 7
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)
Exemplo n.º 8
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()
Exemplo n.º 9
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)
Exemplo n.º 10
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)
Exemplo n.º 11
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
Exemplo n.º 12
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
Exemplo 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)
Exemplo n.º 14
0
def test_parse():
    """ Test adhoc parse"""
    adhoc_cli = AdHocCLI([])
    with pytest.raises(SystemExit) as exec_info:
        adhoc_cli.parse()
Exemplo 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)
Exemplo n.º 16
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)