def gather_facts(host, inventory=None): if inventory is None: inventory = get_inventory() # Gather facts try: # ... temporary playbook file playbook_file = tempfile.NamedTemporaryFile() playbook_file.write(SETUP_PLAYBOOK.format(host=host)) playbook_file.seek(0) # ... run setup module stats = ansible.callbacks.AggregateStats() # callbacks = ansible.callbacks.PlaybookCallbacks(verbose=VERBOSITY) # runner_callbacks = ansible.callbacks.PlaybookRunnerCallbacks( # stats, verbose=VERBOSITY) playbook = PlayBook( playbook=playbook_file.name, inventory=inventory, callbacks=Callbacks(), runner_callbacks=Callbacks(), stats=stats, ) playbook.run() finally: playbook_file.close() return playbook.SETUP_CACHE
def runPlayBook(path): stats = callbacks.AggregateStats() inven = Inventory(host_list=path["hosts"]); playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY) pb = PlayBook(inventory=inven,playbook=path["playbook"],stats=stats,callbacks=playbook_cb,runner_callbacks=runner_cb,) pb.run()
def aws(phase): #parse args with open("keys/rootkey.csv","r") as keyfile: lines = keyfile.readlines() aws_access_key = lines[0].split('=')[1].strip(' ').rstrip() aws_secret_key = lines[1].split('=')[1].strip(' ').rstrip() os.environ['AWS_ACCESS_KEY_ID']= aws_access_key os.environ['AWS_SECRET_ACCESS_KEY']= aws_secret_key d = deployment() red = redis.StrictRedis(host='localhost', port=6379, db=0) if phase == 0: print "Clean up stale reservations...*****************\n" d.destroy_aws_instance() if phase == 1: d.create_aws_instance() d.create_aws_instance() print "\nCheck AWS instance status...******************" aws_ip = d.get_aws_reservation() while aws_ip == None or len(aws_ip) < 2: print "AWS Instance not ready, retry after 30 sec" time.sleep(30) aws_ip = d.get_aws_reservation() canary = aws_ip[0] production = aws_ip[1] print "AWS Canary Instance =" + canary print "AWS Production Instance =" + production print "Update Redis" red.set('canary',"http://"+canary+":3000") red.set('production', "http://"+production+":3000") red.set('production0', "http://"+production+":3000") red.set('instances',1); print red.get('canary') print red.get('production') print "\nWriting Inventory...**************************" aws_inv_can = "canary ansible_ssh_host="+canary+" ansible_ssh_user=ubuntu ansible_ssh_private_key_file=./keys/devops.pem\n" with open("inventory_canary","w") as f: f.write(aws_inv_can) aws_inv_prod = "production ansible_ssh_host="+production+" ansible_ssh_user=ubuntu ansible_ssh_private_key_file=./keys/devops.pem\n" with open("inventory_production","w") as f: f.write(aws_inv_prod) with open("inventory", "w") as f: f.write(aws_inv_can+"\n") f.write(aws_inv_prod) if phase == 2: os.environ['ANSIBLE_HOST_KEY_CHECKING']="false" utils.VERBOSITY = 0 playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) stats = callbacks.AggregateStats() runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY) inventory = Inventory('inventory') print "\nRun Ansible PlayBook...**********************" pb = PlayBook(playbook='server_play.yml', inventory=inventory, callbacks=playbook_cb, runner_callbacks=runner_cb, stats=stats ) pb.run()
def Test(self,host): playbook = PlayBook(playbook='/Users/ezeng/Development/mesos-poc/vm_booting/playbook.yml', # inventory=Inventory('/Users/ezeng/Development/mesos-poc/vm_booting/ansible/inventory'), host_list=host.split(","), callbacks=playbook_cb, runner_callbacks=runner_cb, stats=stats) playbook.run()
def deploy_service(username, passwd, hosts, extras): ruta = os.path.join(ROLESDIR, 'ansible-role-mailserver/site.yml') pb = PlayBook(playbook=ruta, sudo=True, sudo_pass=passwd, host_list=hosts, remote_user=username, extra_vars=extras, callbacks=playbook_cb, runner_callbacks=runner_cb, stats=stats) pb.run()
def action(self, resource, action): # This would require to put this file to remote and execute it (mostly) ssh_props = find_named_transport(resource, 'ssh') remote_user = ssh_props['user'] private_key_file = ssh_props.get('key') ssh_password = ssh_props.get('password') action_file = os.path.join( resource.db_obj.actions_path, resource.actions[action]) variables = resource.args if 'roles' in variables: self.download_roles(variables['roles']) host = resource.ip() transport = C.DEFAULT_TRANSPORT C.HOST_KEY_CHECKING = False stats = callbacks.AggregateStats() playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) runner_cb = callbacks.PlaybookRunnerCallbacks( stats, verbose=utils.VERBOSITY) opts = dict( playbook=action_file, remote_user=remote_user, host_list=[host], extra_vars=variables, callbacks=playbook_cb, runner_callbacks=runner_cb, stats=stats, transport=transport) if ssh_password: opts['remote_pass'] = ssh_password elif private_key_file: opts['private_key_file'] = private_key_file else: raise Exception("No key and no password given") play = PlayBook(**opts) play.run() summary = stats.summarize(host) if summary.get('unreachable') or summary.get('failures'): raise errors.SolarError( 'Ansible playbook %s failed with next summary %s', action_file, summary)
def configure_hosts(self, reservation_obj, playbook): inven = Inventory(host_list=reservation_obj.keys()) for host in inven.get_hosts(): for key, value in reservation_obj[host.name].items(): host.set_variable(key, value) stats = callbacks.AggregateStats() playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY) pb = PlayBook(inventory=inven, playbook=playbook, stats=stats, callbacks=playbook_cb, runner_callbacks=runner_cb) pb.run()
def run_installer(user_list, package_list, sudo_password): """ Runs the playbook `installer.yml` with the supplied parameters """ # Create the inventory controller = Host(name="localhost") controller.set_variable("users", user_list) controller.set_variable("apt_packages", package_list) local_inventory = Inventory([]) local_inventory.get_group("all").add_host(controller) # Boilerplate for callbacks setup utils.VERBOSITY = 0 # Output callbacks setup output_callbacks = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) # API callbacks setup stats = callbacks.AggregateStats() api_callbacks = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY) provision_playbook = PlayBook( playbook="installer.yml", stats=stats, callbacks=output_callbacks, runner_callbacks=api_callbacks, inventory=local_inventory, transport="local", become_pass=sudo_password, ) playbook_result = provision_playbook.run() return playbook_result
def RunRecepie(inventory, playbook_file): """ Run playbook :param hosts: :return: """ # Boilerplace callbacks for stdout/stderr and log output utils.VERBOSITY = 0 playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) stats = callbacks.AggregateStats() runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY) pb = PlayBook( playbook=playbook_file, inventory=inventory, callbacks=playbook_cb, runner_callbacks=runner_cb, stats=stats, ) results = pb.run() # Ensure on_stats callback is called # for callback modules playbook_cb.on_stats(pb.stats) return results
def install_stuff(ip_list, sshpass, req_list): task_id = str(install_stuff.request.id) db.write_in_progress(req_list, ip_list, task_id) pb_name = helper.write_playbook(req_list) playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) stats = callbacks.AggregateStats() runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY) pb = PlayBook(remote_user='******', remote_pass=sshpass, playbook=pb_name, callbacks=playbook_cb, runner_callbacks=runner_cb, stats=stats, host_list=ip_list, ) results = pb.run() if results[ip_list[:-1]]['unreachable'] != 0: os.remove(pb_name) db.del_in_progress(task_id) raise RuntimeError('df//' + ip_list[:-1] + '//' + '1' + '//fd') if results[ip_list[:-1]]['failures'] != 0: os.remove(pb_name) db.del_in_progress(task_id) raise RuntimeError('df//' + ip_list[:-1] + '//' + '1' + '//fd') os.remove(pb_name) db.del_in_progress(task_id) ans = '//' + ip_list[:-1] + '//0//' return ans
def gather_facts(host, inventory=None, user=None): if inventory is None: inventory = get_inventory() # Gather facts try: # ... temporary playbook file playbook_file = tempfile.NamedTemporaryFile() playbook_file.write(SETUP_PLAYBOOK.format(host=host)) playbook_file.seek(0) # ... run setup module stats = ansible.callbacks.AggregateStats() playbook = PlayBook( playbook=playbook_file.name, inventory=inventory, callbacks=Callbacks(), runner_callbacks=Callbacks(), remote_user=user or C.DEFAULT_REMOTE_USER, stats=stats, ) results = playbook.run() # ... notify the user of failures for host, result in results.iteritems(): if result.get('unreachable') or result.get('failures'): yellow('Unable to gather facts for host "{}"'.format(host)) finally: playbook_file.close() return playbook.SETUP_CACHE
def run_playbook(dir, extra_vars): utils.VERBOSITY = 0 playbook_cb = MyPlaybookCallbacks(verbose=utils.VERBOSITY) stats = callbacks.AggregateStats() runner_cb = MyPlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY) inventory = """ [localhost] localhost ansible_connection=local """ # Create a temporary file and write the template string to it hosts = tempfile.NamedTemporaryFile(delete=False, dir=dir) hosts.write(inventory) hosts.close() pb = PlayBook( playbook=os.path.join(dir, "playbook.yml"), host_list=hosts.name, callbacks=playbook_cb, runner_callbacks=runner_cb, extra_vars=extra_vars, stats=stats ) results = pb.run() # Ensure on_stats callback is called # for callback modules playbook_cb.on_stats(pb.stats) logger().info(results)
def run(self): """Run playbook Runs playbook and collects output to self.results """ stats = PlayBook.run(self) return self.process_results(self.results)
def execute(taskexecution_id): from ansible.playbook import PlayBook from ansible.inventory import Inventory from ansible import callbacks from ansible import utils utils.VERBOSITY = 0 playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) stats = callbacks.AggregateStats() runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY) time.sleep(5) taskexecution = TaskExecution.objects.get(pk=taskexecution_id) taskexecution.start() taskexecution.save() inventory = "[local]\n\ localhost ansible_connection=local\n\ \n\ [tasker]\n\ localhost\n\ \n\ [tasker:vars]\n\ taskexecution_id={}".format(taskexecution_id) hosts = NamedTemporaryFile(delete=False) hosts.write(inventory) hosts.close() pb = PlayBook( playbook='/tmp/main.yml', host_list=hosts.name, # remote_user='******', callbacks=playbook_cb, runner_callbacks=runner_cb, stats=stats, # private_key_file='/path/to/key.pem' ) results = pb.run() playbook_cb.on_stats(pb.stats) os.remove(hosts.name) status = results.get('localhost') if status['failures'] > 0 or status['unreachable'] > 0: taskexecution.failed() taskexecution.save() return False taskexecution.succeed() taskexecution.save() return True
def __run_playbook(self, name): # Boilerplace callbacks for stdout/stderr and log output utils.VERBOSITY = 0 playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) stats = callbacks.AggregateStats() runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY) # load playbook pb = PlayBook( playbook = os.path.dirname(__file__) + '/ansible/' + name, host_list = self.__hosts.name, callbacks=playbook_cb, runner_callbacks=runner_cb, stats=stats ) pb.run() return self.__check_success(pb.stats)
def run(self): pb = PlayBook(playbook=self.playbook, host_list=self.host_list, module_path=self.module_path, callbacks=self.playbook_cb, runner_callbacks=self.runner_cb, stats=self.stats ) results = pb.run() return results print results
def action(self, resource, action): # This would require to put this file to remote and execute it (mostly) log.debug("Ansible playbook is not ported to pluggable transports") action_file = os.path.join( resource.metadata['actions_path'], resource.metadata['actions'][action]) stats = callbacks.AggregateStats() playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY) variables = resource.args_dict() if 'roles' in variables: self.download_roles(variables['roles']) remote_user = variables.get('ssh_user') or C.DEFAULT_REMOTE_USER private_key_file = variables.get('ssh_key') or C.DEFAULT_PRIVATE_KEY_FILE if variables.get('ip'): host = variables['ip'] transport = C.DEFAULT_TRANSPORT else: host = 'localhost' transport = 'local' C.HOST_KEY_CHECKING = False play = PlayBook( playbook=action_file, remote_user=remote_user, host_list = [host], private_key_file=private_key_file, extra_vars=variables, callbacks=playbook_cb, runner_callbacks=runner_cb, stats=stats, transport=transport) play.run() summary = stats.summarize(host) if summary.get('unreachable') or summary.get('failures'): raise errors.SolarError( 'Ansible playbook %s failed with next summary %s', action_file, summary)
def runPlaybook(play): playbook = PlayBook(remote_user='******', remote_pass=passwd, playbook=play, callbacks=playbook_cb, runner_callbacks=runner_cb, stats=stats, host_list='ansible/hosts' ) playoutput = playbook.run() for l in playoutput:print l,playoutput[l]
def db_replication_Install(): playbook = PlayBook(remote_user='******', remote_pass=passwd, playbook='./ansible/play-books/mysql-replication-setup.yml', callbacks=playbook_cb, runner_callbacks=runner_cb, stats=stats, host_list='ansible/hosts' ) playoutput = playbook.run() for l in playoutput:print l,playoutput[l]
def startall_in_one(): playbook = PlayBook(remote_user='******', remote_pass=passwd, playbook='./ansible/play-books/all-in-one.yml', callbacks=playbook_cb, runner_callbacks=runner_cb, stats=stats, host_list='ansible/hosts' ) playoutput = playbook.run() for l in playoutput:print l,playoutput[l]
def management_Install(): playbook = PlayBook(remote_user='******', remote_pass=passwd, playbook='./ansible/play-books/cldstk-mgmt_deploy.yml', callbacks=playbook_cb, runner_callbacks=runner_cb, stats=stats, host_list='ansible/hosts' ) playoutput = playbook.run() for l in playoutput:print l,playoutput[l]
def systemtemplate_Install(): playbook = PlayBook(remote_user='******', remote_pass=passwd, playbook='./ansible/play-books/cldstk-preseed-kvm-systmpl.yml', callbacks=playbook_cb, runner_callbacks=runner_cb, stats=stats, host_list='ansible/hosts' ) playoutput = playbook.run() for l in playoutput:print l,playoutput[l]
def runfileupdates(): playbook = PlayBook(remote_user='******', remote_pass=passwd, playbook='./ansible/play-books/cldstk-files-update.yml', callbacks=playbook_cb, runner_callbacks=runner_cb, stats=stats, host_list='ansible/hosts' ) playoutput = playbook.run() for l in playoutput:print l,playoutput[l]
def run_playbook(self, playbook_file, tags=None): """ Run the playbook_file using created inventory and tags specified :return: """ stats = callbacks.AggregateStats() playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY) pb = PlayBook(playbook=playbook_file, inventory=self.ansible_inventory, stats=stats, callbacks=playbook_cb, runner_callbacks=runner_cb, only_tags=tags) playbook_result = pb.run() return playbook_result
def run_playbook(path, inv_path, pk): inv = inventory.Inventory(inv_path) stats = callbacks.AggregateStats() playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY) pb = PlayBook( playbook=path, inventory=inv, private_key_file=pk, callbacks=playbook_cb, runner_callbacks=runner_cb, stats=stats ) try: pb.run() playbook_cb.on_stats(pb.stats) except errors.AnsibleError, e: display("ERROR: %s" % e, color='red') return 1
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)
def __run_playbook(self, ip, playbook): pb_file = os.path.join('playbooks', playbook) pb = PlayBook( playbook=pb_file, host_list=self.hosts.name, callbacks=self.playbook_cb, runner_callbacks=self.runner_cb, stats=self.stats, extra_vars=self.params ) results = pb.run() self.playbook_cb.on_stats(pb.stats) print(results)
def run_playbook_call_callback(playbook_path, inventory_path, subset, extra_vars, event_callback): callbacks_object = EmitterCallbacks(event_callback) stats = callbacks.AggregateStats() pb = PlayBook( playbook = playbook_path, host_list = inventory_path, callbacks = callbacks_object, runner_callbacks = callbacks_object, stats = stats, extra_vars = extra_vars, subset = subset ) results = pb.run() # TODO: use the result of AggregateStats - must be converted to a dict object callbacks_object.on_complete()
def playbook_api(self,yml_fp): ret = None stats = callbacks.AggregateStats() playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY) pb = PlayBook( playbook=yml_fp, host_list=self.ansible_host_list, stats=stats, callbacks=playbook_cb, runner_callbacks=runner_cb ) ret = pb.run()
def _run(self): stats = callbacks.AggregateStats() playbook_callbacks = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) runner_callbacks = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY) playbook = PlayBook( callbacks=playbook_callbacks, any_errors_fatal=True, host_list=self.host_list, playbook=self.playbook, runner_callbacks=runner_callbacks, stats=stats, ) results = playbook.run() return results
'111.222.333.444' # and the rest of our variables }) # Create a temporary file and write the template string to it hosts = NamedTemporaryFile(delete=False) hosts.write(rendered_inventory) hosts.close() pb = PlayBook( playbook='/home/ec2-user/hack/speeds/mysite/py.yaml', host_list=hosts.name, # Our hosts, the rendered inventory file callbacks=playbook_cb, runner_callbacks=runner_cb, stats=stats, # private_key_file='/path/to/key.pem' ) results = pb.run() # Ensure on_stats callback is called # for callback modules playbook_cb.on_stats(pb.stats) os.remove(hosts.name) print results from ansible.playbook import PlayBook pb = PlayBook(playbook='/home/ec2-user/hack/speeds/mysite/py.yaml') pb.run()
def setup_cluster(self, cluster): """Configures the cluster according to the node_kind to ansible group matching. This method is idempotent and therefore can be called multiple times without corrupting the cluster configuration. :param cluster: cluster to configure :type cluster: :py:class:`elasticluster.cluster.Cluster` :return: True on success, False otherwise. Please note, if nothing has to be configures True is returned :raises: `AnsibleError` if the playbook can not be found or playbook is corrupt """ inventory_path = self._build_inventory(cluster) private_key_file = cluster.user_key_private # update ansible constants ansible_constants.HOST_KEY_CHECKING = False ansible_constants.DEFAULT_PRIVATE_KEY_FILE = private_key_file ansible_constants.DEFAULT_SUDO_USER = self._sudo_user # check paths if not inventory_path: # No inventory file has been created, maybe an # invalid calss has been specified in config file? Or none? # assume it is fine. elasticluster.log.info("No setup required for this cluster.") return True if not os.path.exists(inventory_path): raise AnsibleError("inventory file `%s` could not be found" % inventory_path) # ANTONIO: These should probably be configuration error # instead, and should probably checked inside __init__(). if not os.path.exists(self._playbook_path): raise AnsibleError("playbook `%s` could not be found" % self._playbook_path) if not os.path.isfile(self._playbook_path): raise AnsibleError("the playbook `%s` is not a file" % self._playbook_path) elasticluster.log.debug("Using playbook file %s.", self._playbook_path) stats = ansible.callbacks.AggregateStats() playbook_cb = ElasticlusterPbCallbacks(verbose=0) runner_cb = ansible.callbacks.DefaultRunnerCallbacks() if elasticluster.log.level <= logging.INFO: playbook_cb = ansible.callbacks.PlaybookCallbacks() runner_cb = ansible.callbacks.PlaybookRunnerCallbacks(stats) pb = PlayBook( playbook=self._playbook_path, host_list=inventory_path, callbacks=playbook_cb, runner_callbacks=runner_cb, forks=10, stats=stats, sudo=self._sudo, sudo_user=self._sudo_user, private_key_file=private_key_file, ) try: status = pb.run() except AnsibleError as e: elasticluster.log.error( "could not execute ansible playbooks. message=`%s`", str(e)) return False # Check ansible status. cluster_failures = False for host, hoststatus in status.items(): if hoststatus['unreachable']: elasticluster.log.error( "Host `%s` is unreachable, " "please re-run elasticluster setup", host) cluster_failures = True if hoststatus['failures']: elasticluster.log.error( "Host `%s` had %d failures: please re-run elasticluster " "setup or check the Ansible playbook `%s`" % (host, hoststatus['failures'], self._playbook_path)) cluster_failures = True if not cluster_failures: elasticluster.log.info("Cluster correctly configured.") # ANTONIO: TODO: We should return an object to identify if # the cluster was correctly configured, if we had # temporary errors or permanent errors. return True return False
""" # Render Inventory # Change target machine IP target = ['192.168.122.58'] inv_template = jinja2.Template(inventory) render_inv = inv_template.render({'hosts': target}) # Write Inventory File hosts = NamedTemporaryFile(delete=False) hosts.write(render_inv) hosts.close() # Call Ansible play playobj = PlayBook(playbook='dmidecode.yaml', host_list=hosts.name, remote_user='******', stats=stats, callbacks=playbook_cbck, runner_callbacks=runner_cbck, private_key_file='~/.ssh/id_rsa') playresult = playobj.run() # Remove Temporary Inventory File os.remove(hosts.name) # Print aggregated Results print playresult
def configure(self): """ Executes the ansible playbooks that configure the servers in the stack. Assumes that the root playbook directory is ``./playbooks/`` relative to the stack configuration file. Also sets the ansible *module_path* to be ``./common_modules/`` relative to the stack configuration file. E.g. If the stack configuration file is:: $HOME/bang-stacks/my_web_service.yml then the root playbook directory is:: $HOME/bang-stacks/playbooks/ and the ansible module path is:: $HOME/bang-stacks/common_modules/ """ cfg = self.config bang_config_dir = os.path.abspath(os.path.dirname(cfg.filepath)) playbook_dir = os.path.join(bang_config_dir, 'playbooks') creds = cfg.get(A.DEPLOYER_CREDS, {}) pb_kwargs = { # this allows connection reuse using "ControlPersist": 'transport': 'ssh', 'module_path': os.path.join(bang_config_dir, 'common_modules'), 'remote_pass': creds.get(A.creds.SSH_PASS), # TODO: determine forks # 'forks': options.forks, } # only add the 'remote_user' kwarg if it's in the config, otherwise use # ansible's default behaviour. ssh_user = creds.get(A.creds.SSH_USER) if ssh_user: pb_kwargs['remote_user'] = ssh_user ansible_cfg = cfg.get(A.ANSIBLE, {}) ansible_verbosity = ansible_cfg.get(A.ansible.VERBOSITY, 1) ansible.utils.VERBOSITY = ansible_verbosity for playbook in cfg.get(A.PLAYBOOKS, []): playbook_path = os.path.join(playbook_dir, playbook) # gratuitously stolen from main() in ``ansible-playbook`` stats = callbacks.AggregateStats() playbook_cb = callbacks.PlaybookCallbacks( verbose=ansible_verbosity) runner_cb = callbacks.PlaybookRunnerCallbacks( stats, verbose=ansible_verbosity) vault_password = ansible_cfg.get(A.ansible.VAULT_PASS) extra_kwargs = { 'playbook': playbook_path, # TODO: do we really need new instances of the following # for each playbook? 'callbacks': playbook_cb, 'runner_callbacks': runner_cb, 'stats': stats, # ``host_list`` is used to generate the inventory, but # don't worry, we override the inventory later 'host_list': [], 'vault_password': vault_password, } pb_kwargs.update(extra_kwargs) pb = PlayBook(**pb_kwargs) inventory = BangsibleInventory( copy.deepcopy(self.groups_and_vars.lists), copy.deepcopy(self.groups_and_vars.dicts), vault_password=vault_password) inventory.set_playbook_basedir(playbook_dir) pb.inventory = inventory pb.run() hosts = sorted(pb.stats.processed.keys()) playbook_cb.on_stats(pb.stats) failed = False for h in hosts: hsum = pb.stats.summarize(h) if hsum['failures'] or hsum['unreachable']: failed = True print "%-30s : %s" % (h, hsum) # TODO: sort this out # print "%-30s : %s %s %s %s " % ( # hostcolor(h, hsum), # colorize('ok', hsum['ok'], 'green'), # colorize('changed', hsum['changed'], 'yellow'), # colorize('unreachable', hsum['unreachable'], 'red'), # colorize('failed', hsum['failures'], 'red')) if failed: raise BangError("Server configuration failed!")