示例#1
0
    def init_parser(self):
        super(ConsoleCLI, self).init_parser(
            desc="REPL console for executing Ansible tasks.",
            epilog=
            "This is not a live session/connection: each task is executed in the background and returns its results."
        )
        opt_help.add_runas_options(self.parser)
        opt_help.add_inventory_options(self.parser)
        opt_help.add_connect_options(self.parser)
        opt_help.add_check_options(self.parser)
        opt_help.add_vault_options(self.parser)
        opt_help.add_fork_options(self.parser)
        opt_help.add_module_options(self.parser)
        opt_help.add_basedir_options(self.parser)
        opt_help.add_runtask_options(self.parser)
        opt_help.add_tasknoplay_options(self.parser)

        # options unique to shell
        self.parser.add_argument('pattern',
                                 help='host pattern',
                                 metavar='pattern',
                                 default='all',
                                 nargs='?')
        self.parser.add_argument(
            '--step',
            dest='step',
            action='store_true',
            help="one-step-at-a-time: confirm each task before running")
示例#2
0
    def init_parser(self):

        # create parser for CLI options
        super(PlaybookCLI, self).init_parser(
            usage="%prog [options] playbook.yml [playbook2 ...]",
            desc="Runs Ansible playbooks, executing the defined tasks on the targeted hosts.")

        opt_help.add_connect_options(self.parser)
        opt_help.add_meta_options(self.parser)
        opt_help.add_runas_options(self.parser)
        opt_help.add_subset_options(self.parser)
        opt_help.add_check_options(self.parser)
        opt_help.add_inventory_options(self.parser)
        opt_help.add_runtask_options(self.parser)
        opt_help.add_vault_options(self.parser)
        opt_help.add_fork_options(self.parser)
        opt_help.add_module_options(self.parser)

        # ansible playbook specific opts
        self.parser.add_argument('--list-tasks', dest='listtasks', action='store_true',
                                 help="list all tasks that would be executed")
        self.parser.add_argument('--list-tags', dest='listtags', action='store_true',
                                 help="list all available tags")
        self.parser.add_argument('--step', dest='step', action='store_true',
                                 help="one-step-at-a-time: confirm each task before running")
        self.parser.add_argument('--start-at-task', dest='start_at_task',
                                 help="start the playbook at the task matching this name")
        self.parser.add_argument('args', help='Playbook(s)', metavar='playbook', nargs='+')
示例#3
0
    def init_parser(self):
        ''' create an options parser for bin/ansible '''
        super(AdHocCLI, self).init_parser(usage='%prog <host-pattern> [options]',
                                          desc="Define and run a single task 'playbook' against"
                                          " a set of hosts",
                                          epilog="Some modules do not make sense in Ad-Hoc (include,"
                                          " meta, etc)")

        opt_help.add_runas_options(self.parser)
        opt_help.add_inventory_options(self.parser)
        opt_help.add_async_options(self.parser)
        opt_help.add_output_options(self.parser)
        opt_help.add_connect_options(self.parser)
        opt_help.add_check_options(self.parser)
        opt_help.add_runtask_options(self.parser)
        opt_help.add_vault_options(self.parser)
        opt_help.add_fork_options(self.parser)
        opt_help.add_module_options(self.parser)
        opt_help.add_basedir_options(self.parser)

        # options unique to ansible ad-hoc
        self.parser.add_argument('-a', '--args', dest='module_args',
                                 help="module arguments", default=C.DEFAULT_MODULE_ARGS)
        self.parser.add_argument('-m', '--module-name', dest='module_name',
                                 help="module name to execute (default=%s)" % C.DEFAULT_MODULE_NAME,
                                 default=C.DEFAULT_MODULE_NAME)
        self.parser.add_argument('args', metavar='pattern', help='host pattern')
示例#4
0
    def init_parser(self):
        ''' create an options parser for bin/ansible '''

        super(PullCLI, self).init_parser(
            usage='%prog -U <repository> [options] [<playbook.yml>]',
            desc="pulls playbooks from a VCS repo and executes them for the local host")

        # Do not add check_options as there's a conflict with --checkout/-C
        opt_help.add_connect_options(self.parser)
        opt_help.add_vault_options(self.parser)
        opt_help.add_runtask_options(self.parser)
        opt_help.add_subset_options(self.parser)
        opt_help.add_inventory_options(self.parser)
        opt_help.add_module_options(self.parser)
        opt_help.add_runas_prompt_options(self.parser)

        self.parser.add_argument('args', help='Playbook(s)', metavar='playbook.yml', nargs='*')

        # options unique to pull
        self.parser.add_argument('--purge', default=False, action='store_true', help='purge checkout after playbook run')
        self.parser.add_argument('-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_argument('-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_argument('-f', '--force', dest='force', default=False, action='store_true',
                                 help='run the playbook even if the repository could not be updated')
        self.parser.add_argument('-d', '--directory', dest='dest', default=None,
                                 help='absolute path of repository checkout directory (relative paths are not supported)')
        self.parser.add_argument('-U', '--url', dest='url', default=None, help='URL of the playbook repository')
        self.parser.add_argument('--full', dest='fullclone', action='store_true', help='Do a full clone, instead of a shallow one.')
        self.parser.add_argument('-C', '--checkout', dest='checkout',
                                 help='branch/tag/commit to checkout. Defaults to behavior of repository module.')
        self.parser.add_argument('--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_argument('-m', '--module-name', dest='module_name', default=self.DEFAULT_REPO_TYPE,
                                 help='Repository module name, which ansible will use to check out the repo. Choices are %s. Default is %s.'
                                      % (self.REPO_CHOICES, self.DEFAULT_REPO_TYPE))
        self.parser.add_argument('--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.parser.add_argument('--clean', dest='clean', default=False, action='store_true',
                                 help='modified files in the working repository will be discarded')
        self.parser.add_argument('--track-subs', dest='tracksubs', default=False, action='store_true',
                                 help='submodules will track the latest changes. This is equivalent to specifying the --remote flag to git submodule update')
        # add a subset of the check_opts flag group manually, as the full set's
        # shortcodes conflict with above --checkout/-C
        self.parser.add_argument("--check", default=False, dest='check', action='store_true',
                                 help="don't make any changes; instead, try to predict some of the changes that may occur")
        self.parser.add_argument("--diff", default=C.DIFF_ALWAYS, dest='diff', action='store_true',
                                 help="when changing (small) files and templates, show the differences in those files; works great with --check")
示例#5
0
def parser():
    parser = opt_help.create_base_parser('testparser')

    opt_help.add_runas_options(parser)
    opt_help.add_meta_options(parser)
    opt_help.add_runtask_options(parser)
    opt_help.add_vault_options(parser)
    opt_help.add_async_options(parser)
    opt_help.add_connect_options(parser)
    opt_help.add_subset_options(parser)
    opt_help.add_check_options(parser)
    opt_help.add_inventory_options(parser)

    return parser
示例#6
0
    def init_parser(self):
        ''' create an options parser for bin/ansible '''
        super(AdHocCLI, self).init_parser(
            usage='%prog <host-pattern> [options]',
            desc=
            "Define and run a single task 'playbook' against a set of hosts",
            epilog=
            "Some actions do not make sense in Ad-Hoc (include, meta, etc)")

        opt_help.add_runas_options(self.parser)
        opt_help.add_inventory_options(self.parser)
        opt_help.add_async_options(self.parser)
        opt_help.add_output_options(self.parser)
        opt_help.add_connect_options(self.parser)
        opt_help.add_check_options(self.parser)
        opt_help.add_runtask_options(self.parser)
        opt_help.add_vault_options(self.parser)
        opt_help.add_fork_options(self.parser)
        opt_help.add_module_options(self.parser)
        opt_help.add_basedir_options(self.parser)
        opt_help.add_tasknoplay_options(self.parser)

        # options unique to ansible ad-hoc
        self.parser.add_argument(
            '-a',
            '--args',
            dest='module_args',
            help=
            "The action's options in space separated k=v format: -a 'opt1=val1 opt2=val2' "
            "or a json string: -a '{\"opt1\": \"val1\", \"opt2\": \"val2\"}'",
            default=C.DEFAULT_MODULE_ARGS)
        self.parser.add_argument(
            '-m',
            '--module-name',
            dest='module_name',
            help="Name of the action to execute (default=%s)" %
            C.DEFAULT_MODULE_NAME,
            default=C.DEFAULT_MODULE_NAME)
        self.parser.add_argument('args',
                                 metavar='pattern',
                                 help='host pattern')
示例#7
0
    def init_parser(self):
        super(InventoryCLI, self).init_parser(
            usage='usage: %prog [options] [host|group]',
            epilog='Show Ansible inventory information, by default it uses the inventory script JSON format')

        opt_help.add_inventory_options(self.parser)
        opt_help.add_vault_options(self.parser)
        opt_help.add_basedir_options(self.parser)

        # remove unused default options
        self.parser.add_argument('-l', '--limit', help=argparse.SUPPRESS, action=opt_help.UnrecognizedArgument, nargs='?')
        self.parser.add_argument('--list-hosts', help=argparse.SUPPRESS, action=opt_help.UnrecognizedArgument)

        self.parser.add_argument('args', metavar='host|group', nargs='?')

        # Actions
        action_group = self.parser.add_argument_group("Actions", "One of following must be used on invocation, ONLY ONE!")
        action_group.add_argument("--list", action="store_true", default=False, dest='list', help='Output all hosts info, works as inventory script')
        action_group.add_argument("--host", action="store", default=None, dest='host', help='Output specific host info, works as inventory script')
        action_group.add_argument("--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_argument_group(action_group)

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

        # list
        self.parser.add_argument("--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_argument('--output', default=None, dest='output_file',
                                 help="When doing --list, send the inventory to a file instead of to the screen")
示例#8
0
    def init_parser(self):
        super(VaultCLI, self).init_parser(
            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])
        )

        common = opt_help.argparse.ArgumentParser(add_help=False)
        opt_help.add_vault_options(common)
        opt_help.add_verbosity_options(common)

        subparsers = self.parser.add_subparsers(dest='action')
        subparsers.required = True

        output = opt_help.argparse.ArgumentParser(add_help=False)
        output.add_argument('--output', default=None, dest='output_file',
                            help='output file name for encrypt or decrypt; use - for stdout',
                            type=opt_help.unfrack_path())

        # For encrypting actions, we can also specify which of multiple vault ids should be used for encrypting
        vault_id = opt_help.argparse.ArgumentParser(add_help=False)
        vault_id.add_argument('--encrypt-vault-id', default=[], dest='encrypt_vault_id',
                              action='store', type=str,
                              help='the vault id used to encrypt (required if more than one vault-id is provided)')

        create_parser = subparsers.add_parser('create', help='Create new vault encrypted file', parents=[vault_id, common])
        create_parser.set_defaults(func=self.execute_create)
        create_parser.add_argument('args', help='Filename', metavar='file_name', nargs='*')

        decrypt_parser = subparsers.add_parser('decrypt', help='Decrypt vault encrypted file', parents=[output, common])
        decrypt_parser.set_defaults(func=self.execute_decrypt)
        decrypt_parser.add_argument('args', help='Filename', metavar='file_name', nargs='*')

        edit_parser = subparsers.add_parser('edit', help='Edit vault encrypted file', parents=[vault_id, common])
        edit_parser.set_defaults(func=self.execute_edit)
        edit_parser.add_argument('args', help='Filename', metavar='file_name', nargs='*')

        view_parser = subparsers.add_parser('view', help='View vault encrypted file', parents=[common])
        view_parser.set_defaults(func=self.execute_view)
        view_parser.add_argument('args', help='Filename', metavar='file_name', nargs='*')

        encrypt_parser = subparsers.add_parser('encrypt', help='Encrypt YAML file', parents=[common, output, vault_id])
        encrypt_parser.set_defaults(func=self.execute_encrypt)
        encrypt_parser.add_argument('args', help='Filename', metavar='file_name', nargs='*')

        enc_str_parser = subparsers.add_parser('encrypt_string', help='Encrypt a string', parents=[common, output, vault_id])
        enc_str_parser.set_defaults(func=self.execute_encrypt_string)
        enc_str_parser.add_argument('args', help='String to encrypt', metavar='string_to_encrypt', nargs='*')
        enc_str_parser.add_argument('-p', '--prompt', dest='encrypt_string_prompt',
                                    action='store_true',
                                    help="Prompt for the string to encrypt")
        enc_str_parser.add_argument('--show-input', dest='show_string_input', default=False, action='store_true',
                                    help='Do not hide input when prompted for the string to encrypt')
        enc_str_parser.add_argument('-n', '--name', dest='encrypt_string_names',
                                    action='append',
                                    help="Specify the variable name")
        enc_str_parser.add_argument('--stdin-name', dest='encrypt_string_stdin_name',
                                    default=None,
                                    help="Specify the variable name for stdin")

        rekey_parser = subparsers.add_parser('rekey', help='Re-key a vault encrypted file', parents=[common, vault_id])
        rekey_parser.set_defaults(func=self.execute_rekey)
        rekey_new_group = rekey_parser.add_mutually_exclusive_group()
        rekey_new_group.add_argument('--new-vault-password-file', default=None, dest='new_vault_password_file',
                                     help="new vault password file for rekey", type=opt_help.unfrack_path())
        rekey_new_group.add_argument('--new-vault-id', default=None, dest='new_vault_id', type=str,
                                     help='the new vault identity to use for rekey')
        rekey_parser.add_argument('args', help='Filename', metavar='file_name', nargs='*')
示例#9
0
    def _add_my_options(self):
        """
        Add some of my options to the parser
        :return:
        """
        self.parser.prog = __prog__

        self.parser.add_argument(
            "-i",
            "--inventory",
            dest="inventory",
            action="append",
            help="specify inventory host path or comma separated host list.",
        )

        self.parser.add_argument(
            "--include-role-tasks",
            dest="include_role_tasks",
            action="store_true",
            default=False,
            help="Include the tasks of the role in the graph.",
        )

        self.parser.add_argument(
            "-s",
            "--save-dot-file",
            dest="save_dot_file",
            action="store_true",
            default=False,
            help="Save the dot file used to generate the graph.",
        )

        self.parser.add_argument(
            "--view",
            action="store_true",
            default=False,
            help=
            "Automatically open the resulting SVG file with your system’s default viewer application for the file type",
        )

        self.parser.add_argument(
            "-o",
            "--output-file-name",
            dest="output_filename",
            help=
            "Output filename without the '.svg' extension. Default: <playbook>.svg",
        )

        self.parser.add_argument(
            "--open-protocol-handler",
            dest="open_protocol_handler",
            choices=list(OPEN_PROTOCOL_HANDLERS.keys()),
            default="default",
            help=
            """The protocol to use to open the nodes when double-clicking on them in your SVG 
                                 viewer. Your SVG viewer must support double-click and Javascript. 
                                 The supported values are 'default', 'vscode' and 'custom'. 
                                 For 'default', the URL will be the path to the file or folders. When using a browser, 
                                 it will open or download them. 
                                 For 'vscode', the folders and files will be open with VSCode.
                                 For 'custom', you need to set a custom format with --open-protocol-custom-formats.
                                 """,
        )

        self.parser.add_argument(
            "--open-protocol-custom-formats",
            dest="open_protocol_custom_formats",
            default=None,
            help=
            """The custom formats to use as URLs for the nodes in the graph. Required if
                                 --open-protocol-handler is set to custom.
                                 You should provide a JSON formatted string like: {"file": "", "folder": ""}.
                                 Example: If you want to open folders (roles) inside the browser and files (tasks) in
                                 vscode, set this to 
                                 '{"file": "vscode://file/{path}:{line}:{column}", "folder": "{path}"}'
                                 """,
        )

        self.parser.add_argument(
            "--group-roles-by-name",
            action="store_true",
            default=False,
            help=
            "When rendering the graph, only a single role will be display for all roles having the same names.",
        )

        self.parser.add_argument(
            "--version",
            action="version",
            version=
            f"{__prog__} {__version__} (with ansible {ansible_version})",
        )

        self.parser.add_argument(
            "playbook_filenames",
            help="Playbook(s) to graph",
            metavar="playbooks",
            nargs="+",
        )

        # Use ansible helper to add some default options also
        option_helpers.add_subset_options(self.parser)
        option_helpers.add_vault_options(self.parser)
        option_helpers.add_runtask_options(self.parser)