def run(self): super(VaultCLI, self).run() loader = DataLoader() # set default restrictive umask old_umask = os.umask(0o077) if self.options.vault_password_file: # read vault_pass from a file self.b_vault_pass = CLI.read_vault_password_file(self.options.vault_password_file, loader) if self.options.new_vault_password_file: # for rekey only self.b_new_vault_pass = CLI.read_vault_password_file(self.options.new_vault_password_file, loader) if not self.b_vault_pass or self.options.ask_vault_pass: self.b_vault_pass = self.ask_vault_passwords() if not self.b_vault_pass: raise AnsibleOptionsError("A password is required to use Ansible's Vault") if self.action == 'rekey': if not self.b_new_vault_pass: self.b_new_vault_pass = self.ask_new_vault_passwords() if not self.b_new_vault_pass: raise AnsibleOptionsError("A password is required to rekey Ansible's Vault") self.editor = VaultEditor(self.b_vault_pass) self.execute() # and restore umask os.umask(old_umask)
def run(self): super(VaultCLI, self).run() loader = DataLoader() # set default restrictive umask old_umask = os.umask(0o077) if self.options.vault_password_file: # read vault_pass from a file self.vault_pass = CLI.read_vault_password_file(self.options.vault_password_file, loader) else: newpass = False rekey = False if not self.options.new_vault_password_file: newpass = (self.action in ['create', 'rekey', 'encrypt']) rekey = (self.action == 'rekey') self.vault_pass, self.new_vault_pass = self.ask_vault_passwords(ask_new_vault_pass=newpass, rekey=rekey) if self.options.new_vault_password_file: # for rekey only self.new_vault_pass = CLI.read_vault_password_file(self.options.new_vault_password_file, loader) if not self.vault_pass: raise AnsibleOptionsError("A password is required to use Ansible's Vault") self.editor = VaultEditor(self.vault_pass) self.execute() # and restore umask os.umask(old_umask)
def run(self): super(VaultCLI, self).run() if self.options.vault_password_file: # read vault_pass from a file self.vault_pass = CLI.read_vault_password_file( self.options.vault_password_file) else: self.vault_pass, _ = self.ask_vault_passwords( ask_vault_pass=True, ask_new_vault_pass=False, confirm_new=False) if self.options.new_vault_password_file: # for rekey only self.new_vault_pass = CLI.read_vault_password_file( self.options.new_vault_password_file) if not self.vault_pass: raise AnsibleOptionsError( "A password is required to use Ansible's Vault") self.editor = VaultEditor(self.vault_pass) self.execute()
def run(self): results = None super(InventoryCLI, self).run() # Initialize needed objects if getattr(self, '_play_prereqs', False): self.loader, self.inventory, self.vm = self._play_prereqs(self.options) else: # fallback to pre 2.4 way of initialzing from ansible.vars import VariableManager from ansible.inventory import Inventory self._new_api = False self.loader = DataLoader() self.vm = VariableManager() # use vault if needed if self.options.vault_password_file: vault_pass = CLI.read_vault_password_file(self.options.vault_password_file, loader=self.loader) elif self.options.ask_vault_pass: vault_pass = self.ask_vault_passwords() else: vault_pass = None if vault_pass: self.loader.set_vault_password(vault_pass) # actually get inventory and vars self.inventory = Inventory(loader=self.loader, variable_manager=self.vm, host_list=self.options.inventory) self.vm.set_inventory(self.inventory) if self.options.host: hosts = self.inventory.get_hosts(self.options.host) if len(hosts) != 1: raise AnsibleOptionsError("You must pass a single valid host to --hosts parameter") myvars = self._get_host_variables(host=hosts[0]) self._remove_internal(myvars) # FIXME: should we template first? results = self.dump(myvars) elif self.options.graph: results = self.inventory_graph() elif self.options.list: top = self._get_group('all') if self.options.yaml: results = self.yaml_inventory(top) else: results = self.json_inventory(top) results = self.dump(results) if results: # FIXME: pager? display.display(results) exit(0) exit(1)
def run(self): super(VaultCLI, self).run() loader = DataLoader() # set default restrictive umask old_umask = os.umask(0o077) if self.options.vault_password_file: # read vault_pass from a file self.b_vault_pass = CLI.read_vault_password_file( self.options.vault_password_file, loader) if self.options.new_vault_password_file: # for rekey only self.b_new_vault_pass = CLI.read_vault_password_file( self.options.new_vault_password_file, loader) if not self.b_vault_pass or self.options.ask_vault_pass: # the 'read' options dont need to ask for password confirmation. # 'edit' is read/write, but the decrypt will confirm. if self.action in ['decrypt', 'edit', 'view', 'rekey']: self.b_vault_pass = self.ask_vault_passwords() else: self.b_vault_pass = self.ask_new_vault_passwords() if not self.b_vault_pass: raise AnsibleOptionsError( "A password is required to use Ansible's Vault") if self.action == 'rekey': if not self.b_new_vault_pass: self.b_new_vault_pass = self.ask_new_vault_passwords() if not self.b_new_vault_pass: raise AnsibleOptionsError( "A password is required to rekey Ansible's Vault") if self.action == 'encrypt_string': if self.options.encrypt_string_prompt: self.encrypt_string_prompt = True self.editor = VaultEditor(self.b_vault_pass) self.execute() # and restore umask os.umask(old_umask)
def run(self): super(VaultCLI, self).run() loader = DataLoader() if self.options.vault_password_file: # read vault_pass from a file self.vault_pass = CLI.read_vault_password_file(self.options.vault_password_file, loader) else: self.vault_pass, _= self.ask_vault_passwords(ask_vault_pass=True, ask_new_vault_pass=False, confirm_new=False) if self.options.new_vault_password_file: # for rekey only self.new_vault_pass = CLI.read_vault_password_file(self.options.new_vault_password_file, loader) if not self.vault_pass: raise AnsibleOptionsError("A password is required to use Ansible's Vault") self.editor = VaultEditor(self.vault_pass) self.execute()
def _load_auth_secrets(self, hosts=[], secrets=[]): for _safe, _lockpick in secrets: try: _safe_loader = DataLoader(); _safe_lockpick = CLI.read_vault_password_file(_lockpick, loader=_safe_loader); _safe_loader.set_vault_password(_safe_lockpick); _safe_contents = _safe_loader.load_from_file(_safe); if 'credentials' not in _safe_contents: return dict(); #display.display(pprint.pformat(_safe_contents, indent=4), color='green'); return _safe_contents['credentials']; except Exception as e: display.display('[ERROR] ' + str(e), color='red'); return dict();
def role_vars(): parser.add_argument( '--playbook_path', help='Test Playbook path for role - usually role/tests/test.yml', required=True) parser.add_argument( '--vault_password_file', help='Vault password file - usually role/tests/test.yml') args = parser.parse_args() variable_manager = VariableManager() loader = DataLoader() if args.vault_password_file: # read vault_pass from a file vault_pass = CLI.read_vault_password_file(args.vault_password_file, loader=loader) loader.set_vault_password(vault_pass) playbook_path = args.playbook_path if not os.path.exists(playbook_path): print('[ERROR] The playbook does not exist') sys.exit(1) pb = Playbook.load(playbook_path, variable_manager=variable_manager, loader=loader) plays = pb.get_plays() if len(plays) == 0: print('[ERROR] No plays in playbook') sys.exit(1) first_play = plays[0] if first_play._included_path is not None: loader.set_basedir(first_play._included_path) else: loader.set_basedir(pb._basedir) result = dict() for role in first_play.roles: result.update(role.get_default_vars()) result.update(role.get_vars()) print(json.dumps(result))
def __init__(self, inventory, ask_vault_pass, vault_password_files, vault_ids): if vault_ids or len(vault_password_files) > 1: raise NotImplementedError from ansible.cli import CLI super(Inventory20, self).__init__() loader = DataLoader() if ask_vault_pass: self.vault_pass = CLI.ask_vault_passwords() elif vault_password_files: self.vault_pass = CLI.read_vault_password_file(vault_password_files[0], loader) if self.vault_pass is not None: loader.set_vault_password(self.vault_pass) self.variable_manager = VariableManager() try: self.inventory = ansible.inventory.Inventory(loader=loader, variable_manager=self.variable_manager, host_list=inventory) except ansible.errors.AnsibleError: raise NoVaultSecretFound self.variable_manager.set_inventory(self.inventory)
def __init__(self, inventory, ask_vault_pass, vault_password_files, vault_ids): if vault_ids or len(vault_password_files) > 1: raise NotImplementedError from ansible.cli import CLI super(Inventory20, self).__init__() loader = DataLoader() if ask_vault_pass: self.vault_pass = CLI.ask_vault_passwords() elif vault_password_files: self.vault_pass = CLI.read_vault_password_file( vault_password_files[0], loader) if self.vault_pass is not None: loader.set_vault_password(self.vault_pass) self.variable_manager = VariableManager() try: self.inventory = ansible.inventory.Inventory( loader=loader, variable_manager=self.variable_manager, host_list=inventory) except ansible.errors.AnsibleError: raise NoVaultSecretFound self.variable_manager.set_inventory(self.inventory)
def run(self): super(PlaybookCLI, self).run() # Note: slightly wrong, this is written so that implicit localhost # Manage passwords sshpass = None becomepass = None vault_pass = None passwords = {} # 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 vault_pass = CLI.read_vault_password_file(self.options.vault_password_file, loader=loader) loader.set_vault_password(vault_pass) elif self.options.ask_vault_pass: vault_pass = self.ask_vault_passwords()[0] loader.set_vault_password(vault_pass) # 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) # 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) 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) 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") # create the playbook executor, which manages running the plays via a task queue manager pbex = PlaybookExecutor(playbooks=self.args, inventory=inventory, variable_manager=variable_manager, loader=loader, options=self.options, passwords=passwords) results = pbex.run() if isinstance(results, list): for p in results: display.display('\nplaybook: %s' % p['playbook']) for idx, play in enumerate(p['plays']): 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
def run(self): super(PlaybookCLI, self).run() # Note: slightly wrong, this is written so that implicit localhost # Manage passwords sshpass = None becomepass = None 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 vault_pass = CLI.read_vault_password_file( self.options.vault_password_file, loader=loader) loader.set_vault_password(vault_pass) elif self.options.ask_vault_pass: vault_pass = self.ask_vault_passwords()[0] loader.set_vault_password(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) 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) 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: for host in inventory.list_hosts(): variable_manager.clear_facts(host) # create the playbook executor, which manages running the plays via a task queue manager pbex = PlaybookExecutor(playbooks=self.args, inventory=inventory, variable_manager=variable_manager, loader=loader, options=self.options, passwords=passwords) results = pbex.run() if isinstance(results, list): for p in results: display.display('\nplaybook: %s' % p['playbook']) for idx, play in enumerate(p['plays']): 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
def run_command(self, name, ctx=None): cmd = self.able_file.get_command(name) from able.ablefile.command import AbleCommand if not isinstance(cmd, AbleCommand): return 0 cmd.ablefile = self.able_file params, global_params = utils.filter_params(ctx.params) self.options = self.get_global_option_values(cmd, global_params) if 'verbosity' in self.options: display.verbosity = self.options.verbosity # Note: slightly wrong, this is written so that implicit localhost # Manage passwords sshpass = None becomepass = None vault_pass = None passwords = {} # 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() (conn_pass, become_pass) = self.ask_passwords() passwords['conn_pass'] = conn_pass if conn_pass is not None else self.options.conn_pass passwords['become_pass'] = become_pass if become_pass is not None else self.options.become_pass loader = DataLoader() if self.options.vault_password_file: # read vault_pass from a file vault_pass = CLI.read_vault_password_file(self.options.vault_password_file, loader=loader) loader.set_vault_password(vault_pass) elif self.options.ask_vault_pass: vault_pass = self.ask_vault_passwords()[0] loader.set_vault_password(vault_pass) variable_manager = cmd.get_variable_manager() variable_manager.extra_vars = cmd.get_extra_vars(params, self.options) loader = cmd.get_loader() # create inventory and pass to var manager inventory = AbleInventory( loader=loader, variable_manager=variable_manager, host_list=cmd.get_inventory(), inventory_files=cmd.get_inventory_files() ) variable_manager.set_inventory(inventory) # Run any confirmation prompts cmd.do_confirm(variable_manager, loader) # create the playbook executor, which manages running the plays via a task queue manager ex = AbleCommandExecutor( command=cmd, inventory=inventory, variable_manager=variable_manager, loader=loader, options=self.options, passwords=passwords) results = ex.run() if isinstance(results, list): for p in results: display.display('\nCommand: %s' % p['command']) for idx, play in enumerate(p['plays']): msg = "\n command #%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' all_vars = cmd.get_variable_manager().get_vars(loader=cmd.get_loader(), play=self) play_context = PlayContext(play=self, options=self.options) for block in play.compile(): block = block.filter_tagged_tasks(play_context, all_vars) if not block.has_tasks(): continue for task in block.block: 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) 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
from ansible.parsing.vault import VaultEditor from ansible.parsing.dataloader import DataLoader from ansible.cli import CLI import yaml import os loader = DataLoader() vault_password_file = os.environ.get('ANSIBLE_VAULT_PASSWORD_FILE') secret_file = os.environ.get('SECRET_FILE') if vault_password_file and secret_file: password = CLI.read_vault_password_file(vault_password_file, loader) editor = VaultEditor(password) secrets = yaml.load(editor.plaintext(secret_file)) print secrets for k, v in secrets.iteritems(): print k, v else: print """ Specify the following ANSIBLE_VAULT_PASSWORD_FILE SECRET_FILE """
def read_vault_file(self, vault_password_file): from ansible.cli import CLI from ansible.parsing.dataloader import DataLoader return CLI.read_vault_password_file(vault_password_file, DataLoader())
def run(self): super(ConsoleCLI, self).run() sshpass = None becomepass = None vault_pass = None # hosts if len(self.args) != 1: self.pattern = 'all' else: self.pattern = self.args[0] self.options.cwd = self.pattern # dynamically add modules as commands self.modules = self.list_modules() for module in self.modules: setattr( self, 'do_' + module, lambda arg, module=module: self.default(module + ' ' + arg)) setattr(self, 'help_' + module, lambda module=module: self.helpdefault(module)) self.normalize_become_options() (sshpass, becomepass) = self.ask_passwords() self.passwords = {'conn_pass': sshpass, 'become_pass': becomepass} self.loader = DataLoader() if self.options.vault_password_file: # read vault_pass from a file vault_pass = CLI.read_vault_password_file( self.options.vault_password_file, loader=self.loader) self.loader.set_vault_password(vault_pass) elif self.options.ask_vault_pass: vault_pass = self.ask_vault_passwords()[0] self.loader.set_vault_password(vault_pass) self.variable_manager = VariableManager() self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list=self.options.inventory) self.variable_manager.set_inventory(self.inventory) no_hosts = False if len(self.inventory.list_hosts()) == 0: # Empty inventory no_hosts = True display.warning( "provided hosts list is empty, only localhost is available") self.inventory.subset(self.options.subset) hosts = self.inventory.list_hosts(self.pattern) if len(hosts) == 0 and not no_hosts: raise AnsibleError( "Specified hosts and/or --limit does not match any hosts") self.groups = self.inventory.list_groups() self.hosts = [x.name for x in hosts] # This hack is to work around readline issues on a mac: # http://stackoverflow.com/a/7116997/541202 if 'libedit' in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") histfile = os.path.join(os.path.expanduser("~"), ".ansible-console_history") try: readline.read_history_file(histfile) except IOError: pass atexit.register(readline.write_history_file, histfile) self.set_prompt() self.cmdloop()
def run(self): super(PlaybookCLI, self).run() # Note: slightly wrong, this is written so that implicit localhost # Manage passwords sshpass = None becomepass = None vault_pass = None passwords = {} # 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 } if self.options.vault_password_file: # read vault_pass from a file vault_pass = CLI.read_vault_password_file(self.options.vault_password_file) elif self.options.ask_vault_pass: vault_pass = self.ask_vault_passwords(ask_vault_pass=True, ask_new_vault_pass=False, confirm_new=False)[0] loader = DataLoader(vault_password=vault_pass) # 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) # 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) # 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) 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 self.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") # create the playbook executor, which manages running the plays via a task queue manager pbex = PlaybookExecutor(playbooks=self.args, inventory=inventory, variable_manager=variable_manager, loader=loader, display=self.display, options=self.options, passwords=passwords) results = pbex.run() if isinstance(results, list): for p in results: self.display.display('\nplaybook: %s' % p['playbook']) i = 1 for play in p['plays']: if play.name: playname = play.name else: playname = '#' + str(i) msg = "\n PLAY: %s" % (playname) mytags = set() if self.options.listtags and play.tags: mytags = mytags.union(set(play.tags)) msg += ' TAGS: [%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 self.display.display(msg) if self.options.listtags or self.options.listtasks: taskmsg = ' tasks:' for block in play.compile(): if not block.has_tasks(): continue j = 1 for task in block.block: taskmsg += "\n %s" % task if self.options.listtags and task.tags: taskmsg += " TAGS: [%s]" % ','.join(mytags.union(set(task.tags))) j = j + 1 self.display.display(taskmsg) i = i + 1 return 0 else: return results
def run(self): ''' use Runner lib to do SSH things ''' super(AdHocCLI, self).run() # only thing left should be host pattern pattern = self.args[0] # ignore connection password cause we are local if self.options.connection == "local": self.options.ask_pass = False sshpass = None becomepass = None vault_pass = None self.normalize_become_options() (sshpass, becomepass) = self.ask_passwords() passwords = { 'conn_pass': sshpass, 'become_pass': becomepass } if self.options.vault_password_file: # read vault_pass from a file vault_pass = CLI.read_vault_password_file(self.options.vault_password_file) elif self.options.ask_vault_pass: vault_pass = self.ask_vault_passwords(ask_vault_pass=True, ask_new_vault_pass=False, confirm_new=False)[0] loader = DataLoader(vault_password=vault_pass) variable_manager = VariableManager() variable_manager.extra_vars = load_extra_vars(loader=loader, options=self.options) inventory = Inventory(loader=loader, variable_manager=variable_manager, host_list=self.options.inventory) variable_manager.set_inventory(inventory) hosts = inventory.list_hosts(pattern) if len(hosts) == 0: self.display.warning("provided hosts list is empty, only localhost is available") if self.options.listhosts: self.display.display(' hosts (%d):' % len(hosts)) for host in hosts: self.display.display(' %s' % host) return 0 if self.options.module_name in C.MODULE_REQUIRE_ARGS and not self.options.module_args: err = "No argument passed to %s module" % self.options.module_name if pattern.endswith(".yml"): err = err + ' (did you mean to run ansible-playbook?)' raise AnsibleOptionsError(err) #TODO: implement async support #if self.options.seconds: # callbacks.display("background launch...\n\n", color='cyan') # results, poller = runner.run_async(self.options.seconds) # results = self.poll_while_needed(poller) #else: # results = runner.run() # create a pseudo-play to execute the specified module via a single task play_ds = self._play_ds(pattern) play = Play().load(play_ds, variable_manager=variable_manager, loader=loader) if self.options.one_line: cb = 'oneline' else: cb = 'minimal' # now create a task queue manager to execute the play self._tqm = None try: self._tqm = TaskQueueManager( inventory=inventory, variable_manager=variable_manager, loader=loader, display=self.display, options=self.options, passwords=passwords, stdout_callback=cb, ) result = self._tqm.run(play) finally: if self._tqm: self._tqm.cleanup() return result
def run(self): super(PlaybookCLI, self).run() # Note: slightly wrong, this is written so that implicit localhost # Manage passwords sshpass = None becomepass = None vault_pass = None passwords = {} # 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 vault_pass = CLI.read_vault_password_file(self.options.vault_password_file, loader=loader) loader.set_vault_password(vault_pass) elif self.options.ask_vault_pass: vault_pass = self.ask_vault_passwords(ask_vault_pass=True, ask_new_vault_pass=False, confirm_new=False)[0] loader.set_vault_password(vault_pass) # 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) # 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) # 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) 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 self.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") # create the playbook executor, which manages running the plays via a task queue manager pbex = PlaybookExecutor( playbooks=self.args, inventory=inventory, variable_manager=variable_manager, loader=loader, display=self.display, options=self.options, passwords=passwords, ) results = pbex.run() if isinstance(results, list): for p in results: self.display.display("\nplaybook: %s" % p["playbook"]) i = 1 for play in p["plays"]: if play.name: playname = play.name else: playname = "#" + str(i) msg = "\n PLAY: %s" % (playname) mytags = set() if self.options.listtags and play.tags: mytags = mytags.union(set(play.tags)) msg += " TAGS: [%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 self.display.display(msg) if self.options.listtags or self.options.listtasks: taskmsg = " tasks:" for block in play.compile(): if not block.has_tasks(): continue j = 1 for task in block.block: taskmsg += "\n %s" % task if self.options.listtags and task.tags: taskmsg += " TAGS: [%s]" % ",".join(mytags.union(set(task.tags))) j = j + 1 self.display.display(taskmsg) i = i + 1 return 0 else: return results
def run(self): super(PlaybookCLI, self).run() # Note: slightly wrong, this is written so that implicit localhost # Manage passwords sshpass = None becomepass = None vault_pass = None passwords = {} # 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} if self.options.vault_password_file: # read vault_pass from a file vault_pass = CLI.read_vault_password_file( self.options.vault_password_file) elif self.options.ask_vault_pass: vault_pass = self.ask_vault_passwords(ask_vault_pass=True, ask_new_vault_pass=False, confirm_new=False)[0] loader = DataLoader(vault_password=vault_pass) # FIXME: this should be moved inside the playbook executor code only_tags = self.options.tags.split(",") skip_tags = self.options.skip_tags if self.options.skip_tags is not None: skip_tags = self.options.skip_tags.split(",") # 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) # 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) # 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) 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 self.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") # create the playbook executor, which manages running the plays via a task queue manager pbex = PlaybookExecutor(playbooks=self.args, inventory=inventory, variable_manager=variable_manager, loader=loader, display=self.display, options=self.options, passwords=passwords) results = pbex.run() if isinstance(results, list): for p in results: self.display.display('\nplaybook: %s\n' % p['playbook']) for play in p['plays']: if self.options.listhosts: self.display.display("\n %s (%s): host count=%d" % (play['name'], play['pattern'], len(play['hosts']))) for host in play['hosts']: self.display.display(" %s" % host) if self.options.listtasks: #TODO: do we want to display block info? self.display.display("\n %s" % (play['name'])) for task in play['tasks']: self.display.display(" %s" % task) if self.options.listtags: #TODO: fix once we figure out block handling above self.display.display("\n %s: tags count=%d" % (play['name'], len(play['tags']))) for tag in play['tags']: self.display.display(" %s" % tag) return 0 else: return results
def run(self): super(ConsoleCLI, self).run() sshpass = None becomepass = None vault_pass = None # hosts if len(self.args) != 1: self.pattern = 'all' else: self.pattern = self.args[0] self.options.cwd = self.pattern # dynamically add modules as commands self.modules = self.list_modules() for module in self.modules: setattr(self, 'do_' + module, lambda arg, module=module: self.default(module + ' ' + arg)) setattr(self, 'help_' + module, lambda module=module: self.helpdefault(module)) self.normalize_become_options() (sshpass, becomepass) = self.ask_passwords() self.passwords = { 'conn_pass': sshpass, 'become_pass': becomepass } self.loader = DataLoader() if self.options.vault_password_file: # read vault_pass from a file vault_pass = CLI.read_vault_password_file(self.options.vault_password_file, loader=self.loader) self.loader.set_vault_password(vault_pass) elif self.options.ask_vault_pass: vault_pass = self.ask_vault_passwords()[0] self.loader.set_vault_password(vault_pass) self.variable_manager = VariableManager() self.inventory = Inventory(loader=self.loader, variable_manager=self.variable_manager, host_list=self.options.inventory) self.variable_manager.set_inventory(self.inventory) no_hosts = False if len(self.inventory.list_hosts()) == 0: # Empty inventory no_hosts = True display.warning("provided hosts list is empty, only localhost is available") self.inventory.subset(self.options.subset) hosts = self.inventory.list_hosts(self.pattern) if len(hosts) == 0 and not no_hosts: raise AnsibleError("Specified hosts and/or --limit does not match any hosts") self.groups = self.inventory.list_groups() self.hosts = [x.name for x in hosts] # This hack is to work around readline issues on a mac: # http://stackoverflow.com/a/7116997/541202 if 'libedit' in readline.__doc__: readline.parse_and_bind("bind ^I rl_complete") else: readline.parse_and_bind("tab: complete") histfile = os.path.join(os.path.expanduser("~"), ".ansible-console_history") try: readline.read_history_file(histfile) except IOError: pass atexit.register(readline.write_history_file, histfile) self.set_prompt() self.cmdloop()