def find_host_in_inventory(base, host_name): loader = DataLoader() var_manager = VariableManager() host_vars = None host_info = [] for i in get_inventory_files(base): try: inv = Inventory(host_list='%s/%s' %(base, i), loader=loader, variable_manager=var_manager) host_vars = inv.get_vars(host_name) except AnsibleError as err: # print '%s in inventory %s' %(err, i) inv.host_list = None inv.refresh_inventory() continue if host_vars: ssh_host = host_vars.get('ansible_ssh_host', None) ssh_user = host_vars.get('ansible_ssh_user', None) ssh_key = host_vars.get('ansible_ssh_private_key_file', None) ssh_port = host_vars.get('ansible_ssh_port', 22) else: raise Exception('Host %s is not present in any inventory %s' %(host_name, ' '.join(get_inventory_files(base)))) if not ssh_host or not ssh_user: raise Exception('ansible_ssh_host and ansible_ssh_user required.') host_info.append(str('%s@%s' %(ssh_user, ssh_host))) if ssh_key: ssh_key = os.path.expanduser(ssh_key) if not os.path.isabs(ssh_key): ssh_key = os.path.abspath(ssh_key) if os.path.exists(ssh_key): host_info += ['-i', str(ssh_key)] else: print ("SSH key %s doesn't exists please check path." %(ssh_key)) if ssh_port: if not int(ssh_port) == min(max(int(ssh_port), 0), 65535): raise Exception('Incorrect port number given') host_info += ['-p', str(ssh_port)] return host_info
def run(self): sshpass = None becomepass = None b_vault_pass = None passwords = {} # initial error check, to make sure all specified playbooks are accessible # before we start running anything through the playbook executor for playbook in self.args: if not os.path.exists(playbook): raise AnsibleError("the playbook: %s could not be found" % playbook) if not (os.path.isfile(playbook) or stat.S_ISFIFO(os.stat(playbook).st_mode)): raise AnsibleError( "the playbook: %s does not appear to be a file" % playbook) # don't deal with privilege escalation or passwords when we don't need to if not self.options.listhosts and not self.options.listtasks and not self.options.listtags and not self.options.syntax: self.normalize_become_options() (sshpass, becomepass) = self.ask_passwords() passwords = {'conn_pass': sshpass, 'become_pass': becomepass} loader = DataLoader() if self.options.vault_password_file: # read vault_pass from a file b_vault_pass = CLI.read_vault_password_file( self.options.vault_password_file, loader=loader) loader.set_vault_password(b_vault_pass) elif self.options.ask_vault_pass: b_vault_pass = self.ask_vault_passwords() loader.set_vault_password(b_vault_pass) # create the variable manager, which will be shared throughout # the code, ensuring a consistent view of global variables variable_manager = VariableManager() variable_manager.extra_vars = load_extra_vars(loader=loader, options=self.options) # extra_vars = {'elastic_url':Configuration.elastic_url, # 'uuid':self._job.uuid } variable_manager.options_vars = load_options_vars(self.options) # create the inventory, and filter it based on the subset specified (if any) inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=self.options.inventory) # added by [email protected] inventory.host_list = [] inventory.host_list = self.options.inventory for group in self.inventoryContainer.groups: if group.name == 'all': if group.vars: inventory.get_group('all').vars.update(group.vars) else: group.parent_groups.append(inventory.get_group('all')) inventory.get_group('all').child_groups.append(group) # inventory.get_group('all').hosts.extend(group.hosts) # inventory.get_group('all').vars.update(group.vars) inventory.add_group(group) variable_manager.set_inventory(inventory) # (which is not returned in list_hosts()) is taken into account for # warning if inventory is empty. But it can't be taken into account for # checking if limit doesn't match any hosts. Instead we don't worry about # limit if only implicit localhost was in inventory to start with. # # Fix this when we rewrite inventory by making localhost a real host (and thus show up in list_hosts()) no_hosts = False # if len(inventory.list_hosts()) == 0: # Empty inventory # display.warning("provided hosts list is empty, only localhost is available") # no_hosts = True inventory.subset(self.options.subset) # if len(inventory.list_hosts()) == 0 and no_hosts is False: # Invalid limit # raise AnsibleError("Specified --limit does not match any hosts") # flush fact cache if requested if self.options.flush_cache: self._flush_cache(inventory, variable_manager) # create the playbook executor, which manages running the plays via a task queue manager self.pbex = PlaybookExecutor(playbooks=[playbook], inventory=inventory, variable_manager=variable_manager, loader=loader, options=self.options, passwords=passwords) results = self.pbex.run() self.apijob.stats = self.pbex._tqm._stats self.apijob.finished() if isinstance(results, list): for p in self.results: display.display('\nplaybook: %s' % p['playbook']) for idx, play in enumerate(p['plays']): if play._included_path is not None: loader.set_basedir(play._included_path) else: pb_dir = os.path.realpath( os.path.dirname(p['playbook'])) loader.set_basedir(pb_dir) msg = "\n play #%d (%s): %s" % (idx + 1, ','.join( play.hosts), play.name) mytags = set(play.tags) msg += '\tTAGS: [%s]' % (','.join(mytags)) if self.options.listhosts: playhosts = set(inventory.get_hosts(play.hosts)) msg += "\n pattern: %s\n hosts (%d):" % ( play.hosts, len(playhosts)) for host in playhosts: msg += "\n %s" % host display.display(msg) all_tags = set() if self.options.listtags or self.options.listtasks: taskmsg = '' if self.options.listtasks: taskmsg = ' tasks:\n' def _process_block(b): taskmsg = '' for task in b.block: if isinstance(task, Block): taskmsg += _process_block(task) else: if task.action == 'meta': continue all_tags.update(task.tags) if self.options.listtasks: cur_tags = list( mytags.union(set(task.tags))) cur_tags.sort() if task.name: taskmsg += " %s" % task.get_name( ) else: taskmsg += " %s" % task.action taskmsg += "\tTAGS: [%s]\n" % ', '.join( cur_tags) return taskmsg all_vars = variable_manager.get_vars(loader=loader, play=play) play_context = PlayContext(play=play, options=self.options) for block in play.compile(): block = block.filter_tagged_tasks( play_context, all_vars) if not block.has_tasks(): continue taskmsg += _process_block(block) if self.options.listtags: cur_tags = list(mytags.union(all_tags)) cur_tags.sort() taskmsg += " TASK TAGS: [%s]\n" % ', '.join( cur_tags) display.display(taskmsg) return 0 else: return results