コード例 #1
0
    def playbook_run(self, message, args):
        """Run a playbook"""
        if isinstance(args, str) or isinstance(args, unicode):
            arg = args
        elif isinstance(args, list):
            arg = args[0]
        else:
            message.error('参数类型错误')
            return
        message.send('Starting to execute playbook: {}'.format(arg))
        pb_dict = self.all_playbooks[arg]
        stats = callbacks.AggregateStats(),
        runner_cb = callbacks.PlaybookRunnerCallbacks(stats,
                                                      verbose=utils.VERBOSITY)
        if pb_dict['hosts']:
            pb = playbook.PlayBook(
                playbook=pb_dict['path'],
                host_list=pb_dict['hosts'],
                stats=stats,
                callbacks=callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY),
                runner_callbacks=runner_cb)
        else:
            pb = playbook.PlayBook(playbook=pb_dict['path'],
                                   inventory=common.inventory)
        results = pb.run()

        return results
コード例 #2
0
ファイル: ansible_glue.py プロジェクト: invokelabs/platform
def run_ansible_in_python(task):
    stats = callbacks.AggregateStats()
    ## everything between this comment
    ## and the "end" should hopefully not be necessary
    ## after Ansible 1.4.6 or 1.5 is released, since there
    ## will be an implicit sys.executable interpreter for the localhost
    ## host. This will almost certainly need tweaking anyway for dynamic inventory
    ## in ec2. I'm not sure yet how this would work.
    localhost = Host('localhost')
    localhost.set_variable('ansible_python_interpreter', sys.executable)
    all_group = Group('all')
    all_group.add_host(localhost)
    inventory = Inventory(None)
    inventory.add_group(all_group)
    os.putenv('EC2_INI_PATH', 'lib/glue/ec2-external.ini')
    ec2_inventory = InventoryScript(filename='lib/glue/ec2.py')
    inventory.parser = ec2_inventory
    [inventory.add_group(group) for group in ec2_inventory.groups.values()]
    ## end

    pb = playbook.PlayBook(playbook=task.inputs[0].abspath(),
                           inventory=inventory,
                           stats=stats,
                           callbacks=callbacks.PlaybookCallbacks(verbose=3),
                           runner_callbacks=callbacks.PlaybookRunnerCallbacks(stats, verbose=3)
                           )
    pb.run()
コード例 #3
0
    def prepare_runner(self,
                       _playbook_path,
                       options={},
                       tasks=None,
                       _extra_vars={},
                       verbosity=3):
        _OPTIONS = self.__prepare_runner_metadata(options, tasks)
        _vb = _OPTIONS['verbosity']
        _inventory = inventory.Inventory(self.HOSTS_INI_FILE)
        stats = callbacks.AggregateStats()
        playbook_cb = callbacks.PlaybookCallbacks(verbose=_vb)
        runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=_vb)

        runner = playbook.PlayBook(
            playbook=_playbook_path,
            inventory=_inventory,
            extra_vars=_extra_vars,
            private_key_file=self.PRIVATE_KEY,
            #vault_password=vaultpass,
            only_tags=tasks,
            stats=stats,
            callbacks=playbook_cb,
            runner_callbacks=runner_cb)

        return runner
コード例 #4
0
    def process_policy(self, contract_policy, epg, host_ips, new_host_ips):
        host_template = jinja2.Template(HOSTS_TEMPLATE)
        rendered_host_template = host_template.render({
            'all_host_ip':
            host_ips,
            'new_host_ip':
            new_host_ips
        })
        print 'hosts_file:'
        print rendered_host_template
        hosts_file = NamedTemporaryFile(delete=False)
        hosts_file.write(rendered_host_template)
        hosts_file.close()

        # Create the temporary ferm.conf file
        ferm_config = contract_policy.generate_configuration(
            self._endpoint_db[epg])
        ferm_config_template = jinja2.Template(ferm_config)
        rendered_ferm_config_template = ferm_config_template.render(
            {'ferm_conf': 'ferm.conf'})
        print 'ferm.conf:'
        print rendered_ferm_config_template
        ferm_config_file = NamedTemporaryFile(delete=False)
        ferm_config_file.write(rendered_ferm_config_template)
        ferm_config_file.close()

        # Create the temporary yml playbook
        my_playbook_template = jinja2.Template(MY_PLAYBOOK)
        my_rendered_playbook_template = my_playbook_template.render({
            'ferm_conf':
            ferm_config_file.name,
            'user_name':
            SERVER_USERNAME
        })
        my_playbook_file = NamedTemporaryFile(delete=False)
        print 'Playbook:'
        print my_rendered_playbook_template
        my_playbook_file.write(my_rendered_playbook_template)
        my_playbook_file.close()

        # Call the playbook
        pb = playbook.PlayBook(playbook=my_playbook_file.name,
                               host_list=hosts_file.name,
                               stats=self._ansible_stats,
                               callbacks=self._ansible_playbook_cb,
                               runner_callbacks=self._ansible_runner_cb,
                               remote_user=SERVER_USERNAME,
                               remote_pass=SERVER_PASSWORD,
                               become_pass=SERVER_PASSWORD)
        result = pb.run()
        print 'result:', result
        if self._ansible_stats.failures or self._ansible_stats.dark:
            raise RuntimeError('Playbook failed')
コード例 #5
0
ファイル: snippet.py プロジェクト: szabo92/gistable
def run_playbook(playbook_path, hosts_path, key_file):
    stats = callbacks.AggregateStats()
    playbook_cb = callbacks.PlaybookCallbacks(verbose=0)
    runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=0)
    playbook.PlayBook(playbook=playbook_path,
                      host_list=hosts_path,
                      stats=stats,
                      forks=4,
                      callbacks=playbook_cb,
                      runner_callbacks=runner_cb,
                      private_key_file=key_file).run()
    return stats
コード例 #6
0
def run_playbook(path, extra_vars):
    stats = callbacks.AggregateStats()
    playbook_cb = LoggingCallbacks(verbose=3)
    runner_cb = LoggingRunnerCallbacks(stats, verbose=3)

    pb = playbook.PlayBook(playbook=path,
                           stats=stats,
                           callbacks=playbook_cb,
                           runner_callbacks=runner_cb,
                           extra_vars=extra_vars)
    pb.run()
    if stats.failures or stats.dark:
        raise RuntimeError('Playbook {0} failed'.format(path))
    return pb.SETUP_CACHE['localhost']
コード例 #7
0
    def run(self):
        stats = AggregateStats()
        playbook_cb = PlaybookCallbacks(verbose=utils.VERBOSITY)
        runner_cb = PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY)

        pb = playbook.PlayBook(playbook=self.playbook,
                               stats=stats,
                               callbacks=playbook_cb,
                               runner_callbacks=runner_cb,
                               inventory=self.inventory,
                               extra_vars=self.inv_vars,
                               check=False)

        pr = pb.run()

        print json.dumps(pr, sort_keys=True, indent=4, separators=(',', ': '))
コード例 #8
0
def run_ansible():
    vaultpass = "******"
    I = inventory.Inventory("hosts.ini")

    parsed_extra_vars = { 'tags' : ['two'],
                          'date': 2
    }
    stats = callbacks.AggregateStats()
    playbook_cb = callbacks.PlaybookCallbacks(verbose=3)

    runner_cb = callbacks.PlaybookRunnerCallbacks(stats,
                                                  verbose=3)
    pb = playbook.PlayBook(
        playbook='sample_playbook.yaml',
        inventory=I,
        extra_vars=parsed_extra_vars,
        #private_key_file="/path/to/key.pem",
        #vault_password=vaultpass,
        stats=stats,
        callbacks=playbook_cb,
        runner_callbacks=runner_cb
    )
    pb.run()
    
    hosts = sorted(pb.stats.processed.keys())
    
    failed_hosts = []
    unreachable_hosts = []
    for h in hosts:
        t = pb.stats.summarize(h)
        if t['failures'] > 0:
            failed_hosts.append(h)
        if t['unreachable'] > 0:
            unreachable_hosts.append(h)

    print("failed hosts: ", failed_hosts)
    print("unreachable hosts: ", unreachable_hosts)
    
    retries = failed_hosts + unreachable_hosts
    print("retries:", retries)
    if len(retries) > 0:
        return 1
    return 0
コード例 #9
0
def run_playbook(path, extra_vars):

    stats = callbacks.AggregateStats()
    playbook_cb = LoggingCallbacks(verbose=3)
    runner_cb = LoggingRunnerCallbacks(stats, verbose=3)

    inventory = ansible.inventory.Inventory("/code/hosts")

    pb = playbook.PlayBook(
        playbook=path,
        stats=stats,
        callbacks=playbook_cb,
        runner_callbacks=runner_cb,
        inventory=inventory,
        extra_vars=extra_vars,
        # private_key_file='/code/key'
    )

    pr = pb.run()

    #if stats.failures or stats.dark:
    #    raise RuntimeError('Playbook {0} failed'.format(path))

    return runner_cb.res  # pr #pb.SETUP_CACHE['127.0.0.1']
コード例 #10
0
inventory = inventory.Inventory(INVENTORY_FILE)
inventory.subset(ANSIBLE_HOSTS)

inventory.set_playbook_basedir(os.path.dirname(PLAYBOOK))
hosts = inventory.list_hosts(ANSIBLE_HOSTS)

if len(hosts) == 0:
    raise Exception(
        'Could not find any host to match "%s" in the inventory "%s" file' %
        (ANSIBLE_HOSTS, INVENTORY_FILE))

stream = open(CONFIG_RECIPES_FILE, 'r')
configurations = yaml.load(stream)

for recipe in configurations:
    print recipe['only_tags']

    dictionary = dict(inventory=inventory,
                      playbook=PLAYBOOK,
                      callbacks=playbook_cb,
                      runner_callbacks=runner_cb,
                      stats=stats,
                      check=False)

    dictionary.update(recipe)

    pb = playbook.PlayBook(**dictionary)
    results = pb.run()
    print results