Example #1
0
    def parse(self):
        # create parser for CLI options
        parser = CLI.base_parser(
            usage="%s [options] playbook.yml" % __prog__,
            subset_opts=True,
            vault_opts=True,
            runtask_opts=True,
            desc="Make graph from your Playbook.",
        )

        parser.add_option(
            '-i',
            '--inventory',
            dest='inventory',
            action="append",
            help=
            "specify inventory host path (default=[%s]) or comma separated host list. "
        )

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

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

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

        parser.version = "%s %s (with ansible %s)" % (__prog__, __version__,
                                                      ansible_version)

        self.parser = parser

        super(PlaybookGrapherCLI, self).parse()

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

        if len(self.args) > 1:
            raise AnsibleOptionsError(
                "You must specify only one playbook file to graph.")

        display.verbosity = self.options.verbosity

        if self.options.output_filename is None:
            self.options.output_filename = os.path.splitext(
                ntpath.basename(self.args[0]))[0]
Example #2
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
Example #3
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

        if len(self.args) == 0:
            raise AnsibleOptionsError(
                "Vault requires at least one filename as a parameter")
Example #4
0
    def parse(self):
        """
        Add the grapher specific options
        FIXME: In Ansible 2.9, optparse will be replaced by argparse https://github.com/ansible/ansible/pull/50610
        :return:
        :rtype:
        """
        parser = CLI.base_parser(
            usage="%s [options] playbook.yml" % __prog__,
            subset_opts=True,
            vault_opts=True,
            runtask_opts=True,
            desc="Make graph from your Playbook.",
        )

        _add_my_options(parser)

        self.parser = parser

        super(PlaybookGrapherCLI, self).parse()

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

        if len(self.args) > 1:
            raise AnsibleOptionsError(
                "You must specify only one playbook file to graph.")

        if self.options.output_filename is None:
            # use the playbook name (without the extension) as output filename
            self.options.output_filename = os.path.splitext(
                ntpath.basename(self.args[0]))[0]
Example #5
0
    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
Example #6
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
Example #7
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
Example #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)
Example #9
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,
            fork_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(runas_opts=True, vault_opts=True)

        return True
Example #10
0
    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
Example #11
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")
Example #12
0
    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("-j", "--json", action="store_true", default=False, dest='json_dump',
                               help='**For internal testing only** Dump json metadata 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.json_dump, self.options.list_dir, self.options.list_files, self.options.show_snippet].count(True) > 1:
            raise AnsibleOptionsError("Only one of -l, -F, -s, -j or -a can be used at the same time.")

        display.verbosity = self.options.verbosity
Example #13
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
Example #14
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)
Example #15
0
    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
Example #16
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)')

        super(DocCLI, self).parse()

        display.verbosity = self.options.verbosity
Example #17
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
Example #18
0
    def parse(self):
        ''' create an options parser for bin/ansible '''

        self.parser = CLI.base_parser(
            usage='%prog -U <repository> [options]',
            connect_opts=True,
            vault_opts=True,
            runtask_opts=True,
            subset_opts=True,
            inventory_opts=True,
            module_opts=True,
            runas_prompt_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 not self.options.dest:
            hostname = socket.getfqdn()
            # use a hostname dependent directory, in case of $HOME on nfs
            self.options.dest = os.path.join('~/.ansible/pull', hostname)
        self.options.dest = os.path.expandvars(os.path.expanduser(self.options.dest))

        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 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)))

        display.verbosity = self.options.verbosity
        self.validate_conflicts(vault_opts=True)
Example #19
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
Example #20
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)
Example #21
0
    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)
Example #22
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
Example #23
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)
Example #24
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,
        )

        # 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(AdHocCLI, self).parse()

        display.verbosity = self.options.verbosity
        self.validate_conflicts(runas_opts=True,
                                vault_opts=True,
                                fork_opts=True)
Example #25
0
    def parse(self):

        self.parser = CLI.base_parser(
            usage="usage: %%prog [%s] [--help] [options] [ansible.cfg]" % "|".join(sorted(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
Example #26
0
 def dumpVars(self):
     super(ZBbuilderInventoryCLI, self).parse()
     if ansible_version.startswith('2.7'):
         from ansible.cli import CLI
         parser = CLI.base_parser(vault_opts=True, inventory_opts=True)
         options, args = parser.parse_args(["-i", "hosts"])
         return self._play_prereqs(options)
     if ansible_version.startswith('2.9'):
         return self._play_prereqs()
Example #27
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'
Example #28
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'
Example #29
0
    def parse(self):

        self.parser = CLI.base_parser(
            vault_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()

        display.verbosity = self.options.verbosity

        can_output = ['encrypt', 'decrypt', 'encrypt_string']

        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 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"
                )

        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'
                )
Example #30
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)
Example #31
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,
     )
Example #32
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)
Example #33
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,
     )
Example #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 = {}
Example #35
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")

        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"
                )
Example #36
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
Example #37
0
    def parse(self):
        ''' create an options parser for bin/ansible '''

        self.parser = CLI.base_parser(
            usage='%prog <host-pattern> [options]',
            runas_opts=True,
            inventory_opts=True,
            async_opts=True,
            output_opts=True,
            connect_opts=True,
            check_opts=True,
            runtask_opts=True,
            vault_opts=True,
            fork_opts=True,
            module_opts=True,
            basedir_opts=True,
            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)",
        )

        # 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)

        super(AdHocCLI, self).parse()

        if len(self.args) < 1:
            raise AnsibleOptionsError("Missing target hosts")
        elif len(self.args) > 1:
            raise AnsibleOptionsError("Extraneous options or arguments")

        display.verbosity = self.options.verbosity
        self.validate_conflicts(runas_opts=True,
                                vault_opts=True,
                                fork_opts=True)
Example #38
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")
Example #39
0
    def parse(self):

        self.parser = CLI.base_parser(
            usage='usage: %prog [options] [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='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'
            ])

        super(DocCLI, self).parse()

        display.verbosity = self.options.verbosity
Example #40
0
    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)
Example #41
0
    def parse(self):
        parser = CLI.base_parser(
            usage="%prog [options] playbook.yml",
            desc="Creates documentation from Ansible playbooks.",
        )

        parser.add_option('-i', '--inventory', dest='inventory', action="append",
                          help='specify inventory host path or comma separated host list')
        parser.add_option('-l', '--limit', default=C.DEFAULT_SUBSET, dest='subset',
                          help='further limit selected hosts to an additional pattern')
        parser.add_option('--output', '-o', dest='output',
                          help='output file', default='output.txt')
        parser.add_option('--template-path', dest='template_path',
                          help='path to template files', default='templates')
        parser.add_option('--template-master', dest='template_master',
                          help='path to template master file', default='master.j2')
        parser.add_option('--showdetails', dest='showdetails', action='store_true',
                          help='show JSON details for task')
        parser.add_option('--showtasks', dest='showtasks', action='store_true',
                          help='show tasks in table of contents')

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

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

        display.verbosity = self.options.verbosity
        self.options.vault_ids = []
        self.options.vault_password_files = []
        self.options.ask_vault_pass = False
        # NOTE(iwalker): need to set liststasks to True so pbex.run() does not actually run the playbook
        self.options.listtasks = True
        self.options.listhosts = False
        self.options.listtags = False
        self.options.syntax = False
        self.options.become = False
        self.options.become_method = 'sudo'
        self.options.become_user = '******'
        self.options.check = False
        self.options.diff = False

        if self.options.showdetails:
            display.warning('--showdetails option may expose passwords and other secure data!')
Example #42
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
        )

        # 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
        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')

        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'
Example #43
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]))

        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.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
Example #44
0
    def parse(self):

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

        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='Show documentation for all plugins')
        self.parser.add_option("-t",
                               "--type",
                               action="store",
                               default='module',
                               dest='type',
                               type='choice',
                               help='Choose which plugin type',
                               choices=[
                                   'module', 'cache', 'connection', 'callback',
                                   'lookup', 'strategy'
                               ])

        super(DocCLI, self).parse()

        display.verbosity = self.options.verbosity
Example #45
0
    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')
Example #46
0
    def setUp(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,
        )

        (options, args) = parser.parse_args(['-vv', '--check'])

        mock_play = MagicMock()
        mock_play.connection    = 'mock'
        mock_play.remote_user   = '******'
        mock_play.port          = 1234
        mock_play.become        = True
        mock_play.become_method = 'mock'
        mock_play.become_user   = '******'
        mock_play.no_log        = True

        self.play_context = PlayContext(play=mock_play, options=options)

        mock_task = MagicMock()
        mock_task.connection    = mock_play.connection
        mock_task.remote_user   = mock_play.remote_user
        mock_task.no_log        = mock_play.no_log
        mock_task.become        = mock_play.become
        mock_task.become_method = mock_play.becom_method
        mock_task.become_user   = mock_play.become_user
        mock_task.become_pass   = '******'
        mock_task._local_action = False
        mock_task.delegate_to   = None

        self.mock_task = mock_task

        self.mock_templar = MagicMock()
Example #47
0
    def setUp(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,
        )

        (options, args) = parser.parse_args(['-vv', '--check'])

        mock_play = MagicMock()
        mock_play.connection = 'mock'
        mock_play.remote_user = '******'
        mock_play.port = 1234
        mock_play.become = True
        mock_play.become_method = 'mock'
        mock_play.become_user = '******'
        mock_play.no_log = True

        self.play_context = PlayContext(play=mock_play, options=options)

        mock_task = MagicMock()
        mock_task.connection = mock_play.connection
        mock_task.remote_user = mock_play.remote_user
        mock_task.no_log = mock_play.no_log
        mock_task.become = mock_play.become
        mock_task.become_method = mock_play.becom_method
        mock_task.become_user = mock_play.become_user
        mock_task.become_pass = '******'
        mock_task._local_action = False
        mock_task.delegate_to = None

        self.mock_task = mock_task

        self.mock_templar = MagicMock()
Example #48
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,
        )

        # 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)
Example #49
0
    def parse(self):
        ''' create an options parser for bin/ansible '''

        self.parser = CLI.base_parser(
            usage='%prog <host-pattern> [options]',
            runas_opts=True,
            inventory_opts=True,
            async_opts=True,
            output_opts=True,
            connect_opts=True,
            check_opts=True,
            runtask_opts=True,
            vault_opts=True,
            fork_opts=True,
            module_opts=True,
            basedir_opts=True,
            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)",
        )

        # 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)

        super(AdHocCLI, self).parse()

        if len(self.args) < 1:
            raise AnsibleOptionsError("Missing target hosts")
        elif len(self.args) > 1:
            raise AnsibleOptionsError("Extraneous options or arguments")

        display.verbosity = self.options.verbosity
        self.validate_conflicts(runas_opts=True, vault_opts=True, fork_opts=True)
Example #50
0
    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])
        )

        self.set_action()

        # options specific to actions
        if self.action == "delete":
            self.parser.set_usage("usage: %prog delete [options] github_user github_repo")
        elif self.action == "import":
            self.parser.set_usage("usage: %prog import [options] github_user github_repo")
            self.parser.add_option('--no-wait', dest='wait', action='store_false', default=True,
                help='Don\'t wait for import results.')
            self.parser.add_option('--branch', dest='reference',
                help='The name of a branch to import. Defaults to the repository\'s default branch (usually master)')
            self.parser.add_option('--status', dest='check_status', action='store_true', default=False,
                help='Check the status of the most recent import request for given github_user/github_repo.')
        elif self.action == "info":
            self.parser.set_usage("usage: %prog info [options] role_name[,version]")
        elif self.action == "init":
            self.parser.set_usage("usage: %prog init [options] role_name")
            self.parser.add_option('-p', '--init-path', dest='init_path', default="./",
                help='The path in which the skeleton role will be created. The default is the current working directory.')
            self.parser.add_option(
                '--offline', dest='offline', default=False, action='store_true',
                help="Don't query the galaxy API when creating roles")
        elif self.action == "install":
            self.parser.set_usage("usage: %prog install [options] [-r FILE | role_name(s)[,version] | scm+role_repo_url[,version] | tar_file(s)]")
            self.parser.add_option('-i', '--ignore-errors', dest='ignore_errors', action='store_true', default=False,
                help='Ignore errors and continue with the next specified role.')
            self.parser.add_option('-n', '--no-deps', dest='no_deps', action='store_true', default=False,
                help='Don\'t download roles listed as dependencies')
            self.parser.add_option('-r', '--role-file', dest='role_file',
                help='A file containing a list of roles to be imported')
        elif self.action == "remove":
            self.parser.set_usage("usage: %prog remove role1 role2 ...")
        elif self.action == "list":
            self.parser.set_usage("usage: %prog list [role_name]")
        elif self.action == "login":
            self.parser.set_usage("usage: %prog login [options]")
            self.parser.add_option('--github-token', dest='token', default=None,
                help='Identify with github token rather than username and password.')
        elif self.action == "search":
            self.parser.add_option('--platforms', dest='platforms',
                help='list of OS platforms to filter by')
            self.parser.add_option('--galaxy-tags', dest='tags',
                help='list of galaxy tags to filter by')
            self.parser.add_option('--author', dest='author',
                help='GitHub username')
            self.parser.set_usage("usage: %prog search [searchterm1 searchterm2] [--galaxy-tags galaxy_tag1,galaxy_tag2] [--platforms platform1,platform2] [--author username]")
        elif self.action == "setup":
            self.parser.set_usage("usage: %prog setup [options] source github_user github_repo secret")
            self.parser.add_option('--remove', dest='remove_id', default=None,
                help='Remove the integration matching the provided ID value. Use --list to see ID values.')
            self.parser.add_option('--list', dest="setup_list", action='store_true', default=False,
                help='List all of your integrations.')

        # options that apply to more than one action
        if not self.action in ("delete","import","init","login","setup"):
            # NOTE: while the option type=str, the default is a list, and the
            # callback will set the value to a list.
            self.parser.add_option('-p', '--roles-path', dest='roles_path',
                                   action="callback", callback=CLI.expand_paths,
                                   type=str, default=C.DEFAULT_ROLES_PATH,
                help='The path to the directory containing your roles. '
                     'The default is the roles_path configured in your '
                     'ansible.cfg file (/etc/ansible/roles if not configured)')

        if self.action in ("import","info","init","install","login","search","setup","delete"):
            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=False,
                help='Ignore SSL certificate validation errors.')

        if self.action in ("init","install"):
            self.parser.add_option('-f', '--force', dest='force', action='store_true', default=False,
                help='Force overwriting an existing role')

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

        return True
Example #51
0
    def _run(self, *module_args, **complex_args):
        """Execute an ansible adhoc command returning the result in a AdhocResult object."""
        # Assemble module argument string
        if module_args:
            complex_args.update(dict(_raw_params=' '.join(module_args)))

        # Assert hosts matching the provided pattern exist
        hosts = self.options['inventory_manager'].list_hosts()
        no_hosts = False
        if len(hosts) == 0:
            no_hosts = True
            warnings.warn("provided hosts list is empty, only localhost is available")

        self.options['inventory_manager'].subset(self.options.get('subset'))
        hosts = self.options['inventory_manager'].list_hosts(self.options['host_pattern'])
        if len(hosts) == 0 and not no_hosts:
            raise ansible.errors.AnsibleError("Specified hosts and/or --limit does not match any hosts")

        # Log the module and parameters
        log.debug("[%s] %s: %s" % (self.options['host_pattern'], self.options['module_name'], complex_args))

        parser = CLI.base_parser(
            runas_opts=True,
            inventory_opts=True,
            async_opts=True,
            output_opts=True,
            connect_opts=True,
            check_opts=True,
            runtask_opts=True,
            vault_opts=True,
            fork_opts=True,
            module_opts=True,
        )
        (options, args) = parser.parse_args([])

        # Pass along cli options
        options.verbosity = 5
        options.connection = self.options.get('connection')
        options.remote_user = self.options.get('user')
        options.become = self.options.get('become')
        options.become_method = self.options.get('become_method')
        options.become_user = self.options.get('become_user')
        options.module_path = self.options.get('module_path')

        # Initialize callback to capture module JSON responses
        cb = ResultAccumulator()

        kwargs = dict(
            inventory=self.options['inventory_manager'],
            variable_manager=self.options['variable_manager'],
            loader=self.options['loader'],
            options=options,
            stdout_callback=cb,
            passwords=dict(conn_pass=None, become_pass=None),
        )

        # create a pseudo-play to execute the specified module via a single task
        play_ds = dict(
            name="pytest-ansible",
            hosts=self.options['host_pattern'],
            gather_facts='no',
            tasks=[
                dict(
                    action=dict(
                        module=self.options['module_name'], args=complex_args
                    ),
                ),
            ]
        )
        log.debug("Play(%s)", play_ds)
        play = Play().load(play_ds, variable_manager=self.options['variable_manager'], loader=self.options['loader'])

        # now create a task queue manager to execute the play
        tqm = None
        try:
            log.debug("TaskQueueManager(%s)", kwargs)
            tqm = TaskQueueManager(**kwargs)
            tqm.run(play)
        finally:
            if tqm:
                tqm.cleanup()

        # Log the results
        log.debug(cb.results)

        # Raise exception if host(s) unreachable
        # FIXME - if multiple hosts were involved, should an exception be raised?
        if cb.unreachable:
            raise AnsibleConnectionFailure("Host unreachable", dark=cb.unreachable, contacted=cb.contacted)

        # Success!
        return AdHocResult(contacted=cb.contacted)
Example #52
0
    def launch_playbook_v2(self):
        ''' run ansible-playbook operations v2.X'''
        # 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,
        )

        options, _ = parser.parse_args([])

        sshpass = None
        if not options.become_user:
            options.become_user = "******"

        if self.pk_file:
            options.private_key_file = self.pk_file
        else:
            sshpass = self.passwd

        passwords = {'conn_pass': sshpass, 'become_pass': sshpass}

        if self.user:
            options.remote_user = self.user

        if not os.path.exists(self.playbook_file):
            raise errors.AnsibleError(
                "the playbook: %s could not be found" % self.playbook_file)
        if not os.path.isfile(self.playbook_file):
            raise errors.AnsibleError(
                "the playbook: %s does not appear to be a file" % self.playbook_file)

        variable_manager = VariableManager()
        variable_manager.extra_vars = self.extra_vars

        if self.inventory_file:
            options.inventory = self.inventory_file

        options.forks = self.threads

        loader = DataLoader()
        # Add this to avoid the Ansible bug:  no host vars as host is not in inventory
        # In version 2.0.1 it must be fixed
        ansible.inventory.HOSTS_PATTERNS_CACHE = {}

        inventory = ansible.inventory.Inventory(
            loader=loader, variable_manager=variable_manager, host_list=options.inventory)
        variable_manager.set_inventory(inventory)

        if self.host:
            inventory.subset(self.host)
        # let inventory know which playbooks are using so it can know the
        # basedirs
        inventory.set_playbook_basedir(os.path.dirname(self.playbook_file))

        num_retries = 0
        return_code = 4
        results = None

        while return_code != 0 and num_retries < self.retries:
            time.sleep(5 * num_retries)
            num_retries += 1
            return_code = 0

            try:
                # create the playbook executor, which manages running the plays
                # via a task queue manager
                pbex = IMPlaybookExecutor(playbooks=[self.playbook_file],
                                          inventory=inventory,
                                          variable_manager=variable_manager,
                                          loader=loader,
                                          options=options,
                                          passwords=passwords,
                                          output=self.output)

                return_code = pbex.run()

            except errors.AnsibleError, e:
                display("ERROR: %s" % e, output=self.output)
                return_code = 1

            if return_code != 0:
                display("ERROR executing playbook (%s/%s)" %
                        (num_retries, self.retries), output=self.output)
Example #53
0
    def parse(self):
        ''' create an options parser for bin/ansible '''

        self.parser = CLI.base_parser(
            usage='%prog -U <repository> [options] [<playbook.yml>]',
            connect_opts=True,
            vault_opts=True,
            runtask_opts=True,
            subset_opts=True,
            inventory_opts=True,
            module_opts=True,
            runas_prompt_opts=True,
            desc="pulls playbooks from a VCS repo and executes them for the local host",
        )

        # 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('--full', dest='fullclone', action='store_true', help='Do a full clone, instead of a shallow one.')
        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. Choices are %s. Default is %s.'
                                    % (self.REPO_CHOICES, 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.parser.add_option('--clean', dest='clean', default=False, action='store_true',
                               help='modified files in the working repository will be discarded')
        self.parser.add_option('--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')
        self.parser.add_option("--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")

        super(PullCLI, self).parse()

        if not self.options.dest:
            hostname = socket.getfqdn()
            # use a hostname dependent directory, in case of $HOME on nfs
            self.options.dest = os.path.join('~/.ansible/pull', hostname)
        self.options.dest = os.path.expandvars(os.path.expanduser(self.options.dest))

        if os.path.exists(self.options.dest) and not os.path.isdir(self.options.dest):
            raise AnsibleOptionsError("%s is not a valid or accessible directory." % self.options.dest)

        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 self.options.module_name not in self.SUPPORTED_REPO_MODULES:
            raise AnsibleOptionsError("Unsupported repo module %s, choices are %s" % (self.options.module_name, ','.join(self.SUPPORTED_REPO_MODULES)))

        display.verbosity = self.options.verbosity
        self.validate_conflicts(vault_opts=True)
Example #54
0
    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])
        )


        self.set_action()

        # options specific to actions
        if self.action == "info":
            self.parser.set_usage("usage: %prog info [options] role_name[,version]")
        elif self.action == "init":
            self.parser.set_usage("usage: %prog init [options] role_name")
            self.parser.add_option('-p', '--init-path', dest='init_path', default="./",
                help='The path in which the skeleton role will be created. The default is the current working directory.')
            self.parser.add_option(
                '--offline', dest='offline', default=False, action='store_true',
                help="Don't query the galaxy API when creating roles")
        elif self.action == "install":
            self.parser.set_usage("usage: %prog install [options] [-r FILE | role_name(s)[,version] | scm+role_repo_url[,version] | tar_file(s)]")
            self.parser.add_option('-i', '--ignore-errors', dest='ignore_errors', action='store_true', default=False,
                help='Ignore errors and continue with the next specified role.')
            self.parser.add_option('-n', '--no-deps', dest='no_deps', action='store_true', default=False,
                help='Don\'t download roles listed as dependencies')
            self.parser.add_option('-r', '--role-file', dest='role_file',
                help='A file containing a list of roles to be imported')
        elif self.action == "remove":
            self.parser.set_usage("usage: %prog remove role1 role2 ...")
        elif self.action == "list":
            self.parser.set_usage("usage: %prog list [role_name]")
        elif self.action == "search":
            self.parser.add_option('--platforms', dest='platforms',
                help='list of OS platforms to filter by')
            self.parser.add_option('--galaxy-tags', dest='tags',
                help='list of galaxy tags to filter by')
            self.parser.set_usage("usage: %prog search [<search_term>] [--galaxy-tags <galaxy_tag1,galaxy_tag2>] [--platforms platform]")

        # options that apply to more than one action
        if self.action != "init":
            self.parser.add_option('-p', '--roles-path', dest='roles_path', default=C.DEFAULT_ROLES_PATH,
                help='The path to the directory containing your roles. '
                     'The default is the roles_path configured in your '
                     'ansible.cfg file (/etc/ansible/roles if not configured)')

        if self.action in ("info","init","install","search"):
            self.parser.add_option('-s', '--server', dest='api_server', default="https://galaxy.ansible.com",
                help='The API server destination')
            self.parser.add_option('-c', '--ignore-certs', action='store_false', dest='validate_certs', default=True,
                help='Ignore SSL certificate validation errors.')

        if self.action in ("init","install"):
            self.parser.add_option('-f', '--force', dest='force', action='store_true', default=False,
                help='Force overwriting an existing role')

        # get options, args and galaxy object
        self.options, self.args =self.parser.parse_args()
        self.display.verbosity = self.options.verbosity
        self.galaxy = Galaxy(self.options, self.display)

        return True
Example #55
0
    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]))

        self.set_action()

        # options specific to actions
        if self.action == "info":
            self.parser.set_usage(
                "usage: %prog info [options] role_name[,version]")
        elif self.action == "init":
            self.parser.set_usage("usage: %prog init [options] role_name")
            self.parser.add_option(
                '-p',
                '--init-path',
                dest='init_path',
                default="./",
                help=
                'The path in which the skeleton role will be created. The default is the current working directory.'
            )
            self.parser.add_option(
                '--offline',
                dest='offline',
                default=False,
                action='store_true',
                help="Don't query the galaxy API when creating roles")
        elif self.action == "install":
            self.parser.set_usage(
                "usage: %prog install [options] [-r FILE | role_name(s)[,version] | scm+role_repo_url[,version] | tar_file(s)]"
            )
            self.parser.add_option(
                '-i',
                '--ignore-errors',
                dest='ignore_errors',
                action='store_true',
                default=False,
                help='Ignore errors and continue with the next specified role.'
            )
            self.parser.add_option(
                '-n',
                '--no-deps',
                dest='no_deps',
                action='store_true',
                default=False,
                help='Don\'t download roles listed as dependencies')
            self.parser.add_option(
                '-r',
                '--role-file',
                dest='role_file',
                help='A file containing a list of roles to be imported')
        elif self.action == "remove":
            self.parser.set_usage("usage: %prog remove role1 role2 ...")
        elif self.action == "list":
            self.parser.set_usage("usage: %prog list [role_name]")
        elif self.action == "search":
            self.parser.add_option('--platforms',
                                   dest='platforms',
                                   help='list of OS platforms to filter by')
            self.parser.add_option('--galaxy-tags',
                                   dest='tags',
                                   help='list of galaxy tags to filter by')
            self.parser.set_usage(
                "usage: %prog search [<search_term>] [--galaxy-tags <galaxy_tag1,galaxy_tag2>] [--platforms platform]"
            )

        # options that apply to more than one action
        if self.action != "init":
            self.parser.add_option(
                '-p',
                '--roles-path',
                dest='roles_path',
                default=C.DEFAULT_ROLES_PATH,
                help='The path to the directory containing your roles. '
                'The default is the roles_path configured in your '
                'ansible.cfg file (/etc/ansible/roles if not configured)')

        if self.action in ("info", "init", "install", "search"):
            self.parser.add_option('-s',
                                   '--server',
                                   dest='api_server',
                                   default="https://galaxy.ansible.com",
                                   help='The API server destination')
            self.parser.add_option(
                '-c',
                '--ignore-certs',
                action='store_false',
                dest='validate_certs',
                default=True,
                help='Ignore SSL certificate validation errors.')

        if self.action in ("init", "install"):
            self.parser.add_option('-f',
                                   '--force',
                                   dest='force',
                                   action='store_true',
                                   default=False,
                                   help='Force overwriting an existing role')

        # get options, args and galaxy object
        self.options, self.args = self.parser.parse_args()
        self.display.verbosity = self.options.verbosity
        self.galaxy = Galaxy(self.options, self.display)

        return True
    def parse(self):
        """ create an options parser for bin/ansible """

        self.parser = CLI.base_parser(
            usage="%prog -U <repository> [options]",
            connect_opts=True,
            vault_opts=True,
            runtask_opts=True,
            subset_opts=True,
            inventory_opts=True,
            module_opts=True,
            runas_prompt_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(
            "--full", dest="fullclone", action="store_true", help="Do a full clone, instead of a shallow one."
        )
        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.parser.add_option(
            "--clean",
            dest="clean",
            default=False,
            action="store_true",
            help="modified files in the working repository will be discarded",
        )
        self.parser.add_option(
            "--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",
        )

        # for pull we don't wan't a default
        self.parser.set_defaults(inventory=None)

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

        if not self.options.dest:
            hostname = socket.getfqdn()
            # use a hostname dependent directory, in case of $HOME on nfs
            self.options.dest = os.path.join("~/.ansible/pull", hostname)
        self.options.dest = os.path.expandvars(os.path.expanduser(self.options.dest))

        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 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))
            )

        display.verbosity = self.options.verbosity
        self.validate_conflicts(vault_opts=True)
Example #57
0
    def __run(self, *module_args, **complex_args):
        '''
        The API provided by ansible is not intended as a public API.
        '''

        # Assemble module argument string
        if module_args:
            complex_args.update(dict(_raw_params=' '.join(module_args)))

        # Assert hosts matching the provided pattern exist
        hosts = self.inventory_manager.list_hosts(self.pattern)
        if len(hosts) == 0:
            raise AnsibleNoHostsMatch("No hosts match:'%s'" % self.pattern)

        # Log the module and parameters
        log.debug("[%s] %s: %s" % (self.pattern, self.module_name, complex_args))

        parser = CLI.base_parser(
            runas_opts=True,
            async_opts=True,
            output_opts=True,
            connect_opts=True,
            check_opts=True,
            runtask_opts=True,
            vault_opts=True,
            fork_opts=True,
            module_opts=True,
        )
        (options, args) = parser.parse_args([])

        # Pass along cli options
        options.verbosity = 5
        options.connection = self.options.get('connection')
        options.remote_user = self.options.get('user')
        options.become = self.options.get('become')
        options.become_method = self.options.get('become_method')
        options.become_user = self.options.get('become_user')
        options.module_path = self.options.get('module_path')

        # Initialize callback to capture module JSON responses
        cb = ResultAccumulator()

        kwargs = dict(
            inventory=self.inventory_manager,
            variable_manager=self.variable_manager,
            loader=self.loader,
            options=options,
            stdout_callback=cb,
            passwords=dict(conn_pass=None, become_pass=None),
        )

        # create a pseudo-play to execute the specified module via a single task
        play_ds = dict(
            name="Ansible Ad-Hoc",
            hosts=self.pattern,
            gather_facts='no',
            tasks=[
                dict(
                    action=dict(
                        module=self.module_name, args=complex_args
                    )
                ),
            ]
        )
        log.debug("__run - Building Play() object - %s" % play_ds)
        play = Play().load(play_ds, variable_manager=self.variable_manager, loader=self.loader)

        # now create a task queue manager to execute the play
        tqm = None
        try:
            log.debug("__run - TaskQueueManager(%s)" % kwargs)
            tqm = TaskQueueManager(**kwargs)
            tqm.run(play)
        finally:
            if tqm:
                tqm.cleanup()

        # Log the results
        log.debug(cb.results)

        # FIXME - should command failures raise an exception, or return?
        # If we choose to raise, callers will need to adapt accordingly
        # Catch any failures in the response
        # for host in results['contacted'].values():
        #     if 'failed' in host or host.get('rc', 0) != 0:
        #         raise Exception("Command failed: %s" % self.module_name, results)

        # Raise exception if host(s) unreachable
        # FIXME - if multiple hosts were involved, should an exception be raised?
        if cb.unreachable:
            # FIXME - unreachable hosts should be included in the exception message
            raise AnsibleHostUnreachable("Host unreachable", dark=cb.unreachable, contacted=cb.contacted)

        # No hosts contacted
        # if not cb.contacted:
        #     raise ansible.errors.AnsibleConnectionFailed("Provided hosts list is empty")

        # Success!
        return cb.contacted