當前位置: 首頁>>代碼示例>>Python>>正文


Python inventory.Inventory方法代碼示例

本文整理匯總了Python中ansible.inventory.Inventory方法的典型用法代碼示例。如果您正苦於以下問題:Python inventory.Inventory方法的具體用法?Python inventory.Inventory怎麽用?Python inventory.Inventory使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在ansible.inventory的用法示例。


在下文中一共展示了inventory.Inventory方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: get_play_prereqs_2

# 需要導入模塊: from ansible import inventory [as 別名]
# 或者: from ansible.inventory import Inventory [as 別名]
def get_play_prereqs_2(self, options):
        loader = DataLoader()

        if self.vault_pass:
            loader.set_vault_password(self.vault_pass)

        variable_manager = VariableManager()
        variable_manager.extra_vars = self.extra_vars
        variable_manager.options_vars = {'ansible_version': self.version_info(ansible_version)}

        inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=options.inventory)
        variable_manager.set_inventory(inventory)

        # let inventory know which playbooks are using so it can know the
        # basedirs
        inventory.set_playbook_basedir(os.path.dirname(self.playbook_file))

        return loader, inventory, variable_manager 
開發者ID:grycap,項目名稱:im,代碼行數:20,代碼來源:ansible_launcher.py

示例2: __init__

# 需要導入模塊: from ansible import inventory [as 別名]
# 或者: from ansible.inventory import Inventory [as 別名]
def __init__(self, host_list, module_name, args, private_key_file="/root/.ssh/id_rsa", forks=5, extra_vars=None):
        super(AnsibleAdhcTask, self).__init__(host_list, private_key_file, forks, extra_vars)
        self.call_back = result_collector.CallbackModule()

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

        # create play with tasks
        play_source = dict(
            name="Ansible Play",
            hosts='all',
            gather_facts='no',
            tasks=[dict(action=dict(module=module_name, args=args))]
        )
        self.play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader) 
開發者ID:510908220,項目名稱:heartbeats,代碼行數:20,代碼來源:ansible_task.py

示例3: adduser

# 需要導入模塊: from ansible import inventory [as 別名]
# 或者: from ansible.inventory import Inventory [as 別名]
def adduser(ips, users):
    inventory ="""
    {% for i in hosts -%}
    {{ i }}
    {% endfor %}
    """
    inventory_template = jinja2.Template(inventory)
    rendered_inventory = inventory_template.render({'hosts': ips})
    hosts = NamedTemporaryFile(delete=False,suffix='tmp',dir='/tmp/ansible/')
    hosts.write(rendered_inventory)
    hosts.close()
    inventory = Inventory(hosts.name)
    stats =  callbacks.AggregateStats()
    playbook_cb =callbacks.PlaybookCallbacks()
    runner_cb   =callbacks.PlaybookRunnerCallbacks(stats)
    vars={}
    vars['users'] = users
    results = PlayBook(playbook='user.yaml',callbacks=playbook_cb,runner_callbacks=runner_cb,stats=stats,inventory=inventory,extra_vars=vars)
    res = results.run()
    logs = []
    logs.append("finish playbook\n")
    logs.append(str(res))
    return  logs 
開發者ID:strongit,項目名稱:flask-ansible-api-celery,代碼行數:25,代碼來源:flask-celery-server.py

示例4: __init__

# 需要導入模塊: from ansible import inventory [as 別名]
# 或者: from ansible.inventory import Inventory [as 別名]
def __init__(self, resource):
        """
        resource的數據格式是一個列表字典,比如
            {
                "group1": {
                    "hosts": [{"hostname": "10.10.10.10", "port": "22", "username": "test", "password": "mypass"}, ...],
                    "vars": {"var1": value1, "var2": value2, ...}
                }
            }

        如果你隻傳入1個列表,這默認該列表內的所有主機屬於my_group組,比如
            [{"hostname": "10.10.10.10", "port": "22", "username": "test", "password": "mypass"}, ...]
        """
        self.resource = resource
        self.inventory = Inventory(host_list=[])
        self.gen_inventory() 
開發者ID:zsjtoby,項目名稱:DevOpsCloud,代碼行數:18,代碼來源:ansible_api.py

示例5: Playbook

# 需要導入模塊: from ansible import inventory [as 別名]
# 或者: from ansible.inventory import Inventory [as 別名]
def Playbook():
    vars={}
    inventory = Inventory(hostfile)
    stats =  callbacks.AggregateStats()
    playbook_cb =callbacks.PlaybookCallbacks()
    runner_cb   =callbacks.PlaybookRunnerCallbacks(stats)
    hosts=request.args.get('ip')
    task=request.args.get('playbook')
    vars['hosts'] = hosts
    play=task + '.yml'
    results = PlayBook(playbook=play,callbacks=playbook_cb,runner_callbacks=runner_cb,stats=stats,inventory=inventory,extra_vars=vars)
    res = results.run()
    return json.dumps(res,indent=4) 
開發者ID:strongit,項目名稱:flask-ansible-api-celery,代碼行數:15,代碼來源:flask-api.py

示例6: initialize_inventory

# 需要導入模塊: from ansible import inventory [as 別名]
# 或者: from ansible.inventory import Inventory [as 別名]
def initialize_inventory(self):
        log.debug("HostManagerV2.initialize_inventory()")

        self.options['loader'] = DataLoader()
        self.options['variable_manager'] = VariableManager()
        self.options['inventory_manager'] = Inventory(loader=self.options['loader'],
                                                      variable_manager=self.options['variable_manager'],
                                                      host_list=self.options['inventory'])
        self.options['variable_manager'].set_inventory(self.options['inventory_manager']) 
開發者ID:ansible,項目名稱:pytest-ansible,代碼行數:11,代碼來源:v2.py

示例7: initialize_inventory

# 需要導入模塊: from ansible import inventory [as 別名]
# 或者: from ansible.inventory import Inventory [as 別名]
def initialize_inventory(self):
        self.options['inventory_manager'] = Inventory(self.options['inventory'])
        # self.options['inventory_manager'].subset(self.pattern) 
開發者ID:ansible,項目名稱:pytest-ansible,代碼行數:5,代碼來源:v1.py

示例8: get_inventory

# 需要導入模塊: from ansible import inventory [as 別名]
# 或者: from ansible.inventory import Inventory [as 別名]
def get_inventory(inventory_path=None, vault_password_path=None):
    if inventory_path is None:
        try:
            inventory_path = os.path.expanduser(
                config.get('inventory', 'path'))
        except ConfigParser.NoSectionError:
            inventory_path = 'inventory'
    vault_password = get_vault_password(vault_password_path)
    return Inventory(inventory_path, vault_password=vault_password)


# Filesystem Tools 
開發者ID:dellis23,項目名稱:ansible-toolkit,代碼行數:14,代碼來源:utils.py

示例9: __init__

# 需要導入模塊: from ansible import inventory [as 別名]
# 或者: from ansible.inventory import Inventory [as 別名]
def __init__(self, playbook, inventory, run_data=None, verbosity=0, tags=None, skip_tags=None):
        self.run_data = run_data or {}
        self.options = Options()

        self.options.verbosity = verbosity
        self.options.connection = 'local'  # Need a connection type "smart" or "ssh"
        self.options.become = True
        self.options.become_method = 'sudo'
        self.options.become_user = 'root'
        self.options.tags = tags or []
        self.options.skip_tags = skip_tags or []
        # Set global verbosity
        self.display = Display()
        self.display.verbosity = self.options.verbosity
        # Executor appears to have it's own
        # verbosity object/setting as well
        playbook_executor.verbosity = self.options.verbosity

        # Become Pass Needed if not logging in as user root
        passwords = {}

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

        # All the variables from all the various places
        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=inventory)
        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) 
開發者ID:Juniper,項目名稱:contrail-docker,代碼行數:42,代碼來源:runner.py

示例10: execute_action

# 需要導入模塊: from ansible import inventory [as 別名]
# 或者: from ansible.inventory import 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

示例11: run_module

# 需要導入模塊: from ansible import inventory [as 別名]
# 或者: from ansible.inventory import Inventory [as 別名]
def run_module(self, module_name='ping', module_args=None, hosts="all",
                   inventory_file=None, **kwargs):

        if not module_args:
            check_raw = module_name in ('command', 'win_command', 'shell',
                                        'win_shell', 'script', 'raw')
            module_args = parse_kv(constants.DEFAULT_MODULE_ARGS, check_raw)

        conn_pass = None
        if 'conn_pass' in kwargs:
            conn_pass = kwargs['conn_pass']

        become_pass = None
        if 'become_pass' in kwargs:
            become_pass = kwargs['become_pass']

        passwords = {'conn_pass': conn_pass, 'become_pass': become_pass}

        options = self._build_opt_dict(inventory_file, **kwargs)

        variable_manager = vars.VariableManager()
        loader = dataloader.DataLoader()
        variable_manager.extra_vars = options.extra_vars

        ansible_inv = inventory.Inventory(loader=loader,
                                          variable_manager=variable_manager,
                                          host_list=options.inventory)
        variable_manager.set_inventory(ansible_inv)
        ansible_inv.subset(options.subset)

        play_ds = self._play_ds(hosts, module_name, module_args)
        play_obj = play.Play().load(play_ds, variable_manager=variable_manager,
                                    loader=loader)

        try:
            tqm = task_queue_manager.TaskQueueManager(
                inventory=ansible_inv,
                variable_manager=variable_manager,
                loader=loader,
                options=options,
                passwords=passwords,
                stdout_callback='minimal',
                run_additional_callbacks=True
            )

            # There is no public API for adding callbacks, hence we use a
            # private property to add callbacks
            tqm._callback_plugins.extend(self._callbacks)

            result = tqm.run(play_obj)
        finally:
            if tqm:
                tqm.cleanup()
            if loader:
                loader.cleanup_all_tmp_files()

        stats = tqm._stats
        result = self._process_stats(stats)
        return result 
開發者ID:vmware-archive,項目名稱:column,代碼行數:61,代碼來源:api_runner.py

示例12: __init__

# 需要導入模塊: from ansible import inventory [as 別名]
# 或者: from ansible.inventory import Inventory [as 別名]
def __init__(self, playbook, hosts='hosts', options={}, passwords={}, vault_pass=None):

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

        # Set global verbosity
        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()
        # Set vault password
        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:
            # Empty inventory
            self.display.error("Provided hosts list is empty.")
            sys.exit(1)

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

        if len(self.inventory.list_hosts()) == 0:
            # Invalid limit
            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) 
開發者ID:wagoodman,項目名稱:bridgy,代碼行數:58,代碼來源:ansible_utils.py


注:本文中的ansible.inventory.Inventory方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。