Пример #1
0
 def playbookrun(self, playbook_path):
     context._init_global_context(self.ops)
     playbook = PlaybookExecutor(playbook=playbook_path,
                                 inventory=self.inventory,
                                 variable_manager=self.variable_manager,
                                 loader=self.loader,
                                 passwords=self.passwords)
     result = playbook.run()
     return result
Пример #2
0
def test_set_global_context():
    options = FakeOptions()
    options.tags = [u'production', u'webservers']
    options.check_mode = True
    options.start_at_task = u'Start with くらとみ'

    expected = frozenset(
        (('tags', (u'production', u'webservers')), ('check_mode', True),
         ('start_at_task', u'Start with くらとみ')))

    context._init_global_context(options)
    assert frozenset(context.CLIARGS.items()) == expected
Пример #3
0
    def playbookrun(self, playbook_path):

        # self.variable_manager.extra_vars = {'customer': 'test', 'disabled': 'yes'}
        context._init_global_context(self.ops)

        playbook = PlaybookExecutor(playbooks=playbook_path,
                                    inventory=self.inventory,
                                    variable_manager=self.variable_manager,
                                    loader=self.loader,
                                    passwords=self.passwords)
        result = playbook.run()
        return result
Пример #4
0
def test_play_context(mocker, parser, reset_cli_args):
    (options, args) = parser.parse_args(['-vv', '--check'])
    options.args = args
    context._init_global_context(options)
    play = Play.load({})
    play_context = PlayContext(play=play)

    assert play_context.remote_addr is None
    assert play_context.remote_user is None
    assert play_context.password == ''
    assert play_context.private_key_file == C.DEFAULT_PRIVATE_KEY_FILE
    assert play_context.timeout == C.DEFAULT_TIMEOUT
    assert play_context.verbosity == 2
    assert play_context.check_mode is True

    mock_play = mocker.MagicMock()
    mock_play.force_handlers = True

    play_context = PlayContext(play=mock_play)
    assert play_context.force_handlers is True

    mock_task = mocker.MagicMock()
    mock_task.connection = 'mocktask'
    mock_task.remote_user = '******'
    mock_task.port = 1234
    mock_task.no_log = True
    mock_task.become = True
    mock_task.become_method = 'mocktask'
    mock_task.become_user = '******'
    mock_task.become_pass = '******'
    mock_task._local_action = False
    mock_task.delegate_to = None

    all_vars = dict(
        ansible_connection='mock_inventory',
        ansible_ssh_port=4321,
    )

    mock_templar = mocker.MagicMock()

    play_context = PlayContext()
    play_context = play_context.set_task_and_variable_override(
        task=mock_task, variables=all_vars, templar=mock_templar)

    assert play_context.connection == 'mock_inventory'
    assert play_context.remote_user == 'mocktask'
    assert play_context.no_log is True

    mock_task.no_log = False
    play_context = play_context.set_task_and_variable_override(
        task=mock_task, variables=all_vars, templar=mock_templar)
    assert play_context.no_log is False
Пример #5
0
    def parse(self):
        """Parse the command line args

        This method parses the command line arguments.  It uses the parser
        stored in the self.parser attribute and saves the args and options in
        context.CLIARGS.

        Subclasses need to implement two helper methods, init_parser() and post_process_args() which
        are called from this function before and after parsing the arguments.
        """
        self.init_parser()
        options, args = self.parser.parse_args(self.args[1:])
        options, args = self.post_process_args(options, args)
        options.args = args
        context._init_global_context(options)
def test_play_context_make_become_bad(mocker, parser, reset_cli_args):
    options = parser.parse_args([])
    context._init_global_context(options)
    play_context = PlayContext()

    default_cmd = "/bin/foo"
    default_exe = "/bin/bash"

    play_context.become = True
    play_context.become_user = '******'
    play_context.set_become_plugin(become_loader.get('bad'))
    play_context.become_method = 'bad'

    with pytest.raises(AnsibleError):
        play_context.make_become_cmd(cmd=default_cmd, executable=default_exe)
Пример #7
0
 def __init__(self):
     self.options = {
         'verbosity': 0,
         'ask_pass': False,
         'private_key_file': None,
         'remote_user': None,
         'connection': 'smart',
         'timeout': 10,
         'ssh_common_args': '',
         'sftp_extra_args': '',
         'scp_extra_args': '',
         'ssh_extra_args': '',
         'force_handlers': False,
         'flush_cache': None,
         'become': False,
         'become_method': 'sudo',
         'become_user': None,
         'become_ask_pass': False,
         'tags': ['all'],
         'skip_tags': [],
         'check': False,
         'syntax': None,
         'diff': False,
         'inventory': './test_hosts',
         'listhosts': None,
         'subset': None,
         'extra_vars': [],
         'ask_vault_pass': False,
         'vault_password_files': [],
         'vault_ids': [],
         'forks': 5,
         'module_path': None,
         'listtasks': None,
         'listtags': None,
         'step': None,
         'start_at_task': None,
         'args': ['fake']
     }
     self.ops = Values(self.options)
     self.loader = DataLoader()
     self.passwords = dict()
     self.results_callback = ResultCallback()
     self.inventory = InventoryManager(loader=self.loader,
                                       sources=[self.options['inventory']])
     self.variable_manager = VariableManager(loader=self.loader,
                                             inventory=self.inventory)
     context._init_global_context(self.ops)
Пример #8
0
def ansible_runner_28x(playbook_path,
                       extra_vars,
                       options,
                       inventory_src='localhost',
                       console=True):

    loader = DataLoader()
    variable_manager = VariableManager(loader=loader)
    variable_manager._extra_vars = extra_vars
    inventory = Inventory(loader=loader, sources=[inventory_src])
    variable_manager.set_inventory(inventory)
    passwords = {}
    context._init_global_context(options)

    pbex = PlaybookExecutor([playbook_path], inventory, variable_manager,
                            loader, passwords)
    return pbex
Пример #9
0
def test_su(mocker, parser, reset_cli_args):
    options = parser.parse_args([])
    context._init_global_context(options)

    su = become_loader.get('su')
    sh = shell_loader.get('sh')
    sh.executable = "/bin/bash"

    su.set_options(direct={
        'become_user': '******',
        'become_flags': '',
    })

    cmd = su.build_become_command('/bin/foo', sh)
    assert re.match(
        r"""su\s+foo -c '/bin/bash -c '"'"'echo BECOME-SUCCESS-.+?; /bin/foo'"'"''""",
        cmd)
Пример #10
0
def test_sudosu(mocker, parser, reset_cli_args):
    options = parser.parse_args([])
    context._init_global_context(options)

    default_cmd = "/bin/foo"
    default_exe = "/bin/bash"
    sudo_exe = 'sudo'
    sudo_flags = '-H -s -n'

    success = 'BECOME-SUCCESS-.+?'

    task = {
        'become_user': '******',
        'become_method': 'community.general.sudosu',
        'become_flags': sudo_flags,
    }
    var_options = {}
    cmd = call_become_plugin(task,
                             var_options,
                             cmd=default_cmd,
                             executable=default_exe)
    print(cmd)
    assert (re.match(
        """%s %s  su -l %s %s -c 'echo %s; %s'""" %
        (sudo_exe, sudo_flags, task['become_user'], default_exe, success,
         default_cmd), cmd) is not None)

    task = {
        'become_user': '******',
        'become_method': 'community.general.sudosu',
        'become_flags': sudo_flags,
        'become_pass': '******',
    }
    var_options = {}
    cmd = call_become_plugin(task,
                             var_options,
                             cmd=default_cmd,
                             executable=default_exe)
    print(cmd)
    assert (re.match(
        """%s %s -p "%s" su -l %s %s -c 'echo %s; %s'""" %
        (sudo_exe, sudo_flags.replace(
            '-n', ''), r"\[sudo via ansible, key=.+?\] password:",
         task['become_user'], default_exe, success, default_cmd), cmd)
            is not None)
Пример #11
0
    def ansible_run(self, host_list, task_list):
        context._init_global_context(self.ops)
        play_source = dict(name="Ansible Play",
                           hosts=host_list,
                           gather_facts='no',
                           tasks=task_list)
        play = Play().load(play_source,
                           variable_manager=self.variable_manager,
                           loader=self.loader)

        tqm = None
        try:
            tqm = TaskQueueManager(
                inventory=self.inventory,
                variable_manager=self.variable_manager,
                loader=self.loader,
                # options=self.ops,
                passwords=self.passwords,
                stdout_callback=self.results_callback,
                run_additional_callbacks=C.DEFAULT_LOAD_CALLBACK_PLUGINS,
                run_tree=False,
            )
            result = tqm.run(play)
        finally:
            if tqm is not None:
                tqm.cleanup()
                # shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)

        results_raw = {}
        results_raw['success'] = {}
        results_raw['failed'] = {}
        results_raw['unreachable'] = {}

        for host, result in self.results_callback.host_ok.items():
            results_raw['success'][host] = json.dumps(result._result)

        for host, result in self.results_callback.host_failed.items():
            results_raw['failed'][host] = result._result['msg']

        for host, result in self.results_callback.host_unreachable.items():
            results_raw['unreachable'][host] = result._result['msg']

        return results_raw
Пример #12
0
def test_ksu(mocker, parser, reset_cli_args):
    options = parser.parse_args([])
    context._init_global_context(options)

    default_cmd = "/bin/foo"
    default_exe = "/bin/bash"
    ksu_exe = 'ksu'
    ksu_flags = ''

    success = 'BECOME-SUCCESS-.+?'

    task = {
        'become_user': '******',
        'become_method': 'community.general.ksu',
        'become_flags': ksu_flags,
    }
    var_options = {}
    cmd = call_become_plugin(task, var_options, cmd=default_cmd, executable=default_exe)
    print(cmd)
    assert (re.match("""%s %s %s -e %s -c 'echo %s; %s'""" % (ksu_exe, task['become_user'], ksu_flags,
                                                              default_exe, success, default_cmd), cmd) is not None)
Пример #13
0
def test_dzdo_varoptions(mocker, parser, reset_cli_args):
    options = parser.parse_args([])
    context._init_global_context(options)

    default_cmd = "/bin/foo"
    default_exe = "/bin/bash"
    dzdo_exe = 'dzdo'
    dzdo_flags = ''

    success = 'BECOME-SUCCESS-.+?'

    task = {
        'become_user': '******',
        'become_method': 'community.general.dzdo',
        'become_flags': 'xxx',
    }
    var_options = {
        'ansible_become_user': '******',
        'ansible_become_flags': dzdo_flags,
    }
    cmd = call_become_plugin(task,
                             var_options,
                             cmd=default_cmd,
                             executable=default_exe)
    print(cmd)
    assert re.match(
        """%s %s -u %s %s -c 'echo %s; %s'""" %
        (dzdo_exe, dzdo_flags, var_options['ansible_become_user'], default_exe,
         success, default_cmd), cmd) is not None
    var_options['ansible_become_pass'] = '******'
    cmd = call_become_plugin(task,
                             var_options,
                             cmd=default_cmd,
                             executable=default_exe)
    print(cmd)
    assert re.match(
        """%s %s -p %s -u %s %s -c 'echo %s; %s'""" %
        (dzdo_exe, dzdo_flags, r'\"\[dzdo via ansible, key=.+?\] password:\"',
         var_options['ansible_become_user'], default_exe, success,
         default_cmd), cmd) is not None
Пример #14
0
    def playbook_run(self, playbook_path):

        # self.variable_manager.extra_vars = {'customer': 'test', 'disabled': 'yes'}
        context._init_global_context(self.ops)

        playbook = PlaybookExecutor(playbooks=playbook_path,
                                    inventory=self.inventory,
                                    variable_manager=self.variable_manager,
                                    loader=self.loader,
                                    passwords=self.passwords)

        playbook._tqm._stdout_callback = self.result_playbook
        C.HOST_KEY_CHECKING = False
        playbook.run()
        self.results_raw = {
            'skipped': {},
            'failed': {},
            'ok': {},
            "status": {},
            'unreachable': {},
            "changed": {}
        }
        for host, result in self.result_playbook.task_ok.items():
            self.results_raw['ok'][host] = json.dumps(result._result)

        for host, result in self.result_playbook.task_failed.items():
            self.results_raw['failed'][host] = result._result['msg']

        for host, result in self.result_playbook.task_status.items():
            self.results_raw['status'][host] = result

        for host, result in self.result_playbook.task_skipped.items():
            self.results_raw['skipped'][host] = result._result['msg']

        for host, result in self.result_playbook.task_unreachable.items():
            self.results_raw['unreachable'][host] = result._result['msg']

        return self.results_raw
Пример #15
0
def test_pbrun_basic(mocker, parser, reset_cli_args):
    options = parser.parse_args([])
    context._init_global_context(options)

    default_cmd = "/bin/foo"
    default_exe = "/bin/bash"
    pbrun_exe = 'pbrun'
    pbrun_flags = ''

    success = 'BECOME-SUCCESS-.+?'

    task = {
        'become_method': 'community.general.pbrun',
    }
    var_options = {}
    cmd = call_become_plugin(task,
                             var_options,
                             cmd=default_cmd,
                             executable=default_exe)
    print(cmd)
    assert re.match(
        """%s %s  'echo %s; %s'""" %
        (pbrun_exe, pbrun_flags, success, default_cmd), cmd) is not None
Пример #16
0
def test_doas(mocker, parser, reset_cli_args):
    options = parser.parse_args([])
    context._init_global_context(options)
    play_context = PlayContext()

    default_cmd = "/bin/foo"
    default_exe = "/bin/bash"
    doas_exe = 'doas'
    doas_flags = '-n'

    cmd = play_context.make_become_cmd(cmd=default_cmd, executable=default_exe)
    assert cmd == default_cmd

    success = 'BECOME-SUCCESS-.+?'

    play_context.become = True
    play_context.become_user = '******'
    play_context.set_become_plugin(become_loader.get('doas'))
    play_context.become_method = 'doas'
    play_context.become_flags = doas_flags
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable=default_exe)
    assert (re.match("""%s %s -u %s %s -c 'echo %s; %s'""" % (doas_exe, doas_flags, play_context.become_user, default_exe, success,
                                                              default_cmd), cmd) is not None)
Пример #17
0
    def parse(self):
        """Parse the command line args

        This method parses the command line arguments.  It uses the parser
        stored in the self.parser attribute and saves the args and options in
        context.CLIARGS.

        Subclasses need to implement two helper methods, init_parser() and post_process_args() which
        are called from this function before and after parsing the arguments.
        """
        self.init_parser()

        if HAS_ARGCOMPLETE:
            argcomplete.autocomplete(self.parser)

        try:
            options = self.parser.parse_args(self.args[1:])
        except SystemExit as e:
            if(e.code != 0):
                self.parser.exit(status=2, message=" \n%s" % self.parser.format_help())
            raise
        options = self.post_process_args(options)
        context._init_global_context(options)
Пример #18
0
def test_pfexec(mocker, parser, reset_cli_args):
    options = parser.parse_args([])
    context._init_global_context(options)
    play_context = PlayContext()

    default_cmd = "/bin/foo"
    default_exe = "/bin/bash"
    pfexec_exe = 'pfexec'
    pfexec_flags = ''

    cmd = play_context.make_become_cmd(cmd=default_cmd, executable=default_exe)
    assert cmd == default_cmd

    success = 'BECOME-SUCCESS-.+?'

    play_context.become = True
    play_context.become_user = '******'
    play_context.set_become_plugin(become_loader.get('pfexec'))
    play_context.become_method = 'pfexec'
    play_context.become_flags = pfexec_flags
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable=default_exe)
    assert re.match(
        '''%s %s "'echo %s; %s'"''' %
        (pfexec_exe, pfexec_flags, success, default_cmd), cmd) is not None
Пример #19
0
def test_play_context_make_become_cmd(mocker, parser, reset_cli_args):
    (options, args) = parser.parse_args([])
    options.args = args
    context._init_global_context(options)
    play_context = PlayContext()

    default_cmd = "/bin/foo"
    default_exe = "/bin/bash"
    sudo_exe = 'sudo'
    sudo_flags = '-H -s -n'
    su_exe = 'su'
    su_flags = ''
    pbrun_exe = 'pbrun'
    pbrun_flags = ''
    pfexec_exe = 'pfexec'
    pfexec_flags = ''
    doas_exe = 'doas'
    doas_flags = '-n'
    ksu_exe = 'ksu'
    ksu_flags = ''
    dzdo_exe = 'dzdo'
    dzdo_flags = ''

    cmd = play_context.make_become_cmd(cmd=default_cmd, executable=default_exe)
    assert cmd == default_cmd

    success = 'BECOME-SUCCESS-.+?'

    play_context.become = True
    play_context.become_user = '******'
    play_context.set_become_plugin(become_loader.get('sudo'))
    play_context.become_flags = sudo_flags
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable="/bin/bash")

    assert (re.match("""%s %s  -u %s %s -c 'echo %s; %s'""" % (sudo_exe, sudo_flags, play_context.become_user,
                                                               default_exe, success, default_cmd), cmd) is not None)

    play_context.become_pass = '******'
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable=default_exe)
    assert (re.match("""%s %s -p "%s" -u %s %s -c 'echo %s; %s'""" % (sudo_exe, sudo_flags.replace('-n', ''),
                                                                      r"\[sudo via ansible, key=.+?\] password:"******"/bin/bash")
    assert (re.match("""%s  %s -c '%s -c '"'"'echo %s; %s'"'"''""" % (su_exe, play_context.become_user, default_exe,
                                                                      success, default_cmd), cmd) is not None)

    play_context.set_become_plugin(become_loader.get('pbrun'))
    play_context.become_flags = pbrun_flags
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable="/bin/bash")
    assert re.match("""%s %s -u %s 'echo %s; %s'""" % (pbrun_exe, pbrun_flags, play_context.become_user,
                                                       success, default_cmd), cmd) is not None

    play_context.set_become_plugin(become_loader.get('pfexec'))
    play_context.become_flags = pfexec_flags
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable="/bin/bash")
    assert re.match('''%s %s "'echo %s; %s'"''' % (pfexec_exe, pfexec_flags, success, default_cmd), cmd) is not None

    play_context.set_become_plugin(become_loader.get('doas'))
    play_context.become_flags = doas_flags
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable="/bin/bash")
    assert (re.match("""%s %s -u %s %s -c 'echo %s; %s'""" % (doas_exe, doas_flags, play_context.become_user, default_exe, success,
                                                              default_cmd), cmd) is not None)

    play_context.set_become_plugin(become_loader.get('ksu'))
    play_context.become_flags = ksu_flags
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable="/bin/bash")
    assert (re.match("""%s %s %s -e %s -c 'echo %s; %s'""" % (ksu_exe, play_context.become_user, ksu_flags,
                                                              default_exe, success, default_cmd), cmd) is not None)

    play_context.set_become_plugin(become_loader.get('bad'))
    with pytest.raises(AnsibleError):
        play_context.make_become_cmd(cmd=default_cmd, executable="/bin/bash")

    play_context.set_become_plugin(become_loader.get('dzdo'))
    play_context.become_flags = dzdo_flags
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable="/bin/bash")
    assert re.match("""%s %s -u %s %s -c 'echo %s; %s'""" % (dzdo_exe, dzdo_flags, play_context.become_user, default_exe,
                                                             success, default_cmd), cmd) is not None
    play_context.become_pass = '******'
    play_context.set_become_plugin(become_loader.get('dzdo'))
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable="/bin/bash")
    assert re.match("""%s %s -p %s -u %s %s -c 'echo %s; %s'""" % (dzdo_exe, dzdo_flags, r'\"\[dzdo via ansible, key=.+?\] password:\"',
                                                                   play_context.become_user, default_exe, success, default_cmd), cmd) is not None
Пример #20
0
    def __init__(self,
                 agent_address,
                 group_name='agent',
                 username=None,
                 password=None):
        self.inventory_filename = None
        with tempfile.NamedTemporaryFile('w', delete=False) as inventory:
            print('[{}]'.format(group_name), file=inventory)
            print(agent_address, file=inventory)
            self.inventory_filename = inventory.name

        self.passwords = {
            'conn_pass': password,
            'become_pass': password,
        }

        self.options = Options(  # Fill in required default values
            ask_pass=False,
            ask_su_pass=False,
            ask_sudo_pass=False,
            ask_vault_pass=False,
            become=False,
            become_ask_pass=False,
            become_method='sudo',
            become_user='******',
            check=False,
            connection='smart',
            diff=False,
            extra_vars=[],
            flush_cache=None,
            force_handlers=False,
            forks=5,
            inventory=[self.inventory_filename],
            listhosts=None,
            listtags=None,
            listtasks=None,
            module_path=None,
            new_vault_id=None,
            new_vault_password_files=[],
            private_key_file=None,
            remote_user='',
            scp_extra_args='',
            sftp_extra_args='',
            skip_tags=['questions'],
            ssh_common_args='',
            ssh_extra_args='',
            start_at_task=None,
            step=None,
            su=False,
            su_user=None,
            subset=None,
            sudo=False,
            sudo_user=None,
            syntax=None,
            tags=['all'],
            timeout=10,
            vault_ids=[],
            vault_password_files=[],
            verbosity=0,
        )
        if username is None:
            self.options.remote_user = '******'
            self.options.private_key_file = '/home/openbach/.ssh/id_rsa'
        else:
            self.options.remote_user = username

        if context is None:
            self.loader, self.inventory, self.variables = CLI._play_prereqs(
                self.options)
        else:
            context._init_global_context(self.options)
            self.loader, self.inventory, self.variables = CLI._play_prereqs()
Пример #21
0
 def playbook_all(self, playbook_name, tags_set, extra_vars_dict,
                  keyfile_path):
     ret = -1
     options = argparse.Namespace(ask_pass=False,
                                  ask_vault_pass=False,
                                  become=True,
                                  become_ask_pass=False,
                                  become_method='sudo',
                                  become_user='******',
                                  check=False,
                                  connection='smart',
                                  diff=False,
                                  extra_vars=[json.dumps(extra_vars_dict)],
                                  flush_cache=False,
                                  force_handlers=False,
                                  forks=10,
                                  listhosts=False,
                                  listtags=False,
                                  listtasks=False,
                                  module_path=None,
                                  private_key_file=keyfile_path,
                                  remote_user=None,
                                  scp_extra_args='',
                                  sftp_extra_args='',
                                  skip_tags=[],
                                  ssh_common_args='',
                                  ssh_extra_args='',
                                  start_at_task=None,
                                  step=False,
                                  subset=None,
                                  syntax=False,
                                  tags=tags_set,
                                  timeout=120,
                                  vault_ids=[],
                                  vault_password_files=[],
                                  verbosity=0,
                                  version=None)
     context._init_global_context(options)
     try:
         playbook_path = self._preinstall_playbook_path_builder(
             playbook_name)
         r_print.debug(playbook_path)
         inventry_path = '{work_dir}/.inventry'.format(
             work_dir=rdbox.config.get("ansible", "work_dir"))
         loader = DataLoader()
         self._create_inventry_file_from_k8s(inventry_path)
         inventory = InventoryManager(loader=loader, sources=inventry_path)
         variable_manager = VariableManager(loader=loader,
                                            inventory=inventory)
         #variable_manager._extra_vars = extra_vars_dict
         if not os.path.exists(playbook_path):
             raise IOError(errno.ENOENT, os.strerror(errno.ENOENT),
                           playbook_path)
         passwords = {}
         pbex = PlaybookExecutor(playbooks=[playbook_path],
                                 inventory=inventory,
                                 variable_manager=variable_manager,
                                 loader=loader,
                                 passwords=passwords)
         # redirect
         bak_stdout = sys.stdout
         bak_stderr = sys.stderr
         sys.stdout = StdLoggerWriter(r_print.debug)
         sys.stderr = StdLoggerWriter(r_print.info)
         ret = pbex.run()
     except FileNotFoundError:
         sys.stdout = bak_stdout
         sys.stderr = bak_stderr
         import traceback
         r_print.error(traceback.format_exc())
         ret = -1
     except Exception:
         sys.stdout = bak_stdout
         sys.stderr = bak_stderr
         import traceback
         r_print.error(traceback.format_exc())
         ret = -1
     finally:
         sys.stdout = bak_stdout
         sys.stderr = bak_stderr
     # Cleanup
     try:
         self._remove_file(inventry_path)
     except Exception:
         # No problem
         pass
     return ret
Пример #22
0
    "diff": False,
    "inventory": ["./hosts"],
    "listhosts": None,
    "subset": "server_a",
    "extra_vars": ["targetHost=server_b", "sourseHost=server_a"],
    "ask_vault_pass": False,
    "vault_password_files": [],
    "vault_ids": [],
    "forks": 5,
    "module_path": None,
    "listtasks": None,
    "listtags": None,
    "step": None,
    "start_at_task": None,
})

context._init_global_context(options)
loader, inventory, variable_manager = CLI._play_prereqs()
CLI.get_host_list(inventory, context.CLIARGS["subset"])

pbex = PlaybookExecutor(playbooks=["./playbooks/roles/common/tasks/main.yml"],
                        inventory=inventory,
                        variable_manager=variable_manager,
                        loader=loader,
                        passwords=dict(conn_pass="******",
                                       become_pass="******"))

result_callback = ResultCallback()
pbex._tqm._stdout_callback = result_callback
result_id = pbex.run()
result = result_callback.getResult()
Пример #23
0
def test_sudo(mocker, parser, reset_cli_args):
    options = parser.parse_args([])
    context._init_global_context(options)

    sudo = become_loader.get('sudo')
    sh = shell_loader.get('sh')
    sh.executable = "/bin/bash"

    sudo.set_options(direct={
        'become_user': '******',
        'become_flags': '-n -s -H',
    })

    cmd = sudo.build_become_command('/bin/foo', sh)

    assert re.match(
        r"""sudo\s+-n -s -H\s+-u foo /bin/bash -c 'echo BECOME-SUCCESS-.+? ; /bin/foo'""",
        cmd), cmd

    sudo.set_options(
        direct={
            'become_user': '******',
            'become_flags': '-n -s -H',
            'become_pass': '******',
        })

    cmd = sudo.build_become_command('/bin/foo', sh)
    assert re.match(
        r"""sudo\s+-s\s-H\s+-p "\[sudo via ansible, key=.+?\] password:"******""",
        cmd), cmd

    sudo.set_options(direct={
        'become_user': '******',
        'become_flags': '-snH',
        'become_pass': '******',
    })

    cmd = sudo.build_become_command('/bin/foo', sh)
    assert re.match(
        r"""sudo\s+-sH\s+-p "\[sudo via ansible, key=.+?\] password:"******""",
        cmd), cmd

    sudo.set_options(
        direct={
            'become_user': '******',
            'become_flags': '--non-interactive -s -H',
            'become_pass': '******',
        })

    cmd = sudo.build_become_command('/bin/foo', sh)
    assert re.match(
        r"""sudo\s+-s\s-H\s+-p "\[sudo via ansible, key=.+?\] password:"******""",
        cmd), cmd

    sudo.set_options(
        direct={
            'become_user': '******',
            'become_flags': '--non-interactive -nC5 -s -H',
            'become_pass': '******',
        })

    cmd = sudo.build_become_command('/bin/foo', sh)
    assert re.match(
        r"""sudo\s+-C5\s-s\s-H\s+-p "\[sudo via ansible, key=.+?\] password:"******""",
        cmd), cmd
Пример #24
0
def test_play_context_make_become_cmd(mocker, parser, reset_cli_args):
    (options, args) = parser.parse_args([])
    options.args = args
    context._init_global_context(options)
    play_context = PlayContext()

    default_cmd = "/bin/foo"
    default_exe = "/bin/bash"
    sudo_exe = C.DEFAULT_SUDO_EXE or 'sudo'
    sudo_flags = C.DEFAULT_SUDO_FLAGS
    su_exe = C.DEFAULT_SU_EXE or 'su'
    su_flags = C.DEFAULT_SU_FLAGS or ''
    pbrun_exe = 'pbrun'
    pbrun_flags = ''
    pfexec_exe = 'pfexec'
    pfexec_flags = ''
    doas_exe = 'doas'
    doas_flags = ' -n  -u foo '
    ksu_exe = 'ksu'
    ksu_flags = ''
    dzdo_exe = 'dzdo'
    dzdo_flags = ''

    cmd = play_context.make_become_cmd(cmd=default_cmd, executable=default_exe)
    assert cmd == default_cmd

    play_context.become = True
    play_context.become_user = '******'

    play_context.become_method = 'sudo'
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable="/bin/bash")
    assert (cmd == """%s %s -u %s %s -c 'echo %s; %s'""" %
            (sudo_exe, sudo_flags, play_context.become_user, default_exe,
             play_context.success_key, default_cmd))

    play_context.become_pass = '******'
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable=default_exe)
    assert (cmd == """%s %s -p "%s" -u %s %s -c 'echo %s; %s'""" %
            (sudo_exe, sudo_flags.replace(
                '-n', ''), play_context.prompt, play_context.become_user,
             default_exe, play_context.success_key, default_cmd))

    play_context.become_pass = None
    play_context.become_method = 'su'
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable="/bin/bash")
    assert (cmd == """%s  %s -c '%s -c '"'"'echo %s; %s'"'"''""" %
            (su_exe, play_context.become_user, default_exe,
             play_context.success_key, default_cmd))

    play_context.become_method = 'pbrun'
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable="/bin/bash")
    assert cmd == """%s %s -u %s 'echo %s; %s'""" % (
        pbrun_exe, pbrun_flags, play_context.become_user,
        play_context.success_key, default_cmd)

    play_context.become_method = 'pfexec'
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable="/bin/bash")
    assert cmd == '''%s %s "'echo %s; %s'"''' % (
        pfexec_exe, pfexec_flags, play_context.success_key, default_cmd)

    play_context.become_method = 'doas'
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable="/bin/bash")
    assert (cmd == """%s %s %s -c 'echo %s; %s'""" %
            (doas_exe, doas_flags, default_exe, play_context.success_key,
             default_cmd))

    play_context.become_method = 'ksu'
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable="/bin/bash")
    assert (cmd == """%s %s %s -e %s -c 'echo %s; %s'""" %
            (ksu_exe, play_context.become_user, ksu_flags, default_exe,
             play_context.success_key, default_cmd))

    play_context.become_method = 'bad'
    with pytest.raises(AnsibleError):
        play_context.make_become_cmd(cmd=default_cmd, executable="/bin/bash")

    play_context.become_method = 'dzdo'
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable="/bin/bash")
    assert cmd == """%s %s -u %s %s -c 'echo %s; %s'""" % (
        dzdo_exe, dzdo_flags, play_context.become_user, default_exe,
        play_context.success_key, default_cmd)

    play_context.become_pass = '******'
    play_context.become_method = 'dzdo'
    cmd = play_context.make_become_cmd(cmd=default_cmd, executable="/bin/bash")
    assert (cmd == """%s %s -p %s -u %s %s -c 'echo %s; %s'""" %
            (dzdo_exe, dzdo_flags, shlex_quote(
                play_context.prompt), play_context.become_user, default_exe,
             play_context.success_key, default_cmd))