当前位置: 首页>>代码示例>>Python>>正文


Python cli.CLI类代码示例

本文整理汇总了Python中ansible.cli.CLI的典型用法代码示例。如果您正苦于以下问题:Python CLI类的具体用法?Python CLI怎么用?Python CLI使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了CLI类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_snippet_text

    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)
开发者ID:ernstp,项目名称:ansible,代码行数:27,代码来源:doc.py

示例2: run

    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)
开发者ID:KMK-ONLINE,项目名称:ansible,代码行数:32,代码来源:vault.py

示例3: get_snippet_text

    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)
开发者ID:LukeInkster,项目名称:PythonCorpus,代码行数:25,代码来源:doc.py

示例4: get_man_text

    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)
开发者ID:victron,项目名称:paramiko_ssh-i,代码行数:59,代码来源:doc.py

示例5: __init__

 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)
开发者ID:willthames,项目名称:ansible-inventory-grapher,代码行数:9,代码来源:inventory.py

示例6: parse

    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")
开发者ID:victron,项目名称:paramiko_ssh-i,代码行数:29,代码来源:vault.py

示例7: run

    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)
开发者ID:ernstp,项目名称:ansible,代码行数:60,代码来源:inventory.py

示例8: parse

    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
开发者ID:ernstp,项目名称:ansible,代码行数:25,代码来源:doc.py

示例9: parse

    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)
开发者ID:awiddersheim,项目名称:ansible,代码行数:25,代码来源:console.py

示例10: parser

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
开发者ID:ernstp,项目名称:ansible,代码行数:7,代码来源:test_play_context.py

示例11: parse

    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
开发者ID:awiddersheim,项目名称:ansible,代码行数:26,代码来源:doc.py

示例12: parse

    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
开发者ID:ferhaty,项目名称:ansible,代码行数:31,代码来源:doc.py

示例13: _create_parser

    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
开发者ID:smoothify,项目名称:able,代码行数:31,代码来源:global_options.py

示例14: parse

    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
开发者ID:victron,项目名称:paramiko_ssh-i,代码行数:30,代码来源:adhoc.py

示例15: parse

    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
开发者ID:awiddersheim,项目名称:ansible,代码行数:25,代码来源:config.py


注:本文中的ansible.cli.CLI类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。