当前位置: 首页>>代码示例>>Python>>正文


Python VariableManager.set_inventory方法代码示例

本文整理汇总了Python中ansible.vars.VariableManager.set_inventory方法的典型用法代码示例。如果您正苦于以下问题:Python VariableManager.set_inventory方法的具体用法?Python VariableManager.set_inventory怎么用?Python VariableManager.set_inventory使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ansible.vars.VariableManager的用法示例。

在下文中一共展示了VariableManager.set_inventory方法的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: AnsibleTask

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
def AnsibleTask(task_list,host_list,user):
    '''ansible python api 2.0'''
    loader = DataLoader()
    variable_manager = VariableManager()
    inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=host_list)
    variable_manager.set_inventory(inventory)
    task_dict = []
    for i in task_list:
        task_dict.append({"action": {"module": i[0], "args": i[1] }})
    variable_manager.extra_vars = {"ansible_ssh_user": user, "ansible_ssh_pass": ""}
    play_source = {"name" : "Ansible PlayBook Run", "hosts": host_list[0], "gather_facts": "no","tasks": task_dict}
    play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
    tqm = None
    try:
        tqm = TaskQueueManager(
            inventory = inventory,
            variable_manager = variable_manager,
            loader = loader,
            options = options,
            passwords = None,
            stdout_callback = 'minimal',
            run_tree = False,
        )
        result = tqm.run(play)
    except Exception,e:
        result = e
开发者ID:huizhe2016,项目名称:Python-methods,代码行数:28,代码来源:ansible_api.py


示例2: call_ansible

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
def call_ansible(yaml_file, become=False, tag=None):
  """Call Ansible with a playbook."""

  variable_manager = VariableManager()
  loader           = DataLoader()
  inventory        = Inventory(loader, variable_manager)
  variable_manager.set_inventory(inventory)

  Options = namedtuple('Options',
                       ['listtags',
                        'listtasks',
                        'listhosts',
                        'syntax',
                        'connection',
                        'module_path',
                        'forks',
                        'remote_user',
                        'private_key_file',
                        'ssh_common_args',
                        'ssh_extra_args',
                        'sftp_extra_args',
                        'scp_extra_args',
                        'become',
                        'become_method',
                        'become_user',
                        'verbosity',
                        'check',
                        'tags'])

  options = Options(listtags=False,
                    listtasks=False,
                    listhosts=False,
                    syntax=False,
                    connection='',
                    module_path='',
                    forks=100,
                    remote_user='',
                    private_key_file=None,
                    ssh_common_args=None,
                    ssh_extra_args=None,
                    sftp_extra_args=None,
                    scp_extra_args=None,
                    become=become,
                    become_method='sudo',
                    become_user='root',
                    verbosity=2,
                    check=False,
                    tags=tag)

  pbex = PlaybookExecutor(playbooks=[yaml_file],
                          inventory=inventory,
                          variable_manager=variable_manager,
                          loader=loader,
                          options=options,
                          passwords={})

  logger.debug("Calling Ansible with yaml file: {}".format(yaml_file))
  result = pbex.run()
  if result:
    logger.error("An error occured whilst executing the Ansible Playbook.")
开发者ID:desdrury,项目名称:k8sdc,代码行数:62,代码来源:utility.py


示例3: __init__

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
    def __init__(self, **kwargs):
        super(Ansible_playbook, self).__init__(**kwargs)

        self.task_file = kwargs.get('task_file', None)
        self.sudo = kwargs.get('sudo', False)
        self.sudo_user = kwargs.get('sudo_user', False)
        self.sudo_password = kwargs.get('sudo_password', False)

        # check if parameters have been provided
        if self._is_parameters_ok():

            variable_manager = VariableManager()
            loader = DataLoader()
            options = self._get_options()
            passwords = {'become_pass': self.sudo_password}

            inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list="localhost")
            variable_manager.set_inventory(inventory)
            playbooks = [self.task_file]

            executor = PlaybookExecutor(
                playbooks=playbooks,
                inventory=inventory,
                variable_manager=variable_manager,
                loader=loader,
                options=options,
                passwords=passwords)

            executor.run()
开发者ID:igorstarki,项目名称:kalliope,代码行数:31,代码来源:ansible_playbook.py


示例4: PlayBook

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
class PlayBook(object):
    def __init__(self, inventory='/etc/ansible/hosts', extra_vars=None, private_key_file=None):
        """
        :param playbook: playbook.yml
        :param inventory: inventory file or script
        :type param extra_vars: dict
        :param private_key_file: ssh private key
        """
        self.pbex = None
        self.options = Options(private_key_file=private_key_file, connection='smart', forks=10, timeout=10,
                               verbosity=0, check=False,
                               listtasks=False, listhosts=False, syntax=False,
                               subset=None, module_path=None, become=None, become_user=None, become_method='sudo')

        # initialize needed objects
        self.loader = DataLoader()
        self.variable_manager = VariableManager()
        self.variable_manager.extra_vars = extra_vars
        self.variable_manager.options_vars = {'ansible_check_mode': self.options.check}
        self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list=inventory)
        self.variable_manager.set_inventory(self.inventory)
        # Limits inventory results to a subset of inventory that matches a given pattern
        self.inventory._subset = self.options.subset

    def run_playbook(self, playbook):
        self.pbex = PlaybookExecutor(playbooks=[playbook], inventory=self.inventory,
                                     variable_manager=self.variable_manager,
                                     loader=self.loader, options=self.options,
                                     passwords={'conn_pass': None, 'become_pass': None})
        self.pbex._tqm._stdout_callback = ResultCallback()
        return self.pbex.run()

    def run_play(self, play):
        pass
开发者ID:nxintech,项目名称:Charlie,代码行数:36,代码来源:playbook_api2.py


示例5: ansible_task

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
def ansible_task(playbooks):
    Options = namedtuple('Options', \
    ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'listhosts', 'listtasks', 'listtags', 'syntax'])

    options = Options(
        connection = 'ssh', 
        module_path = '/opt/ansible/modules',
        forks = 100, 
        become = True, 
        become_method = 'sudo', 
        become_user = 'root', 
        check = False, 
        listhosts = None,
        listtasks = None,
        listtags = None,
        syntax = None
    )

    loader = DataLoader()
    variable_manager = VariableManager()
    inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list='/opt/ansible/inventory')
    variable_manager.set_inventory(inventory)

    pb = PlaybookExecutor(playbooks=[playbooks], inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=None)
    pb.run()

    stats = pb._tqm._stats
    ips = stats.processed.keys()
    return [ {ip : stats.summarize(ip)} for ip in ips ]
开发者ID:liujitao,项目名称:teamworkflow,代码行数:31,代码来源:views.py


示例6: playbook_api

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
 def playbook_api(self,yml_fp):
     loader = DataLoader()
     variable_manager = VariableManager()
     
     inventory = Inventory(
         loader=loader,
         variable_manager=variable_manager,
         host_list=self.ansible_host_list
     )
     
     variable_manager.set_inventory(inventory)
     
     playbooks = ["%s" % yml_fp]
     
     pbex = PlaybookExecutor(
                   playbooks=playbooks,
                   inventory=inventory,
                   variable_manager=variable_manager,
                   loader=loader,
                   options=self.options,
                   passwords=self.passwords
             )
                   
     callback = AnsiCallBack()
     pbex._tqm._stdout_callback = callback
     pbex.run()
     
     return self.evaluate_results(callback)
开发者ID:527593036,项目名称:AnsiApi,代码行数:30,代码来源:ansi2v.py


示例7: execute_action

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
  def execute_action(self, action, args):
    """
    Execute the requested operation
    """
    C.DEFAULT_ROLES_PATH = [os.path.join(ROLESDIR, str(action))]

    i3xfce.loggers.ROOTLOGGER.debug("Executing the %s action", action)
    # Get the real user behind the sudo
    username = os.getenv("SUDO_USER")

    if username is None:
      i3xfce.loggers.ROOTLOGGER.debug("Unable to get SUDO_USER environment variable. This means i3-xfce has not been \
      started using sudo")
      raise Exception("This program must be ran using sudo ")

    i3xfce.loggers.ROOTLOGGER.debug("Creating the option tuple")
    options_tuple = namedtuple('Options', ['connection', 'forks', 'module_path', 'become_user', 'become',
                                           'become_method', 'check', 'verbosity'])
    try:
      # initialize needed objects
      variable_manager = VariableManager()
      variable_manager.extra_vars = dict(action=str(action),
                                         remote_user=username)

      loader = DataLoader()
      i3xfce.loggers.ROOTLOGGER.debug("Creating option to count number of tasks to execute")
      options = options_tuple(connection=None, module_path=None, forks=1, become_user=None,
                              become=None, become_method=None, verbosity=0, check=True)
      tasks_count_callback = TaskCountCallback()
      # create inventory and pass to var manager
      inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=None)
      variable_manager.set_inventory(inventory)
      # create play with tasks
      play_source = dict(
          name="Ansible Play",
          hosts='localhost',
          gather_facts='no',
          ignore_errors="yes",
          roles=args.parts
          )
      CmdLine._execute_play(play_source, inventory, variable_manager, loader, options, tasks_count_callback)

      i3xfce.loggers.ROOTLOGGER.debug("%i tasks are going to be executed", tasks_count_callback.get_total_tasks_num())
      play_source["ignore_errors"] = "no"
      options = options_tuple(connection=None, module_path=None, forks=1, become_user=None, become=None,
                              become_method=None, verbosity=0, check=args.dryrun)
      self._results_callback = PlaybookExecutionCallback(tasks_count_callback.get_total_tasks_num(),
                                                         tasks_count_callback.get_task_name_max_len())
      CmdLine._execute_play(play_source, inventory, variable_manager, loader, options, self._results_callback)

      self._results_callback.get_progress_bar().stop()
      self._results_callback.get_progress_bar().join()

      if self._results_callback.get_task_failed() is True:
        raise TaskExecutionException("")
    except TaskExecutionException as exc:
      raise
    except Exception as exc:
      raise TaskExecutionException(str(exc))
开发者ID:aacebedo,项目名称:i3-xfce,代码行数:61,代码来源:core.py


示例8: Runner

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
class Runner(object):
    def __init__(self, playbook, display, hosts=None, options={}, passwords={}, vault_pass=None):

        self.options = Options()
        for k, v in options.iteritems():
            setattr(self.options, k, v)

        self.display = display
        self.display.verbosity = self.options.verbosity
        # executor has its own verbosity setting
        playbook_executor.verbosity = self.options.verbosity

        # gets data from YAML/JSON files
        self.loader = DataLoader()
        if vault_pass is not None:
            self.loader.set_vault_password(vault_pass)
        elif 'VAULT_PASS' in os.environ:
            self.loader.set_vault_password(os.environ['VAULT_PASS'])

        # all the variables from all the various places
        self.variable_manager = VariableManager()
        if self.options.python_interpreter is not None:
            self.variable_manager.extra_vars = {
                'ansible_python_interpreter': self.options.python_interpreter
            }

        # set inventory, using most of above objects
        self.inventory = Inventory(
            loader=self.loader, variable_manager=self.variable_manager,
            host_list=hosts)

        if len(self.inventory.list_hosts()) == 0:
            self.display.error("Provided hosts list is empty.")
            sys.exit(1)

        self.inventory.subset(self.options.subset)

        if len(self.inventory.list_hosts()) == 0:
            self.display.error("Specified limit does not match any hosts.")
            sys.exit(1)

        self.variable_manager.set_inventory(self.inventory)

        # setup playbook executor, but don't run until run() called
        self.pbex = playbook_executor.PlaybookExecutor(
            playbooks=[playbook],
            inventory=self.inventory,
            variable_manager=self.variable_manager,
            loader=self.loader,
            options=self.options,
            passwords=passwords)

    def run(self):
        # run playbook and get stats
        self.pbex.run()
        stats = self.pbex._tqm._stats

        return stats
开发者ID:mcsrainbow,项目名称:python-demos,代码行数:60,代码来源:ansible_runner.py


示例9: main

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
def main():
    host_list  = ['localhost', 'www.example.com', 'www.google.com']
    Options = namedtuple('Options', ['connection','module_path', 'forks', 'remote_user',
            'private_key_file', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args',
            'scp_extra_args', 'become', 'become_method', 'become_user', 'verbosity', 'check'])

    # initialize needed objects
    variable_manager = VariableManager()
    loader = DataLoader()
    options = Options(connection='smart', module_path='/usr/share/ansible', forks=100,
            remote_user=None, private_key_file=None, ssh_common_args=None, ssh_extra_args=None,
            sftp_extra_args=None, scp_extra_args=None, become=None, become_method=None,
            become_user=None, verbosity=None, check=False)

    passwords = dict()

    # create inventory and pass to var manager
    inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=host_list)
    variable_manager.set_inventory(inventory)

    # create play with tasks
    play_source =  dict(
            name = "Ansible Play",
            hosts = host_list,
            gather_facts = 'no',
            tasks = [ dict(action=dict(module='command', args=dict(cmd='/usr/bin/uptime'))) ]
        )
    play = Play().load(play_source, variable_manager=variable_manager, loader=loader)

    # actually run it
    tqm = None
    callback = ResultsCollector()
    try:
        tqm = TaskQueueManager(
                inventory=inventory,
                variable_manager=variable_manager,
                loader=loader,
                options=options,
                passwords=passwords,
            )
        tqm._stdout_callback = callback
        result = tqm.run(play)
    finally:
        if tqm is not None:
            tqm.cleanup()

    print "UP ***********"
    for host, result in callback.host_ok.items():
        print '{} >>> {}'.format(host, result._result['stdout'])

    print "FAILED *******"
    for host, result in callback.host_failed.items():
        print '{} >>> {}'.format(host, result._result['msg'])

    print "DOWN *********"
    for host, result in callback.host_unreachable.items():
        print '{} >>> {}'.format(host, result._result['msg'])
开发者ID:KMK-ONLINE,项目名称:ansible,代码行数:59,代码来源:uptime.py


示例10: get_inventory

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
def get_inventory(inventory='hosts'):
    if HAS_ANSIBLE2:
        loader = DataLoader()
        variable_manager = VariableManager()
        inventory = Inventory(loader=loader, variable_manager=variable_manager)
        variable_manager.set_inventory(inventory)
    else:
        inventory_filename = "%s/%s" % (ANSIBLE_DIR, inventory)
        inventory = Inventory(host_list=inventory_filename)
    return inventory
开发者ID:hasiotis,项目名称:vmbuilder,代码行数:12,代码来源:utils.py


示例11: main

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
def main(args):
    # Options definition
    # Custom tuple to store playbook options
    Options = namedtuple('Options', ['connection', 'module_path', 'forks',
                                     'become', 'become_method', 'become_user',
                                     'check'])

    # Object initialization
    variable_manager = VariableManager()
    loader = DataLoader()
    options = Options(connection='ssh',module_path='library',
                      forks=100, become=None, become_method=None,
                      become_user=None, check=False)
    passwords = {}

    # Dinamyc inventory
    inventory = Inventory(loader=loader, variable_manager=variable_manager,
                          host_list=args)

    # Inventory assignation
    variable_manager.set_inventory(inventory)

    # Play creation with tasks
    play_source = dict(
         name="Ansible Play",
         hosts=args,
         gather_facts='no',
         tasks=[
             dict(action=dict(module='shell', args='hostname -f'),
                  register='shell_out'),
             dict(action=dict(module='debug',
                              args=dict(msg='{{shell_out.stdout}}')))
         ]
    )

    play = Play().load(play_source, variable_manager=variable_manager,
                       loader=loader)

    # Running it
    tqm = None
    try:
        tqm = TaskQueueManager(
                      inventory=inventory,
                      variable_manager=variable_manager,
                      loader=loader,
                      options=options,
                      passwords=passwords,
                      stdout_callback='default'
        )
        result = tqm.run(play)
    finally:
        if tqm is not None:
                    tqm.cleanup()
开发者ID:jadebustos,项目名称:ansible,代码行数:55,代码来源:ansible2.x-example.py


示例12: main

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
def main(argv=sys.argv[1:]):
    Options = namedtuple('Options', ['connection', 'module_path', 'forks',
                                     'become', 'become_method', 'become_user',
                                     'check'])
    # initialize needed objects
    variable_manager = VariableManager()
    loader = DataLoader()
    options = Options(connection='local', module_path='/path/to/mymodules',
                      forks=100, become=None, become_method=None,
                      become_user=None,
                      check=False)

    passwords = dict(vault_pass='secret')

    # create inventory and pass to var manager
    inventory = Inventory(loader=loader, variable_manager=variable_manager,
                          host_list='localhost')

    variable_manager.set_inventory(inventory)

    # create play with tasks
    play_source = dict(name="Ansible Play",
                       hosts='localhost',
                       gather_facts='no',
                       tasks=[
                           dict(action=dict(module='shell',
                                args='uname -a'), register='shell_out'),
                           dict(action=dict(module='debug',
                                args=dict(msg='{{shell_out.stdout}}')))
                       ]
                       )

    play = Play().load(play_source, variable_manager=variable_manager,
                       loader=loader)

    # actually run it
    tqm = None
    try:
        tqm = TaskQueueManager(inventory=inventory,
                               variable_manager=variable_manager,
                               loader=loader,
                               options=options,
                               passwords=passwords,
                               stdout_callback='default',
                               )

        result = tqm.run(play)
        print result
    finally:
        if tqm is not None:
            tqm.cleanup()
开发者ID:javiroman,项目名称:foreman-op,代码行数:53,代码来源:embedded-uname.py


示例13: Runner

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
class Runner(object):

    def __init__(self, hostnames, playbook, private_key_file, run_data, become_pass=None,
                 verbosity=0, callback=None, subset_pattern=None):

        self.hostnames = hostnames

        self.playbook = os.path.join(playbooks_dir, playbook)
        self.run_data = run_data

        self.options = Options(subset=subset_pattern, private_key_file=private_key_file, verbosity=verbosity)

        self.display = Display()
        self.display.verbosity = verbosity
        playbook_executor.verbosity = verbosity

        passwords = {'become_pass': None}

        # Gets data from YAML/JSON files
        self.loader = DataLoader()
        self.loader.set_vault_password(os.environ.get('VAULT_PASS'))

        self.variable_manager = VariableManager()
        self.variable_manager.extra_vars = self.run_data

        self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list=self.hostnames)
        self.variable_manager.set_inventory(self.inventory)

        self.pbex = playbook_executor.PlaybookExecutor(
            playbooks=[self.playbook],
            inventory=self.inventory,
            variable_manager=self.variable_manager,
            loader=self.loader,
            options=self.options,
            passwords=passwords)

        if callback:
            self.pbex._tqm._stdout_callback = callback

    def run(self):
        self.pbex.run()
        stats = self.pbex._tqm._stats

        run_success = True
        hosts = sorted(stats.processed.keys())
        for h in hosts:
            t = stats.summarize(h)
            if t['unreachable'] > 0 or t['failures'] > 0:
                run_success = False

        return run_success
开发者ID:arokem,项目名称:myria-ec2-ansible,代码行数:53,代码来源:cli.py


示例14: main

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
def main(argv=sys.argv[1:]):
    #
    # initialize needed objects
    #
    variable_manager = VariableManager()
    loader = DataLoader()
    # https://pymotw.com/2/collections/namedtuple.html
    Options = namedtuple('Options', ['listtags', 'listtasks', 'listhosts',
                                     'syntax', 'connection', 'module_path',
                                     'forks', 'remote_user', 'private_key_file',
                                     'ssh_common_args', 'ssh_extra_args',
                                     'sftp_extra_args', 'scp_extra_args',
                                     'become', 'become_method', 'become_user',
                                     'verbosity', 'check'])

    options = Options(listtags=False, listtasks=False, listhosts=False,
                      syntax=False, connection='local', module_path=None,
                      forks=100, remote_user='slotlocker',
                      private_key_file=None, ssh_common_args=None,
                      ssh_extra_args=None, sftp_extra_args=None,
                      scp_extra_args=None, become=True, become_method=None,
                      become_user='root', verbosity=None, check=False)

    passwords = {}

    inventory = Inventory(loader=loader, variable_manager=variable_manager,
                          host_list='./ls_hosts')

    variable_manager.set_inventory(inventory)

    playbook_path = './ls.yml'
    if not os.path.exists(playbook_path):
        print '[INFO] The playbook does not exist'
        sys.exit()

    # This can accomodate various other command line arguments.`
    # variable_manager.extra_vars = {'hosts': 'mywebserver'}

    pbex = PlaybookExecutor(playbooks=[playbook_path],
                            inventory=inventory,
                            variable_manager=variable_manager,
                            loader=loader,
                            options=options,
                            passwords=passwords)

    # cb = ResultAccumulator()
    # pbex._tqm._stdout_callback = cb

    results = pbex.run()
    if results != 0:
        print "ERROR"
开发者ID:javiroman,项目名称:foreman-op,代码行数:53,代码来源:embedded-ls.py


示例15: AnsibleTask

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
class AnsibleTask(object):

    def __init__(self, hosts='127.0.0.1', module='shell', args='ls -l',
                 options=DEFAULT_OPTIONS, name='Ansible Play'):
        self.hosts = hosts
        self.module = module
        self.args = args
        self.options = options
        self.name = name
        self.task = dict(action=dict(
            module=self.module, args=self.args
        ), register='shell_out')
        self.tasks = [self.task]
        # initialize needed objects
        self.variable_manager = VariableManager()
        self.loader = DataLoader()
        self.passwords = dict()
        self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list=[self.hosts])
        self.variable_manager.set_inventory(self.inventory)
        self.play_source = dict(
            name=self.name, hosts=self.hosts,
            gather_facts='no', tasks=self.tasks
        )
        self.play = Play().load(self.play_source, loader=self.loader,
                                variable_manager=self.variable_manager)
        self.results_callback = ResultCallback()
        self.return_results = {}
        setattr(self.results_callback, 'task_obj', self)

    def ansible_play(self):
        # run it
        tqm = None
        try:
            tqm = TaskQueueManager(
                inventory=self.inventory,
                variable_manager=self.variable_manager,
                loader=self.loader,
                options=self.options,
                passwords=self.passwords,
                stdout_callback=self.results_callback,
                # stdout_callback='default',
            )
            result = tqm.run(self.play)
        finally:
            if tqm is not None:
                tqm.cleanup()
                #self.inventory.clear_pattern_cache()
            if result != 0:
                raise ValueError('SSH Command Failed, resturn: %s' % result)
            return self.return_results
开发者ID:Zexi,项目名称:perf-scripts,代码行数:52,代码来源:ansible_pst.py


示例16: test_base

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
    def test_base(self):
        test_inv_dir = 'test/inventory'
        for inv in os.listdir(test_inv_dir):
            print "Processing ", inv
            res = dynlxc.main(os.path.join(test_inv_dir, inv), '')

            variable_manager = VariableManager()
            loader = DataLoader()
            self.mock_rv.communicate.return_value = [
                json.dumps(res), 'mocked_err']
            try:
                inventory = Inventory(
                    loader=loader,
                    variable_manager=variable_manager,
                    host_list='inventory/dynlxc.py'
                )
            except Exception as err:
                raise Exception("Inventory file {0} processing result '{1}' "
                                "failed with {2}".format(inv, res, err))
            variable_manager.set_inventory(inventory)

            play_source = dict(name="Ansible Play", hosts='localhost',
                               gather_facts='no')

            playbook = os.path.abspath(os.path.join(test_inv_dir,
                                       '../playbooks', inv))
            if os.path.isfile(playbook):
                with open(playbook) as fh:
                    real_playbook = yaml.load(fh)[0]
                    play_source.update(real_playbook)

            play = Play().load(play_source, variable_manager=variable_manager,
                               loader=loader)
            tqm = None
            try:
                tqm = TaskQueueManager(
                    inventory=inventory,
                    variable_manager=variable_manager,
                    loader=loader,
                    options=self.options,
                    passwords=None,
                    stdout_callback='default',
                )
                result = tqm.run(play)
                assert result == 0, ("Ansible playbook exitcode "
                                     "different from 0")
            finally:
                if tqm is not None:
                    tqm.cleanup()
开发者ID:devjatkin,项目名称:stackforce-ansible,代码行数:51,代码来源:tests_dynlxc.py


示例17: main

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
def main(host_list,module,args):
    Options = namedtuple('Options', ['connection','module_path', 'forks', 'remote_user',
            'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args',
            'scp_extra_args', 'become', 'become_method', 'become_user', 'verbosity', 'check'])

    # initialize needed objects
    variable_manager = VariableManager()
    loader = DataLoader()
    options = Options(connection='smart', module_path='xxx', forks=50,
            remote_user='root', ssh_common_args=None, ssh_extra_args=None,
            sftp_extra_args=None, scp_extra_args=None, become=None, become_method=None,
            become_user=None, verbosity=None, check=False)

    passwords = dict(sshpass=None, becomepass=None)

    # create inventory and pass to var manager
    inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=host_list)
    variable_manager.set_inventory(inventory)

    # create play with tasks
    play_source =  dict(
            name = "Ansible Play",
            hosts = host_list,
            gather_facts = 'no',
            tasks = [ dict(action=dict(module=module, args=args)) ]
        )
    play = Play().load(play_source, variable_manager=variable_manager, loader=loader)

    # actually run it
    tqm = None
    callback = ResultsCollector()
    try:
        tqm = TaskQueueManager(
                inventory=inventory,
                variable_manager=variable_manager,
                loader=loader,
                options=options,
                passwords=passwords,
            )
        tqm._stdout_callback = callback
        tqm.run(play)
        return callback.results[0]['tasks'][0]['hosts']

    finally:
        if tqm is not None:
            tqm.cleanup()
开发者ID:qwerkinglin,项目名称:CMDB_platform,代码行数:48,代码来源:ansible_project_task.py


示例18: hosts_for_tag

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
def hosts_for_tag(cluster_config, tag):

    if not os.path.isfile(cluster_config):
        print("Hostfile does not exist {}".format(cluster_config))
        sys.exit(1)

    variable_manager = VariableManager()
    loader = DataLoader()

    i = ansible.inventory.Inventory(loader=loader, variable_manager=variable_manager, host_list=cluster_config)
    variable_manager.set_inventory(i)

    group = i.get_group(tag)
    if group is None:
        return []
    hosts = group.get_hosts()
    return [host.get_vars() for host in hosts]
开发者ID:couchbaselabs,项目名称:mobile-testkit,代码行数:19,代码来源:provisioning_config_parser.py


示例19: run

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
    def run(experimentid, playbook_path, host_list=C.DEFAULT_HOST_LIST):
        # print self.file_name
        # print self.path
        # print self.file.read()
        Options = namedtuple('Options',
                             ['connection', 'module_path', 'forks', 'remote_user', 'private_key_file',
                              'ssh_common_args',
                              'ssh_extra_args', 'sftp_extra_args', 'scp_extra_args', 'become', 'become_method',
                              'become_user', 'verbosity', 'check', 'listhosts', 'listtasks', 'listtags', 'syntax', 'host_key_checking'])
        variable_manager = VariableManager()

        loader = DataLoader()
        options = Options(connection='ssh', module_path=None, forks=100, remote_user='root', private_key_file=None,
                      ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=None,
                      become_method=None, become_user='root', verbosity=None, check=False, listhosts=None, listtasks=None, listtags=None, syntax=None, host_key_checking=False)
        passwords = dict(vault_pass='secret')

        # create inventory and pass to var manager
        inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=host_list)

        #print host_list
        #print inventory.split_host_pattern(host_list)
        #inventory.parse_inventory(host_list)
        #print inventory.host_list
        #print inventory.get_hosts()
        variable_manager.set_inventory(inventory)

        # create the playbook executor, which manages running the plays via a task queue manager
        # playbook_path = self.file_name

        pbex = PlaybookExecutor(playbooks=[playbook_path], inventory=inventory, variable_manager=variable_manager,
                            loader=loader, options=options, passwords=passwords)
        # pbex._tqm._callback_plugins.append(C.DEFAULT_STDOUT_CALLBACK)
        # pbex._tqm._callback_plugins.append('default')
        # pbex._tqm._callback_plugins.append('default')
        # pbex._tqm._callback_plugins.append('default')

        pbex._tqm._callback_plugins.append(AnsibleCallbackModule(experimentid))
        # pbex._tqm._callback_plugins.append(TreeCallbackModule())

        pbex._playbooks
        results = pbex.run()

        # dont forget to clear host cache after finish, otherwise will raise exception when host_list changes in the new round
        inventory.clear_pattern_cache()
开发者ID:nus-ncl,项目名称:ansible,代码行数:47,代码来源:playbookhandler.py


示例20: execute_tasks

# 需要导入模块: from ansible.vars import VariableManager [as 别名]
# 或者: from ansible.vars.VariableManager import set_inventory [as 别名]
def execute_tasks(play_name, tasks, hosts, host_list=os.path.join(DIRNAME, 'ansible_hosts.py'), callback="default"):
    # NOTICE: Here is a trick. The host we acquired must in the host list
    # everytime. However I can't get the host list in advance. So I add the
    # hosts into the host list eveytime if it doesn't exist.
    if hosts not in ansible_hosts.hosts["all"]["hosts"]:
        ansible_hosts.hosts["all"]["hosts"].append(hosts)

    # initialize needed objects
    variable_manager = VariableManager()
    loader = DataLoader()

    # create inventory and pass to var manager
    inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=host_list)
    variable_manager.set_inventory(inventory)

    # create play with tasks
    play_source = dict(
        name=play_name,
        hosts=hosts,
        gather_facts='no',
        tasks=tasks)

    play = Play().load(play_source, variable_manager=variable_manager, loader=loader)

    Options = namedtuple('Options', ['connection', 'module_path', 'forks',
        'become', 'become_method', 'become_user', 'check'])
    options = Options(connection=None, module_path=None, forks=10, become=None,
        become_method=None, become_user=None, check=False)
    passwords = dict()

    # actually run it
    tqm = None
    try:
        tqm = TaskQueueManager(
            inventory=inventory,
            variable_manager=variable_manager,
            loader=loader,
            options=options,
            passwords=passwords,
            stdout_callback=callback)
        return tqm.run(play)
    finally:
        if tqm is not None:
            tqm.cleanup()
        pass
开发者ID:litterbear,项目名称:initcloud_web,代码行数:47,代码来源:api.py



注:本文中的ansible.vars.VariableManager.set_inventory方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。