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


Python Playbook.load方法代码示例

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


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

示例1: test_playbook_executor__get_serialized_batches

# 需要导入模块: from ansible.playbook import Playbook [as 别名]
# 或者: from ansible.playbook.Playbook import load [as 别名]
    def test_playbook_executor__get_serialized_batches(self):
        fake_loader = DictDataLoader({
            'no_serial.yml': '''
            - hosts: all
              gather_facts: no
              tasks:
              - debug: var=inventory_hostname
            ''',
            'serial_int.yml': '''
            - hosts: all
              gather_facts: no
              serial: 2
              tasks:
              - debug: var=inventory_hostname
            ''',
            'serial_pct.yml': '''
            - hosts: all
              gather_facts: no
              serial: 20%
              tasks:
              - debug: var=inventory_hostname
            ''',
        })

        mock_inventory = MagicMock()
        mock_var_manager = MagicMock()

        # fake out options to use the syntax CLI switch, which will ensure
        # the PlaybookExecutor doesn't create a TaskQueueManager
        mock_options = MagicMock()
        mock_options.syntax.value = True

        pbe = PlaybookExecutor(
            playbooks=['no_serial.yml', 'serial_int.yml', 'serial_pct.yml'],
            inventory=mock_inventory,
            variable_manager=mock_var_manager,
            loader=fake_loader,
            options=mock_options,
            passwords=[],
        )

        playbook = Playbook.load(pbe._playbooks[0], variable_manager=mock_var_manager, loader=fake_loader)
        play = playbook.get_plays()[0]
        mock_inventory.get_hosts.return_value = ['host0','host1','host2','host3','host4','host5','host6','host7','host8','host9']
        self.assertEqual(pbe._get_serialized_batches(play), [['host0','host1','host2','host3','host4','host5','host6','host7','host8','host9']])

        playbook = Playbook.load(pbe._playbooks[1], variable_manager=mock_var_manager, loader=fake_loader)
        play = playbook.get_plays()[0]
        mock_inventory.get_hosts.return_value = ['host0','host1','host2','host3','host4','host5','host6','host7','host8','host9']
        self.assertEqual(pbe._get_serialized_batches(play), [['host0','host1'],['host2','host3'],['host4','host5'],['host6','host7'],['host8','host9']])

        playbook = Playbook.load(pbe._playbooks[2], variable_manager=mock_var_manager, loader=fake_loader)
        play = playbook.get_plays()[0]
        mock_inventory.get_hosts.return_value = ['host0','host1','host2','host3','host4','host5','host6','host7','host8','host9']
        self.assertEqual(pbe._get_serialized_batches(play), [['host0','host1'],['host2','host3'],['host4','host5'],['host6','host7'],['host8','host9']])
开发者ID:dyim42,项目名称:dfw-meetup-20160312,代码行数:57,代码来源:test_playbook_executor.py

示例2: create_playbook

# 需要导入模块: from ansible.playbook import Playbook [as 别名]
# 或者: from ansible.playbook.Playbook import load [as 别名]
def create_playbook(playbook_path):
    """
    Load the given playbook and return the ansible playbook.

    :param playbook_path: Path to the playbook file.
    :type playbook_path: :class:`str`
    :returns: The loaded ansible playbook.
    :rtype: :class:`ansible.playbook.Playbook`
    """
    try:
        playbook = Playbook.load(
            playbook_path,
            loader=LOADER,
            variable_manager=VARIABLE_MANAGER,
        )

        scrape_playbook(playbook)
        return playbook
    except Exception as error:  # pylint: disable=broad-except
        logging.exception(
            "Unexpected error scrapping playbook %r: %r",
            playbook_path, error
        )

        raise argparse.ArgumentTypeError(error)
开发者ID:jenmud,项目名称:ansible-graph,代码行数:27,代码来源:__init__.py

示例3: test_basic_playbook

# 需要导入模块: from ansible.playbook import Playbook [as 别名]
# 或者: from ansible.playbook.Playbook import load [as 别名]
 def test_basic_playbook(self):
     fake_loader = DictDataLoader({
         "test_file.yml":"""
         - hosts: all
         """,
     })
     p = Playbook.load("test_file.yml", loader=fake_loader)
     plays = p.get_plays()
开发者ID:victron,项目名称:paramiko_ssh-i,代码行数:10,代码来源:test_playbook.py

示例4: test_play_iterator

# 需要导入模块: from ansible.playbook import Playbook [as 别名]
# 或者: from ansible.playbook.Playbook import load [as 别名]
    def test_play_iterator(self):
        fake_loader = DictDataLoader({
            "test_play.yml": """
            - hosts: all
              gather_facts: false
              roles:
              - test_role
              pre_tasks:
              - debug: msg="this is a pre_task"
              tasks:
              - debug: msg="this is a regular task"
              post_tasks:
              - debug: msg="this is a post_task"
            """,
            '/etc/ansible/roles/test_role/tasks/main.yml': """
            - debug: msg="this is a role task"
            """,
        })

        p = Playbook.load('test_play.yml', loader=fake_loader)

        hosts = []
        for i in range(0, 10):
            host  = MagicMock()
            host.get_name.return_value = 'host%02d' % i
            hosts.append(host)

        inventory = MagicMock()
        inventory.get_hosts.return_value = hosts
        inventory.filter_hosts.return_value = hosts

        connection_info = ConnectionInformation(play=p._entries[0])

        itr = PlayIterator(
            inventory=inventory,
            play=p._entries[0],
            connection_info=connection_info,
            all_vars=dict(),
        )

        (host_state, task) = itr.get_next_task_for_host(hosts[0])
        print(task)
        self.assertIsNotNone(task)
        (host_state, task) = itr.get_next_task_for_host(hosts[0])
        print(task)
        self.assertIsNotNone(task)
        (host_state, task) = itr.get_next_task_for_host(hosts[0])
        print(task)
        self.assertIsNotNone(task)
        (host_state, task) = itr.get_next_task_for_host(hosts[0])
        print(task)
        self.assertIsNotNone(task)
        (host_state, task) = itr.get_next_task_for_host(hosts[0])
        print(task)
        self.assertIsNone(task)
开发者ID:ferhaty,项目名称:ansible,代码行数:57,代码来源:test_play_iterator.py

示例5: run

# 需要导入模块: from ansible.playbook import Playbook [as 别名]
# 或者: from ansible.playbook.Playbook import load [as 别名]
    def run(self):

        '''
        Run the given playbook, based on the settings in the play which
        may limit the runs to serialized groups, etc.
        '''

        signal.signal(signal.SIGINT, self._cleanup)

        result = 0
        try:
            for playbook_path in self._playbooks:
                pb = Playbook.load(playbook_path, variable_manager=self._variable_manager, loader=self._loader)
        
                # FIXME: playbook entries are just plays, so we should rename them
                for play in pb.get_entries():
                    self._inventory.remove_restriction()

                    # Create a temporary copy of the play here, so we can run post_validate
                    # on it without the templating changes affecting the original object.
                    all_vars = self._variable_manager.get_vars(loader=self._loader, play=play)
                    new_play = play.copy()
                    new_play.post_validate(all_vars, fail_on_undefined=False)

                    for batch in self._get_serialized_batches(new_play):
                        if len(batch) == 0:
                            self._tqm._callback.playbook_on_play_start(new_play.name)
                            self._tqm._callback.playbook_on_no_hosts_matched()
                            result = 0
                            break
                        # restrict the inventory to the hosts in the serialized batch
                        self._inventory.restrict_to_hosts(batch)
                        # and run it...
                        result = self._tqm.run(play=play)
                        if result != 0:
                            break

                    if result != 0:
                        # FIXME: do something here, to signify the playbook execution failed
                        self._cleanup()
                        return result
        except:
            self._cleanup()
            raise

        self._cleanup()
        return result
开发者ID:dataxu,项目名称:ansible,代码行数:49,代码来源:playbook_executor.py

示例6: test_playbook_iterator

# 需要导入模块: from ansible.playbook import Playbook [as 别名]
# 或者: from ansible.playbook.Playbook import load [as 别名]
    def test_playbook_iterator(self):
        fake_loader = DictDataLoader({
            "test_play.yml": """
            - hosts: all
              roles:
              - test_role
              pre_tasks:
              - debug: msg="this is a pre_task"
              tasks:
              - debug: msg="this is a regular task"
              post_tasks:
              - debug: msg="this is a post_task"
            """,
            '/etc/ansible/roles/test_role/tasks/main.yml': """
            - debug: msg="this is a role task"
            """,
        })

        p = Playbook.load('test_play.yml', loader=fake_loader)

        hosts = []
        for i in range(0, 10):
            host  = MagicMock()
            host.get_name.return_value = 'host%02d' % i
            hosts.append(host)

        inventory = MagicMock()
        inventory.get_hosts.return_value = hosts

        itr = PlaybookIterator(inventory, None, p)
        task = itr.get_next_task_for_host(hosts[0])
        print(task)
        self.assertIsNotNone(task)
        task = itr.get_next_task_for_host(hosts[0])
        print(task)
        self.assertIsNotNone(task)
        task = itr.get_next_task_for_host(hosts[0])
        print(task)
        self.assertIsNotNone(task)
        task = itr.get_next_task_for_host(hosts[0])
        print(task)
        self.assertIsNotNone(task)
        task = itr.get_next_task_for_host(hosts[0])
        print(task)
        self.assertIsNone(task)
开发者ID:conlini,项目名称:frozen-ansible,代码行数:47,代码来源:test_playbook_iterator.py

示例7: run

# 需要导入模块: from ansible.playbook import Playbook [as 别名]
# 或者: from ansible.playbook.Playbook import load [as 别名]
    def run(self, playbook):
        pb = Playbook.load(playbook, variable_manager=self.variable_manager, loader=self.loader)
        # only support one playbook.yml
        play = pb.get_plays()[0]

        tqm = None
        try:
            tqm = TaskQueueManager(
                inventory=self.inventory,
                variable_manager=self.variable_manager,
                loader=self.loader,
                options=self.options,
                passwords={'conn_pass': None, 'become_pass': None},
                stdout_callback=self.callback,
            )
            return tqm.run(play), self.callback.result
        finally:
            if tqm is not None:
                tqm.cleanup()
开发者ID:nxintech,项目名称:Charlie,代码行数:21,代码来源:playbook_api_new.py

示例8: build_plays

# 需要导入模块: from ansible.playbook import Playbook [as 别名]
# 或者: from ansible.playbook.Playbook import load [as 别名]
def build_plays(loader, variable_manager, playbook_path, plays=[], hosts=[]):
    playbook = Playbook.load(playbook_path, variable_manager, loader)
    plays = []
    
    for play in playbook.get_plays():
        if play.get_name() in plays:
            plays.append(play)
            continue
        
        if play._ds['hosts'] in hosts:
            plays.append(play)
            continue

        for piece in play._ds['hosts']:
            if piece in hosts:
                plays.append(play)
                break

    return plays
开发者ID:vmindru,项目名称:terraform-provisioner-ansible,代码行数:21,代码来源:ansible-local.py

示例9: _execute_playbook

# 需要导入模块: from ansible.playbook import Playbook [as 别名]
# 或者: from ansible.playbook.Playbook import load [as 别名]
def _execute_playbook(playbook_name):
    """
    Execute a playbook stored in the *share_dir*.
    """
    install_dir = os.path.dirname(os.path.dirname(sys.executable))
    share_dir = os.path.join(install_dir, 'share', 'dws')
    playbook_path = os.path.join(share_dir, 'playbooks', playbook_name)
    if not os.path.exists(playbook_path):
        # When running directly from within src_dir.
        share_dir = os.path.join(install_dir, 'share')
        playbook_path = os.path.join(share_dir, 'playbooks', playbook_name)
    sysconf_dir = os.path.join(install_dir, 'etc')
    Options = namedtuple('Options', ['connection', 'module_path', 'forks',
        'become', 'become_method', 'become_user', 'check'])
    options = Options(connection='local',
        module_path=os.path.dirname(tero.__file__), forks=100, become=None,
        become_method=None, become_user=None, check=False)
    passwords = dict(vault_pass='secret')
    loader = DataLoader()
    variable_manager = VariableManager()
    inventory = Inventory(loader=loader, variable_manager=variable_manager,
        host_list=os.path.join(sysconf_dir, 'ansible', 'hosts'))
    variable_manager.set_inventory(inventory)
    playbook = Playbook.load(playbook_path,
        variable_manager=variable_manager, loader=loader)
    tqm = None
    try:
        tqm = TaskQueueManager(
            inventory=inventory,
            variable_manager=variable_manager,
            loader=loader,
            options=options,
            passwords=passwords)
        for play in playbook.get_plays():
            result = tqm.run(play)
    finally:
        if tqm is not None:
            tqm.cleanup()
开发者ID:djaodjin,项目名称:drop,代码行数:40,代码来源:duploades.py

示例10: DataLoader

# 需要导入模块: from ansible.playbook import Playbook [as 别名]
# 或者: from ansible.playbook.Playbook import load [as 别名]
# Object supplying methods to load JSON or YAML from file or string, into a Python data structure.
loader = DataLoader()

# https://github.com/ansible/ansible/blob/devel/lib/ansible/inventory/__init__.py
#
# Builds the inventory as a data structure (including groups), object also caches host and group vars.
# Loader supplies JSON/YAML parsing methods, variable_manager allows object to copy (cache) vars data
inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list='localhost')

# Here we simply copy back the inventory data into the central variable_manager.
variable_manager.set_inventory(inventory)

# https://github.com/ansible/ansible/blob/devel/lib/ansible/playbook/__init__.py
#
# We use the Playbook object to load and then create Play objects from YAML files.  Playbook
# will load and parse the YAML data into the Playbook.entries[] list.
# Playbook.load() is a static method that calls Playbook.__init__
playbook = Playbook.load("test/site.yml", variable_manager, loader)

# Now we have the playbook loaded we can loop through the plays.  A play is a list of roles
# and/or tasks/handler blocks to execute on a set of hosts.
# see definition: https://github.com/ansible/ansible/blob/devel/lib/ansible/playbook/play.py
for play in playbook.get_plays():
    for block in play.compile():
        if block.has_tasks():
            for task in block.block:
                if task._role in play.get_roles():
                    changed = str(task._get_parent_attribute('changed_when'))
                    failed = str(task._get_parent_attribute('failed_when'))
                    print("PLAY: %s, ROLE: %s, %s, changed_when: %s, failed_when: %s" % (play.get_name(), task._role, task, changed, failed))
开发者ID:thisdougb,项目名称:ansible-play-graphing,代码行数:32,代码来源:list_ansible_tasks.py

示例11: test_play_iterator

# 需要导入模块: from ansible.playbook import Playbook [as 别名]
# 或者: from ansible.playbook.Playbook import load [as 别名]
    def test_play_iterator(self):
        fake_loader = DictDataLoader({
            "test_play.yml": """
            - hosts: all
              gather_facts: false
              roles:
              - test_role
              pre_tasks:
              - debug: msg="this is a pre_task"
              tasks:
              - debug: msg="this is a regular task"
              post_tasks:
              - debug: msg="this is a post_task"
            """,
            '/etc/ansible/roles/test_role/tasks/main.yml': """
            - debug: msg="this is a role task"
            """,
        })

        p = Playbook.load('test_play.yml', loader=fake_loader)

        hosts = []
        for i in range(0, 10):
            host  = MagicMock()
            host.get_name.return_value = 'host%02d' % i
            hosts.append(host)

        inventory = MagicMock()
        inventory.get_hosts.return_value = hosts
        inventory.filter_hosts.return_value = hosts

        mock_var_manager = MagicMock()
        mock_var_manager._fact_cache = dict()

        play_context = PlayContext(play=p._entries[0])

        itr = PlayIterator(
            inventory=inventory,
            play=p._entries[0],
            play_context=play_context,
            variable_manager=mock_var_manager,
            all_vars=dict(),
        )

        # pre task
        (host_state, task) = itr.get_next_task_for_host(hosts[0])
        self.assertIsNotNone(task)
        self.assertEqual(task.action, 'debug')
        # implicit meta: flush_handlers
        (host_state, task) = itr.get_next_task_for_host(hosts[0])
        self.assertIsNotNone(task)
        self.assertEqual(task.action, 'meta')
        # role task
        (host_state, task) = itr.get_next_task_for_host(hosts[0])
        self.assertIsNotNone(task)
        self.assertEqual(task.action, 'debug')
        self.assertIsNotNone(task._role)
        # regular play task
        (host_state, task) = itr.get_next_task_for_host(hosts[0])
        self.assertIsNotNone(task)
        self.assertEqual(task.action, 'debug')
        self.assertIsNone(task._role)
        # implicit meta: flush_handlers
        (host_state, task) = itr.get_next_task_for_host(hosts[0])
        self.assertIsNotNone(task)
        self.assertEqual(task.action, 'meta')
        # post task
        (host_state, task) = itr.get_next_task_for_host(hosts[0])
        self.assertIsNotNone(task)
        self.assertEqual(task.action, 'debug')
        # implicit meta: flush_handlers
        (host_state, task) = itr.get_next_task_for_host(hosts[0])
        self.assertIsNotNone(task)
        self.assertEqual(task.action, 'meta')
        # end of iteration
        (host_state, task) = itr.get_next_task_for_host(hosts[0])
        self.assertIsNone(task)
开发者ID:thebeefcake,项目名称:masterless,代码行数:79,代码来源:test_play_iterator.py

示例12: test_play_iterator

# 需要导入模块: from ansible.playbook import Playbook [as 别名]
# 或者: from ansible.playbook.Playbook import load [as 别名]
    def test_play_iterator(self):
        # import epdb; epdb.st()
        fake_loader = DictDataLoader({
            "test_play.yml": """
            - hosts: all
              gather_facts: false
              roles:
              - test_role
              pre_tasks:
              - debug: msg="this is a pre_task"
              tasks:
              - debug: msg="this is a regular task"
              - block:
                - debug: msg="this is a block task"
                - block:
                  - debug: msg="this is a sub-block in a block"
                rescue:
                - debug: msg="this is a rescue task"
                - block:
                  - debug: msg="this is a sub-block in a rescue"
                always:
                - debug: msg="this is an always task"
                - block:
                  - debug: msg="this is a sub-block in an always"
              post_tasks:
              - debug: msg="this is a post_task"
            """,
            '/etc/ansible/roles/test_role/tasks/main.yml': """
            - name: role task
              debug: msg="this is a role task"
            - block:
              - name: role block task
                debug: msg="inside block in role"
              always:
              - name: role always task
                debug: msg="always task in block in role"
            - include: foo.yml
            - name: role task after include
              debug: msg="after include in role"
            - block:
              - name: starting role nested block 1
                debug:
              - block:
                - name: role nested block 1 task 1
                  debug:
                - name: role nested block 1 task 2
                  debug:
                - name: role nested block 1 task 3
                  debug:
              - name: end of role nested block 1
                debug:
              - name: starting role nested block 2
                debug:
              - block:
                - name: role nested block 2 task 1
                  debug:
                - name: role nested block 2 task 2
                  debug:
                - name: role nested block 2 task 3
                  debug:
              - name: end of role nested block 2
                debug:
            """,
            '/etc/ansible/roles/test_role/tasks/foo.yml': """
            - name: role included task
              debug: msg="this is task in an include from a role"
            """
        })

        mock_var_manager = MagicMock()
        mock_var_manager._fact_cache = dict()
        mock_var_manager.get_vars.return_value = dict()

        p = Playbook.load('test_play.yml', loader=fake_loader, variable_manager=mock_var_manager)

        hosts = []
        for i in range(0, 10):
            host = MagicMock()
            host.name = host.get_name.return_value = 'host%02d' % i
            hosts.append(host)

        mock_var_manager._fact_cache['host00'] = dict()

        inventory = MagicMock()
        inventory.get_hosts.return_value = hosts
        inventory.filter_hosts.return_value = hosts

        play_context = PlayContext(play=p._entries[0])

        itr = PlayIterator(
            inventory=inventory,
            play=p._entries[0],
            play_context=play_context,
            variable_manager=mock_var_manager,
            all_vars=dict(),
        )

        # pre task
        (host_state, task) = itr.get_next_task_for_host(hosts[0])
        self.assertIsNotNone(task)
#.........这里部分代码省略.........
开发者ID:awiddersheim,项目名称:ansible,代码行数:103,代码来源:test_play_iterator.py

示例13: test_play_iterator_add_tasks

# 需要导入模块: from ansible.playbook import Playbook [as 别名]
# 或者: from ansible.playbook.Playbook import load [as 别名]
    def test_play_iterator_add_tasks(self):
        fake_loader = DictDataLoader({
            'test_play.yml': """
            - hosts: all
              gather_facts: no
              tasks:
              - debug: msg="dummy task"
            """,
        })

        mock_var_manager = MagicMock()
        mock_var_manager._fact_cache = dict()
        mock_var_manager.get_vars.return_value = dict()

        p = Playbook.load('test_play.yml', loader=fake_loader, variable_manager=mock_var_manager)

        hosts = []
        for i in range(0, 10):
            host = MagicMock()
            host.name = host.get_name.return_value = 'host%02d' % i
            hosts.append(host)

        inventory = MagicMock()
        inventory.get_hosts.return_value = hosts
        inventory.filter_hosts.return_value = hosts

        play_context = PlayContext(play=p._entries[0])

        itr = PlayIterator(
            inventory=inventory,
            play=p._entries[0],
            play_context=play_context,
            variable_manager=mock_var_manager,
            all_vars=dict(),
        )

        # test the high-level add_tasks() method
        s = HostState(blocks=[0,1,2])
        itr._insert_tasks_into_state = MagicMock(return_value=s)
        itr.add_tasks(hosts[0], [3,4,5])
        self.assertEqual(itr._host_states[hosts[0].name], s)

        # now actually test the lower-level method that does the work
        itr = PlayIterator(
            inventory=inventory,
            play=p._entries[0],
            play_context=play_context,
            variable_manager=mock_var_manager,
            all_vars=dict(),
        )

        # iterate past first task
        _, task = itr.get_next_task_for_host(hosts[0])
        while(task and task.action != 'debug'):
            _, task = itr.get_next_task_for_host(hosts[0])

        if task is None:
            raise Exception("iterated past end of play while looking for place to insert tasks")

        # get the current host state and copy it so we can mutate it
        s = itr.get_host_state(hosts[0])
        s_copy = s.copy()

        # assert with an empty task list, or if we're in a failed state, we simply return the state as-is
        res_state = itr._insert_tasks_into_state(s_copy, task_list=[])
        self.assertEqual(res_state, s_copy)

        s_copy.fail_state = itr.FAILED_TASKS
        res_state = itr._insert_tasks_into_state(s_copy, task_list=[MagicMock()])
        self.assertEqual(res_state, s_copy)

        # but if we've failed with a rescue/always block
        mock_task = MagicMock()
        s_copy.run_state = itr.ITERATING_RESCUE
        res_state = itr._insert_tasks_into_state(s_copy, task_list=[mock_task])
        self.assertEqual(res_state, s_copy)
        self.assertIn(mock_task, res_state._blocks[res_state.cur_block].rescue)
        itr._host_states[hosts[0].name] = res_state
        (next_state, next_task) = itr.get_next_task_for_host(hosts[0], peek=True)
        self.assertEqual(next_task, mock_task)
        itr._host_states[hosts[0].name] = s

        # test a regular insertion
        s_copy = s.copy()
        res_state = itr._insert_tasks_into_state(s_copy, task_list=[MagicMock()])
开发者ID:LukeInkster,项目名称:PythonCorpus,代码行数:87,代码来源:test_play_iterator.py

示例14: run

# 需要导入模块: from ansible.playbook import Playbook [as 别名]
# 或者: from ansible.playbook.Playbook import load [as 别名]
    def run(self):

        '''
        Run the given playbook, based on the settings in the play which
        may limit the runs to serialized groups, etc.
        '''
        result = 0
        try:
            for playbook_path in self._playbooks:
                pb = Playbook.load(playbook_path, variable_manager=self._variable_manager, loader=self._loader)
                self._inventory.set_playbook_basedir(os.path.dirname(playbook_path))

                i = 1

                # make sure the tqm has callbacks loaded
                self._tqm.load_callbacks()
                self._tqm.send_callback('v2_playbook_on_start', pb)

                for play in pb.get_plays():
                    if play._included_path is not None:
                        self._loader.set_basedir(play._included_path)
                    else:
                        self._loader.set_basedir(pb._basedir)

                    # clear any filters which may have been applied to the inventory
                    self._inventory.remove_restriction()

                    # Create a temporary copy of the play here, so we can run post_validate
                    # on it without the templating changes affecting the original object.
                    all_vars = self._variable_manager.get_vars(loader=self._loader, play=play)
                    templar = Templar(loader=self._loader, variables=all_vars)
                    new_play = play.copy()
                    new_play.post_validate(templar)


                    self._tqm._unreachable_hosts.update(self._unreachable_hosts)

                    # we are actually running plays
                    for batch in self._get_serialized_batches(new_play):
                        if len(batch) == 0:
                            self._tqm.send_callback('v2_playbook_on_play_start', new_play)
                            self._tqm.send_callback('v2_playbook_on_no_hosts_matched')
                            break
                        # restrict the inventory to the hosts in the serialized batch
                        self._inventory.restrict_to_hosts(batch)
                        # and run it...
                        result = self._tqm.run(play=play)

                        # check the number of failures here, to see if they're above the maximum
                        # failure percentage allowed, or if any errors are fatal. If either of those
                        # conditions are met, we break out, otherwise we only break out if the entire
                        # batch failed
                        failed_hosts_count = len(self._tqm._failed_hosts) + len(self._tqm._unreachable_hosts)
                        if new_play.any_errors_fatal and failed_hosts_count > 0:
                            break
                        elif new_play.max_fail_percentage is not None and \
                           int((new_play.max_fail_percentage)/100.0 * len(batch)) > int((len(batch) - failed_hosts_count) / len(batch) * 100.0):
                            break
                        elif len(batch) == failed_hosts_count:
                            break

                        # clear the failed hosts dictionaires in the TQM for the next batch
                        self._unreachable_hosts.update(self._tqm._unreachable_hosts)
                        self._tqm.clear_failed_hosts()

                    # if the last result wasn't zero or 3 (some hosts were unreachable),
                    # break out of the serial batch loop
                    if result not in (0, 3):
                        break

                    i = i + 1 # per play

                self._tqm.send_callback('v2_playbook_on_stats', self._tqm._stats)

                # if the last result wasn't zero, break out of the playbook file name loop
                if result != 0:
                    break

        finally:
            if self._tqm is not None:
                self._cleanup()

        return result
开发者ID:lxhiguera,项目名称:im,代码行数:85,代码来源:ansible_executor_v2.py

示例15: test_get_serialized_batches

# 需要导入模块: from ansible.playbook import Playbook [as 别名]
# 或者: from ansible.playbook.Playbook import load [as 别名]
    def test_get_serialized_batches(self):
        fake_loader = DictDataLoader({
            'no_serial.yml': '''
            - hosts: all
              gather_facts: no
              tasks:
              - debug: var=inventory_hostname
            ''',
            'serial_int.yml': '''
            - hosts: all
              gather_facts: no
              serial: 2
              tasks:
              - debug: var=inventory_hostname
            ''',
            'serial_pct.yml': '''
            - hosts: all
              gather_facts: no
              serial: 20%
              tasks:
              - debug: var=inventory_hostname
            ''',
            'serial_list.yml': '''
            - hosts: all
              gather_facts: no
              serial: [1, 2, 3]
              tasks:
              - debug: var=inventory_hostname
            ''',
            'serial_list_mixed.yml': '''
            - hosts: all
              gather_facts: no
              serial: [1, "20%", -1]
              tasks:
              - debug: var=inventory_hostname
            ''',
        })

        mock_inventory = MagicMock()
        mock_var_manager = MagicMock()

        # fake out options to use the syntax CLI switch, which will ensure
        # the PlaybookExecutor doesn't create a TaskQueueManager
        mock_options = MagicMock()
        mock_options.syntax.value = True

        templar = Templar(loader=fake_loader)

        pbe = PlaybookExecutor(
            playbooks=['no_serial.yml', 'serial_int.yml', 'serial_pct.yml', 'serial_list.yml', 'serial_list_mixed.yml'],
            inventory=mock_inventory,
            variable_manager=mock_var_manager,
            loader=fake_loader,
            options=mock_options,
            passwords=[],
        )

        playbook = Playbook.load(pbe._playbooks[0], variable_manager=mock_var_manager, loader=fake_loader)
        play = playbook.get_plays()[0]
        play.post_validate(templar)
        mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']
        self.assertEqual(pbe._get_serialized_batches(play), [['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']])

        playbook = Playbook.load(pbe._playbooks[1], variable_manager=mock_var_manager, loader=fake_loader)
        play = playbook.get_plays()[0]
        play.post_validate(templar)
        mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']
        self.assertEqual(
            pbe._get_serialized_batches(play),
            [['host0', 'host1'], ['host2', 'host3'], ['host4', 'host5'], ['host6', 'host7'], ['host8', 'host9']]
        )

        playbook = Playbook.load(pbe._playbooks[2], variable_manager=mock_var_manager, loader=fake_loader)
        play = playbook.get_plays()[0]
        play.post_validate(templar)
        mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']
        self.assertEqual(
            pbe._get_serialized_batches(play),
            [['host0', 'host1'], ['host2', 'host3'], ['host4', 'host5'], ['host6', 'host7'], ['host8', 'host9']]
        )

        playbook = Playbook.load(pbe._playbooks[3], variable_manager=mock_var_manager, loader=fake_loader)
        play = playbook.get_plays()[0]
        play.post_validate(templar)
        mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']
        self.assertEqual(
            pbe._get_serialized_batches(play),
            [['host0'], ['host1', 'host2'], ['host3', 'host4', 'host5'], ['host6', 'host7', 'host8'], ['host9']]
        )

        playbook = Playbook.load(pbe._playbooks[4], variable_manager=mock_var_manager, loader=fake_loader)
        play = playbook.get_plays()[0]
        play.post_validate(templar)
        mock_inventory.get_hosts.return_value = ['host0', 'host1', 'host2', 'host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']
        self.assertEqual(pbe._get_serialized_batches(play), [['host0'], ['host1', 'host2'], ['host3', 'host4', 'host5', 'host6', 'host7', 'host8', 'host9']])

        # Test when serial percent is under 1.0
        playbook = Playbook.load(pbe._playbooks[2], variable_manager=mock_var_manager, loader=fake_loader)
        play = playbook.get_plays()[0]
        play.post_validate(templar)
#.........这里部分代码省略.........
开发者ID:awiddersheim,项目名称:ansible,代码行数:103,代码来源:test_playbook_executor.py


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