예제 #1
0
파일: doc.py 프로젝트: ernstp/ansible
    def get_snippet_text(self, doc):

        text = []
        desc = CLI.tty_ify(doc['short_description'])
        text.append("- name: %s" % (desc))
        text.append("  %s:" % (doc['module']))
        pad = 31
        subdent = " " * pad
        limit = display.columns - pad

        for o in sorted(doc['options'].keys()):
            opt = doc['options'][o]
            if isinstance(opt['description'], string_types):
                desc = CLI.tty_ify(opt['description'])
            else:
                desc = CLI.tty_ify(" ".join(opt['description']))

            required = opt.get('required', False)
            if not isinstance(required, bool):
                raise("Incorrect value for 'Required', a boolean is needed.: %s" % required)
            if required:
                desc = "(required) %s" % desc
            o = '%s:' % o
            text.append("      %-20s   # %s" % (o, textwrap.fill(desc, limit, subsequent_indent=subdent)))
        text.append('')

        return "\n".join(text)
예제 #2
0
    def get_snippet_text(self, doc):

        text = []
        desc = CLI.tty_ify(doc['short_description'])
        text.append("- name: %s" % (desc))
        text.append("  action: %s" % (doc['module']))
        pad = 31
        subdent = ''.join([" " for a in xrange(pad)])
        limit = display.columns - pad

        for o in sorted(doc['options'].keys()):
            opt = doc['options'][o]
            desc = CLI.tty_ify(" ".join(opt['description']))

            required = opt.get('required', False)
            if not isinstance(required, bool):
                raise("Incorrect value for 'Required', a boolean is needed.: %s" % required)
            if required:
                s = o + "="
            else:
                s = o
            text.append("      %-20s   # %s" % (s, textwrap.fill(desc, limit, subsequent_indent=subdent)))
        text.append('')

        return "\n".join(text)
예제 #3
0
파일: vault.py 프로젝트: KMK-ONLINE/ansible
    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)
예제 #4
0
    def get_man_text(doc):

        opt_indent="        "
        text = []
        text.append("> %s\n" % doc['module'].upper())

        desc = " ".join(doc['description'])

        text.append("%s\n" % textwrap.fill(CLI.tty_ify(desc), initial_indent="  ", subsequent_indent="  "))

        if 'option_keys' in doc and len(doc['option_keys']) > 0:
            text.append("Options (= is mandatory):\n")

        for o in sorted(doc['option_keys']):
            opt = doc['options'][o]

            if opt.get('required', False):
                opt_leadin = "="
            else:
                opt_leadin = "-"

            text.append("%s %s" % (opt_leadin, o))

            desc = " ".join(opt['description'])

            if 'choices' in opt:
                choices = ", ".join(str(i) for i in opt['choices'])
                desc = desc + " (Choices: " + choices + ")"
            if 'default' in opt:
                default = str(opt['default'])
                desc = desc + " [Default: " + default + "]"
            text.append("%s\n" % textwrap.fill(CLI.tty_ify(desc), initial_indent=opt_indent,
                                 subsequent_indent=opt_indent))

        if 'notes' in doc and len(doc['notes']) > 0:
            notes = " ".join(doc['notes'])
            text.append("Notes:%s\n" % textwrap.fill(CLI.tty_ify(notes), initial_indent="  ",
                                subsequent_indent=opt_indent))


        if 'requirements' in doc and doc['requirements'] is not None and len(doc['requirements']) > 0:
            req = ", ".join(doc['requirements'])
            text.append("Requirements:%s\n" % textwrap.fill(CLI.tty_ify(req), initial_indent="  ",
                                subsequent_indent=opt_indent))

        if 'examples' in doc and len(doc['examples']) > 0:
            text.append("Example%s:\n" % ('' if len(doc['examples']) < 2 else 's'))
            for ex in doc['examples']:
                text.append("%s\n" % (ex['code']))

        if 'plainexamples' in doc and doc['plainexamples'] is not None:
            text.append("EXAMPLES:")
            text.append(doc['plainexamples'])
        if 'returndocs' in doc and doc['returndocs'] is not None:
            text.append("RETURN VALUES:")
            text.append(doc['returndocs'])
        text.append('')

        return "\n".join(text)
 def __init__(self, inventory, ask_vault_pass, vault_password_files, vault_ids):
     from ansible.cli import CLI
     super(Inventory24, self).__init__()
     loader = DataLoader()
     if vault_ids or vault_password_files or ask_vault_pass:
         CLI.setup_vault_secrets(loader, vault_ids, vault_password_files, ask_vault_pass)
     self.inventory = ansible.inventory.manager.InventoryManager(loader=loader, sources=inventory)
     self.variable_manager = VariableManager(loader=loader)
     self.variable_manager.set_inventory(self.inventory)
예제 #6
0
    def parse(self):

        # create parser for CLI options
        parser = CLI.base_parser(
            usage = "%prog playbook.yml",
            connect_opts=True,
            meta_opts=True,
            runas_opts=True,
            subset_opts=True,
            check_opts=True,
            inventory_opts=True,
            runtask_opts=True,
            vault_opts=True,
            fork_opts=True,
            module_opts=True,
        )

        # ansible playbook specific opts
        parser.add_option('--list-tasks', dest='listtasks', action='store_true',
            help="list all tasks that would be executed")
        parser.add_option('--list-tags', dest='listtags', action='store_true',
            help="list all available tags")
        parser.add_option('--step', dest='step', action='store_true',
            help="one-step-at-a-time: confirm each task before running")
        parser.add_option('--start-at-task', dest='start_at_task',
            help="start the playbook at the task matching this name")

        self.parser = parser
        super(PlaybookCLI, self).parse()

        if len(self.args) == 0:
            raise AnsibleOptionsError("You must specify a playbook file to run")

        display.verbosity = self.options.verbosity
        self.validate_conflicts(runas_opts=True, vault_opts=True, fork_opts=True)
예제 #7
0
파일: doc.py 프로젝트: ernstp/ansible
    def parse(self):

        self.parser = CLI.base_parser(
            usage='usage: %prog [-l|-s] [options] [-t <plugin type] [plugin]',
            module_opts=True,
            desc="plugin documentation tool",
            epilog="See man pages for Ansible CLI options or website for tutorials https://docs.ansible.com"
        )

        self.parser.add_option("-l", "--list", action="store_true", default=False, dest='list_dir',
                               help='List available plugins')
        self.parser.add_option("-s", "--snippet", action="store_true", default=False, dest='show_snippet',
                               help='Show playbook snippet for specified plugin(s)')
        self.parser.add_option("-a", "--all", action="store_true", default=False, dest='all_plugins',
                               help='**For internal testing only** Show documentation for all plugins.')
        self.parser.add_option("-t", "--type", action="store", default='module', dest='type', type='choice',
                               help='Choose which plugin type (defaults to "module")',
                               choices=['cache', 'callback', 'connection', 'inventory', 'lookup', 'module', 'strategy', 'vars'])

        super(DocCLI, self).parse()

        if [self.options.all_plugins, self.options.list_dir, self.options.show_snippet].count(True) > 1:
            raise AnsibleOptionsError("Only one of -l, -s or -a can be used at the same time.")

        display.verbosity = self.options.verbosity
예제 #8
0
    def parse(self):
        self.parser = CLI.base_parser(
            usage='%prog [<host-pattern>] [options]',
            runas_opts=True,
            inventory_opts=True,
            connect_opts=True,
            check_opts=True,
            vault_opts=True,
            fork_opts=True,
            module_opts=True,
            basedir_opts=True,
            desc="REPL console for executing Ansible tasks.",
            epilog="This is not a live session/connection, each task executes in the background and returns it's results."
        )

        # options unique to shell
        self.parser.add_option('--step', dest='step', action='store_true',
                               help="one-step-at-a-time: confirm each task before running")

        self.parser.set_defaults(cwd='*')

        super(ConsoleCLI, self).parse()

        display.verbosity = self.options.verbosity
        self.validate_conflicts(runas_opts=True, vault_opts=True, fork_opts=True)
예제 #9
0
def parser():
    parser = CLI.base_parser(runas_opts=True, meta_opts=True,
                             runtask_opts=True, vault_opts=True,
                             async_opts=True, connect_opts=True,
                             subset_opts=True, check_opts=True,
                             inventory_opts=True,)
    return parser
예제 #10
0
파일: doc.py 프로젝트: awiddersheim/ansible
    def parse(self):

        self.parser = CLI.base_parser(
            usage='usage: %prog [-l|-F|-s] [options] [-t <plugin type> ] [plugin]',
            module_opts=True,
            desc="plugin documentation tool",
            epilog="See man pages for Ansible CLI options or website for tutorials https://docs.ansible.com"
        )

        self.parser.add_option("-F", "--list_files", action="store_true", default=False, dest="list_files",
                               help='Show plugin names and their source files without summaries (implies --list)')
        self.parser.add_option("-l", "--list", action="store_true", default=False, dest='list_dir',
                               help='List available plugins')
        self.parser.add_option("-s", "--snippet", action="store_true", default=False, dest='show_snippet',
                               help='Show playbook snippet for specified plugin(s)')
        self.parser.add_option("-a", "--all", action="store_true", default=False, dest='all_plugins',
                               help='**For internal testing only** Show documentation for all plugins.')
        self.parser.add_option("-t", "--type", action="store", default='module', dest='type', type='choice',
                               help='Choose which plugin type (defaults to "module")',
                               choices=C.DOCUMENTABLE_PLUGINS)
        super(DocCLI, self).parse()

        if [self.options.all_plugins, self.options.list_dir, self.options.list_files, self.options.show_snippet].count(True) > 1:
            raise AnsibleOptionsError("Only one of -l, -F, -s or -a can be used at the same time.")

        display.verbosity = self.options.verbosity
예제 #11
0
파일: doc.py 프로젝트: ferhaty/ansible
    def parse(self):

        self.parser = CLI.base_parser(
            usage='usage: %prog [options] [module...]',
            epilog='Show Ansible module documentation',
        )

        self.parser.add_option(
            "-M",
            "--module-path",
            action="store",
            dest="module_path",
            default=C.DEFAULT_MODULE_PATH,
            help="Ansible modules/ directory")
        self.parser.add_option(
            "-l",
            "--list",
            action="store_true",
            default=False,
            dest='list_dir',
            help='List available modules')
        self.parser.add_option(
            "-s",
            "--snippet",
            action="store_true",
            default=False,
            dest='show_snippet',
            help='Show playbook snippet for specified module(s)')

        self.options, self.args = self.parser.parse_args()
        self.display.verbosity = self.options.verbosity
예제 #12
0
    def parse(self):

        self.parser = CLI.base_parser(
            usage="usage: %%prog [%s] [--help] [options] [ansible.cfg]" % "|".join(self.VALID_ACTIONS),
            epilog="\nSee '%s <command> --help' for more information on a specific command.\n\n" % os.path.basename(sys.argv[0]),
            desc="View, edit, and manage ansible configuration.",
        )
        self.parser.add_option('-c', '--config', dest='config_file', help="path to configuration file, defaults to first file found in precedence.")

        self.set_action()

        # options specific to self.actions
        if self.action == "list":
            self.parser.set_usage("usage: %prog list [options] ")
        if self.action == "dump":
            self.parser.add_option('--only-changed', dest='only_changed', action='store_true',
                                   help="Only show configurations that have changed from the default")
        elif self.action == "update":
            self.parser.add_option('-s', '--setting', dest='setting', help="config setting, the section defaults to 'defaults'")
            self.parser.set_usage("usage: %prog update [options] [-c ansible.cfg] -s '[section.]setting=value'")
        elif self.action == "search":
            self.parser.set_usage("usage: %prog update [options] [-c ansible.cfg] <search term>")

        self.options, self.args = self.parser.parse_args()
        display.verbosity = self.options.verbosity
예제 #13
0
    def _create_parser():
        # create parser for CLI options
        parser = CLI.base_parser(
            usage="%prog playbook.yml",
            connect_opts=True,
            meta_opts=True,
            runas_opts=True,
            subset_opts=True,
            check_opts=True,
            inventory_opts=True,
            runtask_opts=True,
            vault_opts=True,
            fork_opts=True,
            module_opts=True,
        )

        # specific opts from playbook
        parser.add_option('--list-tasks', dest='listtasks', action='store_true',
                          help="list all tasks that would be executed")
        parser.add_option('--list-tags', dest='listtags', action='store_true',
                          help="list all available tags")
        parser.add_option('--step', dest='step', action='store_true',
                          help="one-step-at-a-time: confirm each task before running")
        parser.add_option('--start-at-task', dest='start_at_task',
                          help="start the command at the task matching this name")
        parser.add_option('-p', '--password', dest='conn_pass',
                          help="Enter SSH password")
        parser.add_option('--become-password', dest='become_pass',
                          help="Enter privilege escalation password")

        return parser
예제 #14
0
    def parse(self):

        self.parser = CLI.base_parser(
            vault_opts=True,
            usage = "usage: %%prog [%s] [--help] [options] vaultfile.yml" % "|".join(self.VALID_ACTIONS),
            epilog = "\nSee '%s <command> --help' for more information on a specific command.\n\n" % os.path.basename(sys.argv[0])
        )

        self.set_action()

        # options specific to self.actions
        if self.action == "create":
            self.parser.set_usage("usage: %prog create [options] file_name")
        elif self.action == "decrypt":
            self.parser.set_usage("usage: %prog decrypt [options] file_name")
        elif self.action == "edit":
            self.parser.set_usage("usage: %prog edit [options] file_name")
        elif self.action == "view":
            self.parser.set_usage("usage: %prog view [options] file_name")
        elif self.action == "encrypt":
            self.parser.set_usage("usage: %prog encrypt [options] file_name")
        elif action == "rekey":
            self.parser.set_usage("usage: %prog rekey [options] file_name")

        self.options, self.args = self.parser.parse_args()
        self.display.verbosity = self.options.verbosity

        if len(self.args) == 0 or len(self.args) > 1:
            raise AnsibleOptionsError("Vault requires a single filename as a parameter")
예제 #15
0
파일: inventory.py 프로젝트: ernstp/ansible
    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)
예제 #16
0
    def parse(self):
        ''' create an options parser for bin/ansible '''

        self.parser = CLI.base_parser(
            usage='%prog <host-pattern> [options]',
            runas_opts=True,
            async_opts=True,
            output_opts=True,
            connect_opts=True,
            check_opts=True,
            runtask_opts=True,
            vault_opts=True,
        )

        # options unique to ansible ad-hoc
        self.parser.add_option('-a', '--args', dest='module_args',
            help="module arguments", default=C.DEFAULT_MODULE_ARGS)
        self.parser.add_option('-m', '--module-name', dest='module_name',
            help="module name to execute (default=%s)" % C.DEFAULT_MODULE_NAME,
            default=C.DEFAULT_MODULE_NAME)

        self.options, self.args = self.parser.parse_args()

        if len(self.args) != 1:
            raise AnsibleOptionsError("Missing target hosts")

        self.display.verbosity = self.options.verbosity
        self.validate_conflicts()

        return True
예제 #17
0
    def parse(self):

        self.parser = CLI.base_parser(
            usage='usage: %prog [options] [host|group]',
            epilog='Show Ansible inventory information, by default it uses the inventory script JSON format',
            inventory_opts=True,
            vault_opts=True,
            basedir_opts=True,
        )

        # remove unused default options
        self.parser.remove_option('--limit')
        self.parser.remove_option('--list-hosts')

        # Actions
        action_group = optparse.OptionGroup(self.parser, "Actions", "One of following must be used on invocation, ONLY ONE!")
        action_group.add_option("--list", action="store_true", default=False, dest='list', help='Output all hosts info, works as inventory script')
        action_group.add_option("--host", action="store", default=None, dest='host', help='Output specific host info, works as inventory script')
        action_group.add_option("--graph", action="store_true", default=False, dest='graph',
                                help='create inventory graph, if supplying pattern it must be a valid group name')
        self.parser.add_option_group(action_group)

        # graph
        self.parser.add_option("-y", "--yaml", action="store_true", default=False, dest='yaml',
                               help='Use YAML format instead of default JSON, ignored for --graph')
        self.parser.add_option("--vars", action="store_true", default=False, dest='show_vars',
                               help='Add vars to graph display, ignored unless used with --graph')

        # list
        self.parser.add_option("--export", action="store_true", default=C.INVENTORY_EXPORT, dest='export',
                               help="When doing an --list, represent in a way that is optimized for export,"
                                    "not as an accurate representation of how Ansible has processed it")
        # self.parser.add_option("--ignore-vars-plugins", action="store_true", default=False, dest='ignore_vars_plugins',
        #                       help="When doing an --list, skip vars data from vars plugins, by default, this would include group_vars/ and host_vars/")

        super(InventoryCLI, self).parse()

        display.verbosity = self.options.verbosity

        self.validate_conflicts(vault_opts=True)

        # there can be only one! and, at least, one!
        used = 0
        for opt in (self.options.list, self.options.host, self.options.graph):
            if opt:
                used += 1
        if used == 0:
            raise AnsibleOptionsError("No action selected, at least one of --host, --graph or --list needs to be specified.")
        elif used > 1:
            raise AnsibleOptionsError("Conflicting options used, only one of --host, --graph or --list can be used at the same time.")

        # set host pattern to default if not supplied
        if len(self.args) > 0:
            self.options.pattern = self.args[0]
        else:
            self.options.pattern = 'all'
예제 #18
0
    def run(self):

        super(ConsoleCLI, self).run()

        sshpass = None
        becomepass = 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, self.inventory, self.variable_manager = self._play_prereqs(
            self.options)

        hosts = CLI.get_host_list(self.inventory, self.options.subset,
                                  self.pattern)

        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()
예제 #19
0
    def _get_magic_variables(self, loader, play, host, task, include_hostvars,
                             include_delegate_to):
        '''
        Returns a dictionary of so-called "magic" variables in Ansible,
        which are special variables we set internally for use.
        '''

        variables = dict()
        variables['playbook_dir'] = loader.get_basedir()

        if host:
            variables['group_names'] = [
                group.name for group in host.get_groups()
            ]

            if self._inventory is not None:
                variables['groups'] = dict()
                for (group_name, group) in iteritems(self._inventory.groups):
                    variables['groups'][group_name] = [
                        h.name for h in group.get_hosts()
                    ]

                if include_hostvars:
                    hostvars_cache_entry = self._get_cache_entry(play=play)
                    if hostvars_cache_entry in HOSTVARS_CACHE:
                        hostvars = HOSTVARS_CACHE[hostvars_cache_entry]
                    else:
                        hostvars = HostVars(play=play,
                                            inventory=self._inventory,
                                            loader=loader,
                                            variable_manager=self)
                        HOSTVARS_CACHE[hostvars_cache_entry] = hostvars
                    variables['hostvars'] = hostvars
                    variables['vars'] = hostvars[host.get_name()]

        if task:
            if task._role:
                variables['role_path'] = task._role._role_path

        if self._inventory is not None:
            variables['inventory_dir'] = self._inventory.basedir()
            if play:
                # add the list of hosts in the play, as adjusted for limit/filters
                # DEPRECATED: play_hosts should be deprecated in favor of ansible_play_hosts,
                #             however this would take work in the templating engine, so for now
                #             we'll add both so we can give users something transitional to use
                host_list = [x.name for x in self._inventory.get_hosts()]
                variables['play_hosts'] = host_list
                variables['ansible_play_hosts'] = host_list

        # the 'omit' value alows params to be left out if the variable they are based on is undefined
        variables['omit'] = self._omit_token
        variables['ansible_version'] = CLI.version_info(gitinfo=False)

        return variables
예제 #20
0
    def parse(self):

        self.parser = CLI.base_parser(
            usage='usage: %prog [-l|-s] [options] [-t <plugin type] [plugin]',
            module_opts=True,
            desc="plugin documentation tool",
            epilog=
            "See man pages for Ansible CLI options or website for tutorials https://docs.ansible.com"
        )

        self.parser.add_option("-l",
                               "--list",
                               action="store_true",
                               default=False,
                               dest='list_dir',
                               help='List available plugins')
        self.parser.add_option(
            "-s",
            "--snippet",
            action="store_true",
            default=False,
            dest='show_snippet',
            help='Show playbook snippet for specified plugin(s)')
        self.parser.add_option(
            "-a",
            "--all",
            action="store_true",
            default=False,
            dest='all_plugins',
            help=
            '**For internal testing only** Show documentation for all plugins.'
        )
        self.parser.add_option(
            "-t",
            "--type",
            action="store",
            default='module',
            dest='type',
            type='choice',
            help='Choose which plugin type (defaults to "module")',
            choices=[
                'cache', 'callback', 'connection', 'inventory', 'lookup',
                'module', 'strategy', 'vars'
            ])

        super(DocCLI, self).parse()

        if [
                self.options.all_plugins, self.options.list_dir,
                self.options.show_snippet
        ].count(True) > 1:
            raise AnsibleOptionsError(
                "Only one of -l, -s or -a can be used at the same time.")

        display.verbosity = self.options.verbosity
예제 #21
0
    def _get_magic_variables(self, loader, play, host, task, include_hostvars,
                             include_delegate_to):
        '''
        Returns a dictionary of so-called "magic" variables in Ansible,
        which are special variables we set internally for use.
        '''

        variables = dict()
        variables['playbook_dir'] = loader.get_basedir()

        if host:
            variables['group_names'] = sorted([
                group.name for group in host.get_groups()
                if group.name != 'all'
            ])

            if self._inventory:
                variables['groups'] = self._inventory.get_group_dict()

        if play:
            variables['role_names'] = [r._role_name for r in play.roles]

        if task:
            if task._role:
                variables['role_name'] = task._role.get_name()
                variables['role_path'] = task._role._role_path
                variables['role_uuid'] = text_type(task._role._uuid)

        if self._inventory is not None:
            variables['inventory_dir'] = self._inventory.basedir()
            variables['inventory_file'] = self._inventory.src()
            if play:
                # add the list of hosts in the play, as adjusted for limit/filters
                # DEPRECATED: play_hosts should be deprecated in favor of ansible_play_hosts,
                #             however this would take work in the templating engine, so for now
                #             we'll add both so we can give users something transitional to use
                variables['play_hosts'] = [
                    x.name for x in self._inventory.get_hosts()
                ]
                variables['ansible_play_hosts'] = [
                    x.name for x in self._inventory.get_hosts(
                        pattern=play.hosts or 'all', ignore_restrictions=True)
                ]

        # the 'omit' value alows params to be left out if the variable they are based on is undefined
        variables['omit'] = self._omit_token
        variables['ansible_version'] = CLI.version_info(gitinfo=False)
        # Set options vars
        for option, option_value in iteritems(self._options_vars):
            variables[option] = option_value

        if self._hostvars is not None and include_hostvars:
            variables['hostvars'] = self._hostvars

        return variables
예제 #22
0
    def run(self):

        results = None

        super(InventoryCLI, self).run()

        # Initialize needed objects
        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.vm.get_vars(self.loader, 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.inventory.get_group('all')
            if self.options.yaml:
                results = self.yaml_inventory(top)
            else:
                results = self.json_inventory(top)
            results = self.dump(results)

        if results:
            display.display(results)
            exit(0)

        exit(1)
예제 #23
0
파일: vault.py 프로젝트: snowsky/ansible-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.vault_pass = CLI.read_vault_password_file(
                self.options.vault_password_file, loader)

        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 or self.options.ask_vault_pass:
            self.vault_pass = self.ask_vault_passwords()

        if not self.vault_pass:
            raise AnsibleOptionsError(
                "A password is required to use Ansible's Vault")

        if self.action == 'rekey':
            if not self.new_vault_pass:
                self.new_vault_pass = self.ask_new_vault_passwords()
            if not self.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.vault_pass)

        self.execute()

        # and restore umask
        os.umask(old_umask)
예제 #24
0
    def get_snippet_text(doc):

        text = []
        desc = CLI.tty_ify(" ".join(doc['short_description']))
        text.append("- name: %s" % (desc))
        text.append("  action: %s" % (doc['module']))

        for o in sorted(doc['options'].keys()):
            opt = doc['options'][o]
            desc = CLI.tty_ify(" ".join(opt['description']))

            if opt.get('required', False):
                s = o + "="
            else:
                s = o

            text.append("      %-20s   # %s" % (s, desc))
        text.append('')

        return "\n".join(text)
예제 #25
0
파일: doc.py 프로젝트: ferhaty/ansible
    def get_snippet_text(doc):

        text = []
        desc = CLI.tty_ify(" ".join(doc["short_description"]))
        text.append("- name: %s" % (desc))
        text.append("  action: %s" % (doc["module"]))

        for o in sorted(doc["options"].keys()):
            opt = doc["options"][o]
            desc = CLI.tty_ify(" ".join(opt["description"]))

            if opt.get("required", False):
                s = o + "="
            else:
                s = o

            text.append("      %-20s   # %s" % (s, desc))
        text.append("")

        return "\n".join(text)
예제 #26
0
    def get_snippet_text(doc):

        text = []
        desc = CLI.tty_ify(" ".join(doc['short_description']))
        text.append("- name: %s" % (desc))
        text.append("  action: %s" % (doc['module']))

        for o in sorted(doc['options'].keys()):
            opt = doc['options'][o]
            desc = CLI.tty_ify(" ".join(opt['description']))

            if opt.get('required', False):
                s = o + "="
            else:
                s = o

            text.append("      %-20s   # %s" % (s, desc))
        text.append('')

        return "\n".join(text)
 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)
예제 #28
0
    def parse(self):
        parser = CLI.base_parser(
            usage="%prog [options] playbook.yml [playbook2 ...]",
            connect_opts=True,
            meta_opts=True,
            runas_opts=True,
            subset_opts=True,
            check_opts=True,
            inventory_opts=True,
            runtask_opts=True,
            vault_opts=True,
            fork_opts=True,
            module_opts=True,
            desc=
            "Runs Ansible playbooks, executing the defined tasks on the targeted hosts.",
        )

        # ansible playbook specific opts
        parser.add_option('--list-tasks',
                          dest='listtasks',
                          action='store_true',
                          help="list all tasks that would be executed")
        parser.add_option('--list-tags',
                          dest='listtags',
                          action='store_true',
                          help="list all available tags")
        parser.add_option(
            '--step',
            dest='step',
            action='store_true',
            help="one-step-at-a-time: confirm each task before running")
        parser.add_option(
            '--start-at-task',
            dest='start_at_task',
            help="start the playbook at the task matching this name")

        # gear playbook specific opts
        parser.add_option('--callback-url',
                          dest='callback_url',
                          type='string',
                          default='/',
                          help="set a callback url. default is '/'")

        self.parser = parser
        super(PlaybookCLI, self).parse()

        if len(self.args) == 0:
            raise AnsibleOptionsError(
                "You must specify a playbook file to run")

        display.verbosity = self.options.verbosity
        self.validate_conflicts(runas_opts=True,
                                vault_opts=True,
                                fork_opts=True)
예제 #29
0
    def parse(self):

        self.parser = CLI.base_parser(
            usage='usage: %prog [options] [host|group]',
            epilog='Show Ansible inventory information, by default it uses the inventory script JSON format',
            inventory_opts=True,
            vault_opts=True,
            basedir_opts=True,
        )

        # Actions
        action_group = optparse.OptionGroup(self.parser, "Actions", "One of following must be used on invocation, ONLY ONE!")
        action_group.add_option("--list", action="store_true", default=False, dest='list', help='Output all hosts info, works as inventory script')
        action_group.add_option("--host", action="store", default=None, dest='host', help='Output specific host info, works as inventory script')
        action_group.add_option("--graph", action="store_true", default=False, dest='graph',
                                help='create inventory graph, if supplying pattern it must be a valid group name')
        self.parser.add_option_group(action_group)

        # Options

        # graph
        self.parser.add_option("-y", "--yaml", action="store_true", default=False, dest='yaml',
                               help='Use YAML format instead of default JSON, ignored for --graph')
        self.parser.add_option("--vars", action="store_true", default=False, dest='show_vars',
                               help='Add vars to graph display, ignored unless used with --graph')

        # list
        self.parser.add_option("--export", action="store_true", default=C.INVENTORY_EXPORT, dest='export',
                               help="When doing an --list, represent in a way that is optimized for export,"
                                    "not as an accurate representation of how Ansible has processed it")
        # self.parser.add_option("--ignore-vars-plugins", action="store_true", default=False, dest='ignore_vars_plugins',
        #                       help="When doing an --list, skip vars data from vars plugins, by default, this would include group_vars/ and host_vars/")

        super(InventoryCLI, self).parse()

        display.verbosity = self.options.verbosity

        self.validate_conflicts(vault_opts=True)

        # there can be only one! and, at least, one!
        used = 0
        for opt in (self.options.list, self.options.host, self.options.graph):
            if opt:
                used += 1
        if used == 0:
            raise AnsibleOptionsError("No action selected, at least one of --host, --graph or --list needs to be specified.")
        elif used > 1:
            raise AnsibleOptionsError("Conflicting options used, only one of --host, --graph or --list can be used at the same time.")

        # set host pattern to default if not supplied
        if len(self.args) > 0:
            self.options.pattern = self.args[0]
        else:
            self.options.pattern = 'all'
예제 #30
0
    def parse(self):
        ''' create an options parser for bin/ansible '''

        self.parser = CLI.base_parser(
            usage='%prog <host-pattern> [options]',
            connect_opts=True,
            vault_opts=True,
            runtask_opts=True,
            subset_opts=True,
            inventory_opts=True,
            module_opts=True,
        )

        # options unique to pull
        self.parser.add_option('--purge', default=False, action='store_true', help='purge checkout after playbook run')
        self.parser.add_option('-o', '--only-if-changed', dest='ifchanged', default=False, action='store_true',
            help='only run the playbook if the repository has been updated')
        self.parser.add_option('-s', '--sleep', dest='sleep', default=None,
            help='sleep for random interval (between 0 and n number of seconds) before starting. This is a useful way to disperse git requests')
        self.parser.add_option('-f', '--force', dest='force', default=False, action='store_true',
            help='run the playbook even if the repository could not be updated')
        self.parser.add_option('-d', '--directory', dest='dest', default=None, help='directory to checkout repository to')
        self.parser.add_option('-U', '--url', dest='url', default=None, help='URL of the playbook repository')
        self.parser.add_option('-C', '--checkout', dest='checkout',
            help='branch/tag/commit to checkout.  ' 'Defaults to behavior of repository module.')
        self.parser.add_option('--accept-host-key', default=False, dest='accept_host_key', action='store_true',
            help='adds the hostkey for the repo url if not already added')
        self.parser.add_option('-m', '--module-name', dest='module_name', default=self.DEFAULT_REPO_TYPE,
            help='Repository module name, which ansible will use to check out the repo. Default is %s.' % self.DEFAULT_REPO_TYPE)
        self.parser.add_option('--verify-commit', dest='verify', default=False, action='store_true',
            help='verify GPG signature of checked out commit, if it fails abort running the playbook.'
                 ' This needs the corresponding VCS module to support such an operation')

        self.options, self.args = self.parser.parse_args()

        if self.options.sleep:
            try:
                secs = random.randint(0,int(self.options.sleep))
                self.options.sleep = secs
            except ValueError:
                raise AnsibleOptionsError("%s is not a number." % self.options.sleep)

        if not self.options.url:
            raise AnsibleOptionsError("URL for repository not specified, use -h for help")

        if len(self.args) != 1:
            raise AnsibleOptionsError("Missing target hosts")

        if self.options.module_name not in self.SUPPORTED_REPO_MODULES:
            raise AnsibleOptionsError("Unsuported repo module %s, choices are %s" % (self.options.module_name, ','.join(self.SUPPORTED_REPO_MODULES)))

        self.display.verbosity = self.options.verbosity
        self.validate_conflicts(vault_opts=True)
예제 #31
0
파일: vault.py 프로젝트: waffleb051/ansible
    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()
예제 #32
0
파일: ndmtk.py 프로젝트: sebashmh/ndmtk
 def _load_auth_secrets(self, hosts=[], secrets=[]):
     for _safe, _lockpick in secrets:
         try:
             _safe_loader = DataLoader()
             _safe_lockpick = None
             try:
                 _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)
             except:
                 _safe_lockpick = CLI.setup_vault_secrets(
                     _safe_loader, [_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()
예제 #33
0
    def _get_magic_variables(self, loader, play, host, task, include_hostvars, include_delegate_to):
        '''
        Returns a dictionary of so-called "magic" variables in Ansible,
        which are special variables we set internally for use.
        '''

        variables = dict()
        variables['playbook_dir'] = loader.get_basedir()
        variables['ansible_playbook_python'] = sys.executable

        if host:
            # host already provides some magic vars via host.get_vars()
            if self._inventory:
                variables['groups']  = self._inventory.get_group_dict()

        if play:
            variables['role_names'] = [r._role_name for r in play.roles]

        if task:
            if task._role:
                variables['role_name'] = task._role.get_name()
                variables['role_path'] = task._role._role_path
                variables['role_uuid'] = text_type(task._role._uuid)

        if self._inventory is not None:
            variables['inventory_dir'] = self._inventory.basedir()
            variables['inventory_file'] = self._inventory.src()
            if play:
                templar = Templar(loader=loader)
                if templar.is_template(play.hosts):
                    pattern = 'all'
                else:
                    pattern = play.hosts or 'all'
                # add the list of hosts in the play, as adjusted for limit/filters
                variables['ansible_play_hosts_all'] = [x.name for x in self._inventory.get_hosts(pattern=pattern, ignore_restrictions=True)]
                variables['ansible_play_hosts'] = [x for x in variables['ansible_play_hosts_all'] if x not in play._removed_hosts]
                variables['ansible_play_batch'] = [x.name for x in self._inventory.get_hosts() if x.name not in play._removed_hosts]

                #DEPRECATED: play_hosts should be deprecated in favor of ansible_play_batch,
                #  however this would take work in the templating engine, so for now we'll add both
                variables['play_hosts'] = variables['ansible_play_batch']

        # the 'omit' value alows params to be left out if the variable they are based on is undefined
        variables['omit'] = self._omit_token
        variables['ansible_version'] = CLI.version_info(gitinfo=False)
        # Set options vars
        for option, option_value in iteritems(self._options_vars):
            variables[option] = option_value

        if self._hostvars is not None and include_hostvars:
            variables['hostvars'] = self._hostvars

        return variables
예제 #34
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     parser = CLI.base_parser(module_opts=True,
                              fork_opts=True,
                              runas_opts=True,
                              check_opts=True)
     self.options, _ = parser.parse_args([])
     self.variable_manager = VariableManager()
     self.loader = DataLoader()
     self.inventory = Inventory(loader=self.loader,
                                variable_manager=self.variable_manager)
     self.passwords = {}
예제 #35
0
 def setUp(self):
     self._parser = CLI.base_parser(
         runas_opts   = True,
         meta_opts    = True,
         runtask_opts = True,
         vault_opts   = True,
         async_opts   = True,
         connect_opts = True,
         subset_opts  = True,
         check_opts   = True,
         inventory_opts = True,
     )
예제 #36
0
    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()
예제 #37
0
 def setUp(self):
     self._parser = CLI.base_parser(
         runas_opts=True,
         meta_opts=True,
         runtask_opts=True,
         vault_opts=True,
         async_opts=True,
         connect_opts=True,
         subset_opts=True,
         check_opts=True,
         inventory_opts=True,
     )
예제 #38
0
def version():
    """
    Print version information.
    """
    echo('origin-ci-tool version:')
    echo('\toct ' + VERSION + '\n')
    echo('ansible version:')
    echo(''.join(['\t' + line + '\n' for line in CLI.version('ansible').splitlines()]))
    echo('openshift-ansible version:')
    echo('\t{}'.format(OPENSHIFT_ANSIBLE_VERSION))
    echo('\t  master/HEAD at {}\n'.format(OPENSHIFT_ANSIBLE_CHECKOUT))
    echo('openshift-ansible-contrib version:')
    echo('\tTODO')
예제 #39
0
파일: doc.py 프로젝트: RajeevNambiar/temp
    def get_snippet_text(self, doc):

        text = []
        desc = CLI.tty_ify(doc['short_description'])
        text.append("- name: %s" % (desc))
        text.append("  action: %s" % (doc['module']))
        pad = 31
        subdent = ''.join([" " for a in xrange(pad)])
        limit = display.columns - pad

        for o in sorted(doc['options'].keys()):
            opt = doc['options'][o]
            desc = CLI.tty_ify(" ".join(opt['description']))

            if opt.get('required', False):
                s = o + "="
            else:
                s = o
            text.append("      %-20s   # %s" % (s, textwrap.fill(desc, limit, subsequent_indent=subdent)))
        text.append('')

        return "\n".join(text)
예제 #40
0
    def __init__(self, tags: List[str] = None, skip_tags: List[str] = None):
        """

        :param tags: Only add plays and tasks tagged with these values
        :param skip_tags: Only add plays and tasks whose tags do not match these values
        """
        loader, inventory, variable_manager = CLI._play_prereqs()
        self.data_loader = loader
        self.inventory_manager = inventory
        self.variable_manager = variable_manager

        self.tags = tags or ["all"]
        self.skip_tags = skip_tags or []
예제 #41
0
def parser():
    parser = CLI.base_parser(
        runas_opts=True,
        meta_opts=True,
        runtask_opts=True,
        vault_opts=True,
        async_opts=True,
        connect_opts=True,
        subset_opts=True,
        check_opts=True,
        inventory_opts=True,
    )
    return parser
예제 #42
0
def run_playbook(task, inventory='hosts_dev', play_book='fetch_config.yml'):
    try:
        cli = PlaybookCLI([" ", '-i', INVENTORY_PATH + inventory, play_book])

        super(PlaybookCLI, cli).run()

        loader, inventory, variable_manager = cli._play_prereqs()

        CLI.get_host_list(inventory, context.CLIARGS['subset'])

        pbex = PlaybookExecutor(playbooks=context.CLIARGS['args'],
                                inventory=inventory,
                                variable_manager=variable_manager,
                                loader=loader,
                                passwords=None)

        pbex._tqm._stdout_callback = ResultCallback(task)
        pbex.run()
        return True
    except Exception as e:
        logger.error(e)
        return False
예제 #43
0
    def get_snippet_text(self, doc):

        text = []
        desc = CLI.tty_ify(doc['short_description'])
        text.append("- name: %s" % (desc))
        text.append("  action: %s" % (doc['module']))
        pad = 31
        subdent = ''.join([" " for a in xrange(pad)])
        limit = display.columns - pad

        for o in sorted(doc['options'].keys()):
            opt = doc['options'][o]
            desc = CLI.tty_ify(" ".join(opt['description']))

            if opt.get('required', False):
                s = o + "="
            else:
                s = o
            text.append("      %-20s   # %s" % (s, textwrap.fill(desc, limit, subsequent_indent=subdent)))
        text.append('')

        return "\n".join(text)
예제 #44
0
    def parse(self):

        self.parser = CLI.base_parser(
            usage="usage: %%prog [%s] [--help] [options] [ansible.cfg]" %
            "|".join(self.VALID_ACTIONS),
            epilog=
            "\nSee '%s <command> --help' for more information on a specific command.\n\n"
            % os.path.basename(sys.argv[0]),
            desc="View, edit, and manage ansible configuration.",
        )

        self.parser.add_option(
            '-c',
            '--config',
            dest='config_file',
            help=
            "path to configuration file, defaults to first file found in precedence."
        )

        self.set_action()

        # options specific to self.actions
        if self.action == "list":
            self.parser.set_usage("usage: %prog list [options] ")
        if self.action == "dump":
            self.parser.add_option(
                '--only-changed',
                dest='only_changed',
                action='store_true',
                help=
                "Only show configurations that have changed from the default")
            self.parser.set_usage(
                "usage: %prog dump [options] [-c ansible.cfg]")
        elif self.action == "view":
            self.parser.set_usage(
                "usage: %prog view [options] [-c ansible.cfg] ")
        elif self.action == "edit":
            self.parser.set_usage(
                "usage: %prog edit [options] [-c ansible.cfg]")
        elif self.action == "update":
            self.parser.add_option(
                '-s',
                '--setting',
                dest='setting',
                help="config setting, the section defaults to 'defaults'")
            self.parser.set_usage(
                "usage: %prog update [options] [-c ansible.cfg] -s '[section.]setting=value'"
            )

        self.options, self.args = self.parser.parse_args()
        display.verbosity = self.options.verbosity
예제 #45
0
파일: vault.py 프로젝트: yaojuin/ansible
    def parse(self):

        self.parser = CLI.base_parser(
            vault_opts=True,
            vault_rekey_opts=True,
            usage="usage: %%prog [%s] [options] [vaultfile.yml]" %
            "|".join(self.VALID_ACTIONS),
            desc="encryption/decryption utility for Ansible data files",
            epilog=
            "\nSee '%s <command> --help' for more information on a specific command.\n\n"
            % os.path.basename(sys.argv[0]))

        self.set_action()

        super(VaultCLI, self).parse()
        self.validate_conflicts(vault_opts=True, vault_rekey_opts=True)

        display.verbosity = self.options.verbosity

        if self.options.vault_ids:
            for vault_id in self.options.vault_ids:
                if u';' in vault_id:
                    raise AnsibleOptionsError(
                        "'%s' is not a valid vault id. The character ';' is not allowed in vault ids"
                        % vault_id)

        if self.action not in self.can_output:
            if len(self.args) == 0:
                raise AnsibleOptionsError(
                    "Vault requires at least one filename as a parameter")
        else:
            # This restriction should remain in place until it's possible to
            # load multiple YAML records from a single file, or it's too easy
            # to create an encrypted file that can't be read back in. But in
            # the meanwhile, "cat a b c|ansible-vault encrypt --output x" is
            # a workaround.
            if self.options.output_file and len(self.args) > 1:
                raise AnsibleOptionsError(
                    "At most one input file may be used with the --output option"
                )

        if self.action == 'encrypt_string':
            if '-' in self.args or len(
                    self.args) == 0 or self.options.encrypt_string_stdin_name:
                self.encrypt_string_read_stdin = True

            # TODO: prompting from stdin and reading from stdin seem mutually exclusive, but verify that.
            if self.options.encrypt_string_prompt and self.encrypt_string_read_stdin:
                raise AnsibleOptionsError(
                    'The --prompt option is not supported if also reading input from stdin'
                )
예제 #46
0
def install_dns_playbook():
    content = request.get_json(force=True)
    tagsexc = content['tagsexc']
    ipmanage = content['ipmanage']
    passwd = content['passwd']
    user = content['user']
    logging.info('runnig ansible-playbook install dns ' + tagsexc + ' ' +
                 ipmanage)
    file = open('app/ansible/hosts', 'w')
    file.write('[dnsservers]\n')
    file.write(ipmanage)
    file.close()
    loader = DataLoader()
    context.CLIARGS = ImmutableDict(tags={tagsexc},
                                    listtags=False,
                                    listtasks=False,
                                    listhosts=False,
                                    syntax=False,
                                    connection='ssh',
                                    module_path=None,
                                    forks=10,
                                    remote_user=user,
                                    private_key_file=None,
                                    ssh_common_args=None,
                                    ssh_extra_args=None,
                                    sftp_extra_args=None,
                                    scp_extra_args=None,
                                    become=True,
                                    become_method='sudo',
                                    become_user='******',
                                    verbosity=True,
                                    check=False,
                                    start_at_task=None,
                                    extra_vars={
                                        'ansible_ssh_user='******'',
                                        'ansible_ssh_pass='******'',
                                        'ansible_become_pass='******''
                                    })
    inventory = InventoryManager(loader=loader, sources=('app/ansible/hosts'))
    variable_manager = VariableManager(
        loader=loader,
        inventory=inventory,
        version_info=CLI.version_info(gitinfo=False))
    pbex = PlaybookExecutor(playbooks=['app/ansible/webadmindns.yml'],
                            inventory=inventory,
                            variable_manager=variable_manager,
                            loader=loader,
                            passwords={})
    results = pbex.run()
    db.session.commit()
    return jsonify({'status': results})
예제 #47
0
파일: vault.py 프로젝트: dkhode/ansible-1
    def parse(self):

        self.parser = CLI.base_parser(
            vault_opts=True,
            usage="usage: %%prog [%s] [--help] [options] vaultfile.yml" %
            "|".join(self.VALID_ACTIONS),
            epilog=
            "\nSee '%s <command> --help' for more information on a specific command.\n\n"
            % os.path.basename(sys.argv[0]))

        self.set_action()

        # options specific to self.actions
        if self.action == "create":
            self.parser.set_usage("usage: %prog create [options] file_name")
        elif self.action == "decrypt":
            self.parser.set_usage("usage: %prog decrypt [options] file_name")
        elif self.action == "edit":
            self.parser.set_usage("usage: %prog edit [options] file_name")
        elif self.action == "view":
            self.parser.set_usage("usage: %prog view [options] file_name")
        elif self.action == "encrypt":
            self.parser.set_usage("usage: %prog encrypt [options] file_name")
        elif self.action == "rekey":
            self.parser.set_usage("usage: %prog rekey [options] file_name")

        super(VaultCLI, self).parse()

        display.verbosity = self.options.verbosity

        can_output = ['encrypt', 'decrypt']

        if self.action not in can_output:
            if self.options.output_file:
                raise AnsibleOptionsError(
                    "The --output option can be used only with ansible-vault %s"
                    % '/'.join(can_output))
            if len(self.args) == 0:
                raise AnsibleOptionsError(
                    "Vault requires at least one filename as a parameter")
        else:
            # This restriction should remain in place until it's possible to
            # load multiple YAML records from a single file, or it's too easy
            # to create an encrypted file that can't be read back in. But in
            # the meanwhile, "cat a b c|ansible-vault encrypt --output x" is
            # a workaround.
            if self.options.output_file and len(self.args) > 1:
                raise AnsibleOptionsError(
                    "At most one input file may be used with the --output option"
                )
예제 #48
0
 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)
예제 #49
0
    def execute(self, playbook_source, hosts_source, extra_vars=None, tags=[]):
        context.CLIARGS = ImmutableDict(
            tags=tags,
            listtags=False,
            listtasks=False,
            listhosts=False,
            syntax=False,
            connection='ssh',
            module_path=None,
            forks=100,
            remote_user='******',
            private_key_file=None,
            ssh_common_args=None,
            ssh_extra_args=None,
            sftp_extra_args=None,
            scp_extra_args=None,
            become=False,
            become_method='sudo',
            become_user='******',
            verbosity=True,
            check=False,
            start_at_task=None,
        )
        with NamedTemporaryFile(mode='w') as hosts_file:
            hosts_file.write(hosts_source)
            hosts_file.seek(0)
            inventory = InventoryManager(loader=self.loader,
                                         sources=(hosts_file.name, ))

        variable_manager = VariableManager(
            loader=self.loader,
            inventory=inventory,
            version_info=CLI.version_info(gitinfo=False))
        if extra_vars:
            variable_manager._extra_vars = extra_vars

        playbook = os.path.abspath("playbooks/" + playbook_source)
        pbex = PlaybookExecutor(playbooks=[playbook],
                                inventory=inventory,
                                variable_manager=variable_manager,
                                loader=self.loader,
                                passwords={})
        result_callback = ResultCallback()
        pbex._tqm._stdout_callback = result_callback
        result_code = pbex.run()

        # Remove ansible tmpdir
        shutil.rmtree(constants.DEFAULT_LOCAL_TMP, True)

        return result_code, result_callback
예제 #50
0
    def _get_magic_variables(self, loader, play, host, task, include_hostvars, include_delegate_to):
        '''
        Returns a dictionary of so-called "magic" variables in Ansible,
        which are special variables we set internally for use.
        '''

        variables = dict()
        variables['playbook_dir'] = loader.get_basedir()
        variables['ansible_playbook_python'] = sys.executable

        if host:
            variables['group_names'] = sorted([group.name for group in host.get_groups() if group.name != 'all'])

            if self._inventory:
                variables['groups']  = self._inventory.get_group_dict()

        if play:
            variables['role_names'] = [r._role_name for r in play.roles]

        if task:
            if task._role:
                variables['role_name'] = task._role.get_name()
                variables['role_path'] = task._role._role_path
                variables['role_uuid'] = text_type(task._role._uuid)

        if self._inventory is not None:
            variables['inventory_dir'] = self._inventory.basedir()
            variables['inventory_file'] = self._inventory.src()
            if play:
                # add the list of hosts in the play, as adjusted for limit/filters
                variables['ansible_play_hosts_all'] = [x.name for x in self._inventory.get_hosts(pattern=play.hosts or 'all', ignore_restrictions=True)]
                variables['ansible_play_hosts'] = [x for x in variables['ansible_play_hosts_all'] if x not in play._removed_hosts]
                variables['ansible_play_batch'] = [x.name for x in self._inventory.get_hosts() if x.name not in play._removed_hosts]

                #DEPRECATED: play_hosts should be deprecated in favor of ansible_play_batch,
                #  however this would take work in the templating engine, so for now we'll add both
                variables['play_hosts'] = variables['ansible_play_batch']

        # the 'omit' value alows params to be left out if the variable they are based on is undefined
        variables['omit'] = self._omit_token
        variables['ansible_version'] = CLI.version_info(gitinfo=False)
        # Set options vars
        for option, option_value in iteritems(self._options_vars):
            variables[option] = option_value

        if self._hostvars is not None and include_hostvars:
            variables['hostvars'] = self._hostvars

        return variables
예제 #51
0
파일: vault.py 프로젝트: dkhode/ansible-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.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)
예제 #52
0
파일: doc.py 프로젝트: RajeevNambiar/temp
    def parse(self):

        self.parser = CLI.base_parser(
            usage='usage: %prog [options] [module...]',
            epilog='Show Ansible module documentation',
            module_opts=True,
        )

        self.parser.add_option("-l", "--list", action="store_true", default=False, dest='list_dir',
                help='List available modules')
        self.parser.add_option("-s", "--snippet", action="store_true", default=False, dest='show_snippet',
                help='Show playbook snippet for specified module(s)')

        self.options, self.args = self.parser.parse_args(self.args[1:])
        display.verbosity = self.options.verbosity
예제 #53
0
    def parse(self):

        self.parser = CLI.base_parser(
            usage='usage: %prog [options] [module...]',
            epilog='Show Ansible module documentation',
            module_opts=True,
        )

        self.parser.add_option("-l", "--list", action="store_true", default=False, dest='list_dir',
                help='List available modules')
        self.parser.add_option("-s", "--snippet", action="store_true", default=False, dest='show_snippet',
                help='Show playbook snippet for specified module(s)')

        self.options, self.args = self.parser.parse_args(self.args[1:])
        display.verbosity = self.options.verbosity
예제 #54
0
    def parse(self):

        # create parser for CLI options
        parser = CLI.base_parser(
            usage="%prog playbook.yml",
            connect_opts=True,
            meta_opts=True,
            runas_opts=True,
            subset_opts=True,
            check_opts=True,
            inventory_opts=True,
            runtask_opts=True,
            vault_opts=True,
            fork_opts=True,
            module_opts=True,
        )

        # ansible playbook specific opts
        parser.add_option('--list-tasks',
                          dest='listtasks',
                          action='store_true',
                          help="list all tasks that would be executed")
        parser.add_option('--list-tags',
                          dest='listtags',
                          action='store_true',
                          help="list all available tags")
        parser.add_option(
            '--step',
            dest='step',
            action='store_true',
            help="one-step-at-a-time: confirm each task before running")
        parser.add_option(
            '--start-at-task',
            dest='start_at_task',
            help="start the playbook at the task matching this name")

        self.options, self.args = parser.parse_args(self.args[1:])

        self.parser = parser

        if len(self.args) == 0:
            raise AnsibleOptionsError(
                "You must specify a playbook file to run")

        display.verbosity = self.options.verbosity
        self.validate_conflicts(runas_opts=True,
                                vault_opts=True,
                                fork_opts=True)
예제 #55
0
def _run_ansible(playbook: str, variables: dict = None):
    if variables is None:
        variables = {}
    from ansible import context
    from ansible.cli import CLI
    from ansible.module_utils.common.collections import ImmutableDict
    from ansible.executor.playbook_executor import PlaybookExecutor
    from ansible.parsing.dataloader import DataLoader
    from ansible.inventory.manager import InventoryManager
    from ansible.vars.manager import VariableManager

    loader = DataLoader()
    context.CLIARGS = ImmutableDict(
        tags={},
        listtags=False,
        listtasks=False,
        listhosts=False,
        syntax=False,
        connection="ssh",
        module_path=None,
        forks=100,
        remote_user="******",
        private_key_file=None,
        ssh_common_args=None,
        ssh_extra_args=None,
        sftp_extra_args=None,
        scp_extra_args=None,
        become=True,
        become_method="sudo",
        become_user="******",
        verbosity=True,
        check=False,
        start_at_task=None,
    )
    inventory = InventoryManager(loader=loader, sources=())
    variable_manager = VariableManager(
        loader=loader,
        inventory=inventory,
        version_info=CLI.version_info(gitinfo=False))
    variable_manager._extra_vars = variables
    pbex = PlaybookExecutor(
        playbooks=[os.path.join(SETUP_DIR, "ansible", playbook)],
        inventory=inventory,
        variable_manager=variable_manager,
        loader=loader,
        passwords={},
    )
    return pbex.run()
예제 #56
0
    def _get_magic_variables(self, loader, play, host, task, include_hostvars, include_delegate_to):
        '''
        Returns a dictionary of so-called "magic" variables in Ansible,
        which are special variables we set internally for use.
        '''

        variables = dict()
        variables['playbook_dir'] = loader.get_basedir()

        if host:
            variables['group_names'] = [group.name for group in host.get_groups()]

            if self._inventory is not None:
                variables['groups']  = dict()
                for (group_name, group) in iteritems(self._inventory.groups):
                    variables['groups'][group_name] = [h.name for h in group.get_hosts()]

                if include_hostvars:
                    hostvars_cache_entry = self._get_cache_entry(play=play)
                    if hostvars_cache_entry in HOSTVARS_CACHE:
                        hostvars = HOSTVARS_CACHE[hostvars_cache_entry]
                    else:
                        hostvars = HostVars(play=play, inventory=self._inventory, loader=loader, variable_manager=self)
                        HOSTVARS_CACHE[hostvars_cache_entry] = hostvars
                    variables['hostvars'] = hostvars
                    variables['vars'] = hostvars[host.get_name()]

        if task:
            if task._role:
                variables['role_path'] = task._role._role_path

        if self._inventory is not None:
            variables['inventory_dir'] = self._inventory.basedir()
            if play:
                # add the list of hosts in the play, as adjusted for limit/filters
                # DEPRECATED: play_hosts should be deprecated in favor of ansible_play_hosts,
                #             however this would take work in the templating engine, so for now
                #             we'll add both so we can give users something transitional to use
                host_list = [x.name for x in self._inventory.get_hosts()]
                variables['play_hosts'] = host_list
                variables['ansible_play_hosts'] = host_list

        # the 'omit' value alows params to be left out if the variable they are based on is undefined
        variables['omit'] = self._omit_token
        variables['ansible_version'] = CLI.version_info(gitinfo=False)

        return variables
예제 #57
0
    def run(self):

        super(ConsoleCLI, self).run()

        sshpass = None
        becomepass = 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, self.inventory, self.variable_manager = self._play_prereqs(self.options)

        hosts = CLI.get_host_list(self.inventory, self.options.subset, self.pattern)

        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()
예제 #58
0
    def parse(self):

        self.parser = CLI.base_parser(
            vault_opts=True,
            usage="usage: %%prog [%s] [--help] [options] vaultfile.yml" % "|".join(self.VALID_ACTIONS),
            epilog="\nSee '%s <command> --help' for more information on a specific command.\n\n"
            % os.path.basename(sys.argv[0]),
        )

        self.set_action()

        # options specific to self.actions
        if self.action == "create":
            self.parser.set_usage("usage: %prog create [options] file_name")
        elif self.action == "decrypt":
            self.parser.set_usage("usage: %prog decrypt [options] file_name")
        elif self.action == "edit":
            self.parser.set_usage("usage: %prog edit [options] file_name")
        elif self.action == "view":
            self.parser.set_usage("usage: %prog view [options] file_name")
        elif self.action == "encrypt":
            self.parser.set_usage("usage: %prog encrypt [options] file_name")
        elif self.action == "rekey":
            self.parser.set_usage("usage: %prog rekey [options] file_name")

        self.options, self.args = self.parser.parse_args()
        self.display.verbosity = self.options.verbosity

        can_output = ["encrypt", "decrypt"]

        if self.action not in can_output:
            if self.options.output_file:
                raise AnsibleOptionsError(
                    "The --output option can be used only with ansible-vault %s" % "/".join(can_output)
                )
            if len(self.args) == 0:
                raise AnsibleOptionsError("Vault requires at least one filename as a parameter")
        else:
            # This restriction should remain in place until it's possible to
            # load multiple YAML records from a single file, or it's too easy
            # to create an encrypted file that can't be read back in. But in
            # the meanwhile, "cat a b c|ansible-vault encrypt --output x" is
            # a workaround.
            if self.options.output_file and len(self.args) > 1:
                raise AnsibleOptionsError("At most one input file may be used with the --output option")
예제 #59
0
파일: galaxy.py 프로젝트: ernstp/ansible
    def parse(self):
        ''' create an options parser for bin/ansible '''

        self.parser = CLI.base_parser(
            usage="usage: %%prog [%s] [--help] [options] ..." % "|".join(self.VALID_ACTIONS),
            epilog="\nSee '%s <command> --help' for more information on a specific command.\n\n" % os.path.basename(sys.argv[0])
        )

        # common
        self.parser.add_option('-s', '--server', dest='api_server', default=C.GALAXY_SERVER, help='The API server destination')
        self.parser.add_option('-c', '--ignore-certs', action='store_true', dest='ignore_certs', default=C.GALAXY_IGNORE_CERTS,
                               help='Ignore SSL certificate validation errors.')
        self.set_action()

        super(GalaxyCLI, self).parse()

        display.verbosity = self.options.verbosity
        self.galaxy = Galaxy(self.options)