diff --git a/v2/ansible/constants.py b/v2/ansible/constants.py index 09935693ace..12eb8db413b 100644 --- a/v2/ansible/constants.py +++ b/v2/ansible/constants.py @@ -203,6 +203,11 @@ ACCELERATE_KEYS_FILE_PERMS = get_config(p, 'accelerate', 'accelerate_keys_fi ACCELERATE_MULTI_KEY = get_config(p, 'accelerate', 'accelerate_multi_key', 'ACCELERATE_MULTI_KEY', False, boolean=True) PARAMIKO_PTY = get_config(p, 'paramiko_connection', 'pty', 'ANSIBLE_PARAMIKO_PTY', True, boolean=True) +# galaxy related +DEFAULT_GALAXY_URI = get_config(p, 'galaxy', 'server_uri', 'ANSIBLE_GALAXY_SERVER_URI', 'https://galaxy.ansible.com') +# this can be configured to blacklist SCMS but cannot add new ones unless the code is also updated +GALAXY_SCMS = get_config(p, 'galaxy', 'scms', 'ANSIBLE_GALAXY_SCMS', ['git','hg'], islist=True) + # characters included in auto-generated passwords DEFAULT_PASSWORD_CHARS = ascii_letters + digits + ".,:-_" diff --git a/v2/ansible/galaxy/__init__.py b/v2/ansible/galaxy/__init__.py new file mode 100644 index 00000000000..c3d37fe22e9 --- /dev/null +++ b/v2/ansible/galaxy/__init__.py @@ -0,0 +1,48 @@ +######################################################################## +# +# (C) 2015, Brian Coca +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see . +# +######################################################################## +''' This manages remote shared Ansible objects, mainly roles''' + +import os + +from ansible.errors import AnsibleError +from ansible.utils.display import Display + +class Galaxy(object): + ''' Keeps global galaxy info ''' + + def __init__(self, options, display=None): + + if display is None: + self.display = Display() + else: + self.display = display + + self.options = options + self.roles_path = os.path.expanduser(self.options.roles_path) + + self.roles = {} + + def add_role(self, role): + self.roles[role.name] = role + + def remove_role(self, role_name): + del self.roles[role_name] + diff --git a/v2/ansible/galaxy/api.py b/v2/ansible/galaxy/api.py new file mode 100755 index 00000000000..a9d1566e049 --- /dev/null +++ b/v2/ansible/galaxy/api.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python + +######################################################################## +# +# (C) 2013, James Cammarata +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see . +# +######################################################################## +import json +from urllib2 import urlopen, quote as urlquote +from urlparse import urlparse + +from ansible.errors import AnsibleError + +class GalaxyAPI(object): + ''' This class is meant to be used as a API client for an Ansible Galaxy server ''' + + SUPPORTED_VERSIONS = ['v1'] + + def __init__(self, galaxy, api_server): + + self.galaxy = galaxy + + try: + urlparse(api_server, scheme='https') + except: + raise AnsibleError("Invalid server API url passed: %s" % self.galaxy.api_server) + + server_version = self.get_server_api_version(api_server) + self.galaxy.display.vvvvv("Server version: %s" % server_version) + if server_version in self.SUPPORTED_VERSIONS: + self.baseurl = '%s/api/%s' % (api_server, server_version) + self.version = server_version # for future use + self.galaxy.display.vvvvv("Base API: %s" % self.baseurl) + else: + raise AnsibleError("Unsupported Galaxy server API version: %s" % server_version) + + def get_server_api_version(self, api_server): + """ + Fetches the Galaxy API current version to ensure + the API server is up and reachable. + """ + + try: + self.galaxy.display.vvvvv("Querying server version: %s" % api_server) + data = json.load(urlopen(api_server)) + if not data.get("current_version", None): + return None + else: + return data + except: + return None + + def lookup_role_by_name(self, role_name, notify=True): + """ + Find a role by name + """ + + role_name = urlquote(role_name) + + try: + parts = role_name.split(".") + user_name = ".".join(parts[0:-1]) + role_name = parts[-1] + if notify: + self.galaxy.display.display("- downloading role '%s', owned by %s" % (role_name, user_name)) + except: + raise AnsibleError("- invalid role name (%s). Specify role as format: username.rolename" % role_name) + + url = '%s/roles/?owner__username=%s&name=%s' % (self.baseurl, user_name, role_name) + try: + data = json.load(urlopen(url)) + if len(data["results"]) != 0: + return data["results"][0] + except: + # TODO: report on connection/availability errors + pass + + return None + + def fetch_role_related(self, related, role_id): + """ + Fetch the list of related items for the given role. + The url comes from the 'related' field of the role. + """ + + try: + url = '%s/roles/%d/%s/?page_size=50' % (self.baseurl, int(role_id), related) + data = json.load(urlopen(url)) + results = data['results'] + done = (data.get('next', None) == None) + while not done: + url = '%s%s' % (self.baseurl, data['next']) + self.galaxy.display.display(url) + data = json.load(urlopen(url)) + results += data['results'] + done = (data.get('next', None) == None) + return results + except: + return None + + def get_list(self, what): + """ + Fetch the list of items specified. + """ + + try: + url = '%s/%s/?page_size' % (self.baseurl, what) + data = json.load(urlopen(url)) + if "results" in data: + results = data['results'] + else: + results = data + done = True + if "next" in data: + done = (data.get('next', None) == None) + while not done: + url = '%s%s' % (self.baseurl, data['next']) + self.galaxy.display.display(url) + data = json.load(urlopen(url)) + results += data['results'] + done = (data.get('next', None) == None) + return results + except Exception as error: + raise AnsibleError("Failed to download the %s list: %s" % (what, str(error))) diff --git a/v2/ansible/galaxy/data/metadata_template.j2 b/v2/ansible/galaxy/data/metadata_template.j2 new file mode 100644 index 00000000000..328e13a814c --- /dev/null +++ b/v2/ansible/galaxy/data/metadata_template.j2 @@ -0,0 +1,45 @@ +galaxy_info: + author: {{ author }} + description: {{description}} + company: {{ company }} + # If the issue tracker for your role is not on github, uncomment the + # next line and provide a value + # issue_tracker_url: {{ issue_tracker_url }} + # Some suggested licenses: + # - BSD (default) + # - MIT + # - GPLv2 + # - GPLv3 + # - Apache + # - CC-BY + license: {{ license }} + min_ansible_version: {{ min_ansible_version }} + # + # Below are all platforms currently available. Just uncomment + # the ones that apply to your role. If you don't see your + # platform on this list, let us know and we'll get it added! + # + #platforms: + {%- for platform,versions in platforms.iteritems() %} + #- name: {{ platform }} + # versions: + # - all + {%- for version in versions %} + # - {{ version }} + {%- endfor %} + {%- endfor %} + # + # Below are all categories currently available. Just as with + # the platforms above, uncomment those that apply to your role. + # + #categories: + {%- for category in categories %} + #- {{ category.name }} + {%- endfor %} +dependencies: [] + # List your role dependencies here, one per line. + # Be sure to remove the '[]' above if you add dependencies + # to this list. + {% for dependency in dependencies %} + #- {{ dependency }} + {% endfor %} diff --git a/v2/ansible/galaxy/data/readme b/v2/ansible/galaxy/data/readme new file mode 100644 index 00000000000..225dd44b9fc --- /dev/null +++ b/v2/ansible/galaxy/data/readme @@ -0,0 +1,38 @@ +Role Name +========= + +A brief description of the role goes here. + +Requirements +------------ + +Any pre-requisites that may not be covered by Ansible itself or the role should be mentioned here. For instance, if the role uses the EC2 module, it may be a good idea to mention in this section that the boto package is required. + +Role Variables +-------------- + +A description of the settable variables for this role should go here, including any variables that are in defaults/main.yml, vars/main.yml, and any variables that can/should be set via parameters to the role. Any variables that are read from other roles and/or the global scope (ie. hostvars, group vars, etc.) should be mentioned here as well. + +Dependencies +------------ + +A list of other roles hosted on Galaxy should go here, plus any details in regards to parameters that may need to be set for other roles, or variables that are used from other roles. + +Example Playbook +---------------- + +Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too: + + - hosts: servers + roles: + - { role: username.rolename, x: 42 } + +License +------- + +BSD + +Author Information +------------------ + +An optional section for the role authors to include contact information, or a website (HTML is not allowed). diff --git a/v2/ansible/galaxy/role.py b/v2/ansible/galaxy/role.py new file mode 100644 index 00000000000..89d8399b2da --- /dev/null +++ b/v2/ansible/galaxy/role.py @@ -0,0 +1,290 @@ +######################################################################## +# +# (C) 2015, Brian Coca +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see . +# +######################################################################## + +import datetime +import os +import subprocess +import tarfile +import tempfile +import yaml +from shutil import rmtree +from urllib2 import urlopen + +from ansible import constants as C +from ansible.errors import AnsibleError + +class GalaxyRole(object): + + SUPPORTED_SCMS = set(['git', 'hg']) + META_MAIN = os.path.join('meta', 'main.yml') + META_INSTALL = os.path.join('meta', '.galaxy_install_info') + + def __init__(self, galaxy, role_name, role_version=None, role_url=None): + + self.options = galaxy.options + self.display = galaxy.display + + self.name = role_name + self.meta_data = None + self.install_info = None + self.role_path = (os.path.join(self.roles_path, self.name)) + + # TODO: possibly parse version and url from role_name + self.version = role_version + self.url = role_url + if self.url is None and '://' in self.name: + self.url = self.name + + if C.GALAXY_SCMS: + self.scms = self.SUPPORTED_SCMS.intersection(set(C.GALAXY_SCMS)) + else: + self.scms = self.SUPPORTED_SCMS + + if not self.scms: + self.display.warning("No valid SCMs configured for Galaxy.") + + + def fetch_from_scm_archive(self, scm, role_url, role_version): + + # this can be configured to prevent unwanted SCMS but cannot add new ones unless the code is also updated + if scm not in self.scms: + self.display.display("The %s scm is not currently supported" % scm) + return False + + tempdir = tempfile.mkdtemp() + clone_cmd = [scm, 'clone', role_url, self.name] + with open('/dev/null', 'w') as devnull: + try: + self.display.display("- executing: %s" % " ".join(clone_cmd)) + popen = subprocess.Popen(clone_cmd, cwd=tempdir, stdout=devnull, stderr=devnull) + except: + raise AnsibleError("error executing: %s" % " ".join(clone_cmd)) + rc = popen.wait() + if rc != 0: + self.display.display("- command %s failed" % ' '.join(clone_cmd)) + self.display.display(" in directory %s" % tempdir) + return False + + temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.tar') + if scm == 'hg': + archive_cmd = ['hg', 'archive', '--prefix', "%s/" % self.name] + if role_version: + archive_cmd.extend(['-r', role_version]) + archive_cmd.append(temp_file.name) + if scm == 'git': + archive_cmd = ['git', 'archive', '--prefix=%s/' % self.name, '--output=%s' % temp_file.name] + if role_version: + archive_cmd.append(role_version) + else: + archive_cmd.append('HEAD') + + with open('/dev/null', 'w') as devnull: + self.display.display("- executing: %s" % " ".join(archive_cmd)) + popen = subprocess.Popen(archive_cmd, cwd=os.path.join(tempdir, self.name), + stderr=devnull, stdout=devnull) + rc = popen.wait() + if rc != 0: + self.display.display("- command %s failed" % ' '.join(archive_cmd)) + self.display.display(" in directory %s" % tempdir) + return False + + rmtree(tempdir, ignore_errors=True) + + return temp_file.name + + + + def read_metadata(self): + """ + Reads the metadata as YAML, if the file 'meta/main.yml' exists + """ + meta_path = os.path.join(self.role_path, self.META_MAIN) + if os.path.isfile(meta_path): + try: + f = open(meta_path, 'r') + self.meta_data = yaml.safe_load(f) + except: + self.display.vvvvv("Unable to load metadata for %s" % self.name) + return False + finally: + f.close() + + return True + + def read_galaxy_install_info(self): + """ + Returns the YAML data contained in 'meta/.galaxy_install_info', + if it exists. + """ + + info_path = os.path.join(self.role_path, self.META_INSTALL) + if os.path.isfile(info_path): + try: + f = open(info_path, 'r') + self.install_info = yaml.safe_load(f) + except: + self.display.vvvvv("Unable to load Galaxy install info for %s" % self.name) + return False + finally: + f.close() + + return True + + def write_galaxy_install_info(self): + """ + Writes a YAML-formatted file to the role's meta/ directory + (named .galaxy_install_info) which contains some information + we can use later for commands like 'list' and 'info'. + """ + + info = dict( + version=self.version, + install_date=datetime.datetime.utcnow().strftime("%c"), + ) + info_path = os.path.join(self.role_path, self.META_INSTALL) + try: + f = open(info_path, 'w+') + self.install_info = yaml.safe_dump(info, f) + except: + return False + finally: + f.close() + + return True + + def remove(self): + """ + Removes the specified role from the roles path. There is a + sanity check to make sure there's a meta/main.yml file at this + path so the user doesn't blow away random directories + """ + if self.read_metadata(): + try: + rmtree(self.role_path) + return True + except: + pass + + return False + + def fetch(self, target, role_data): + """ + Downloads the archived role from github to a temp location, extracts + it, and then copies the extracted role to the role library path. + """ + + # first grab the file and save it to a temp location + if self.url: + archive_url = self.url + else: + archive_url = 'https://github.com/%s/%s/archive/%s.tar.gz' % (role_data["github_user"], role_data["github_repo"], target) + self.display.display("- downloading role from %s" % archive_url) + + try: + url_file = urlopen(archive_url) + temp_file = tempfile.NamedTemporaryFile(delete=False) + data = url_file.read() + while data: + temp_file.write(data) + data = url_file.read() + temp_file.close() + return temp_file.name + except: + # TODO: better urllib2 error handling for error + # messages that are more exact + self.display.error("failed to download the file.") + return False + + def install(self, role_version, role_filename): + # the file is a tar, so open it that way and extract it + # to the specified (or default) roles directory + + if not tarfile.is_tarfile(role_filename): + self.display.error("the file downloaded was not a tar.gz") + return False + else: + if role_filename.endswith('.gz'): + role_tar_file = tarfile.open(role_filename, "r:gz") + else: + role_tar_file = tarfile.open(role_filename, "r") + # verify the role's meta file + meta_file = None + members = role_tar_file.getmembers() + # next find the metadata file + for member in members: + if self.META_MAIN in member.name: + meta_file = member + break + if not meta_file: + self.display.error("this role does not appear to have a meta/main.yml file.") + return False + else: + try: + self.meta_data = yaml.safe_load(role_tar_file.extractfile(meta_file)) + except: + self.display.error("this role does not appear to have a valid meta/main.yml file.") + return False + + # we strip off the top-level directory for all of the files contained within + # the tar file here, since the default is 'github_repo-target', and change it + # to the specified role's name + self.display.display("- extracting %s to %s" % (self.name, self.role_path)) + try: + if os.path.exists(self.role_path): + if not os.path.isdir(self.role_path): + self.display.error("the specified roles path exists and is not a directory.") + return False + elif not getattr(self.options, "force", False): + self.display.error("the specified role %s appears to already exist. Use --force to replace it." % self.name) + return False + else: + # using --force, remove the old path + if not self.remove(): + self.display.error("%s doesn't appear to contain a role." % self.role_path) + self.display.error(" please remove this directory manually if you really want to put the role here.") + return False + else: + os.makedirs(self.role_path) + + # now we do the actual extraction to the role_path + for member in members: + # we only extract files, and remove any relative path + # bits that might be in the file for security purposes + # and drop the leading directory, as mentioned above + if member.isreg() or member.issym(): + parts = member.name.split(os.sep)[1:] + final_parts = [] + for part in parts: + if part != '..' and '~' not in part and '$' not in part: + final_parts.append(part) + member.name = os.path.join(*final_parts) + role_tar_file.extract(member, self.role_path) + + # write out the install info file for later use + self.version = role_version + self.write_galaxy_install_info() + except OSError as e: + self.display.error("Could not update files in %s: %s" % (self.role_path, str(e))) + return False + + # return the parsed yaml metadata + self.display.display("- %s was installed successfully" % self.role_name) + return True diff --git a/v2/bin/ansible-galaxy b/v2/bin/ansible-galaxy new file mode 100755 index 00000000000..1c8215b944f --- /dev/null +++ b/v2/bin/ansible-galaxy @@ -0,0 +1,560 @@ +#!/usr/bin/env python + +######################################################################## +# +# (C) 2013, James Cammarata +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see . +# +######################################################################## + +import datetime +import json +import os +import os.path +import shutil +import subprocess +import sys +import tarfile +import tempfile +import urllib +import urllib2 +import yaml + +from collections import defaultdict +from distutils.version import LooseVersion +from jinja2 import Environment +from optparse import OptionParser + +import ansible.constants as C +import ansible.utils +import ansible.galaxy +from ansible.errors import AnsibleError + +class Cli(object): + + VALID_ACTIONS = ("init", "info", "install", "list", "remove") + SKIP_INFO_KEYS = ("platforms","readme_html", "related", "summary_fields", "average_aw_composite", "average_aw_score", "url" ) + + def __init__(self): + + if display is None: + self.display = Display() + else: + self.display = display + self.action = None + + def set_action(args): + """ + Get the action the user wants to execute from the + sys argv list. + """ + for i in range(0,len(args)): + arg = args[i] + if arg in VALID_ACTIONS: + del args[i] + self.action = arg + + + def parse(self): + ''' create an options parser for bin/ansible ''' + usage = "usage: %%prog [%s] [--help] [options] ..." % "|".join(VALID_ACTIONS) + epilog = "\nSee '%s --help' for more information on a specific command.\n\n" % os.path.basename(sys.argv[0]) + OptionParser.format_epilog = lambda self, formatter: self.epilog + parser = OptionParser(usage=usage, epilog=epilog) + + if not self.action: + parser.print_help() + sys.exit(1) + + # options specific to actions + if self.action == "info": + parser.set_usage("usage: %prog info [options] role_name[,version]") + elif self.action == "init": + parser.set_usage("usage: %prog init [options] role_name") + 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.') + 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": + parser.set_usage("usage: %prog install [options] [-r FILE | role_name(s)[,version] | scm+role_repo_url[,version] | tar_file(s)]") + parser.add_option( + '-i', '--ignore-errors', dest='ignore_errors', action='store_true', default=False, + help='Ignore errors and continue with the next specified role.') + parser.add_option( + '-n', '--no-deps', dest='no_deps', action='store_true', default=False, + help='Don\'t download roles listed as dependencies') + parser.add_option( + '-r', '--role-file', dest='role_file', + help='A file containing a list of roles to be imported') + elif self.action == "remove": + parser.set_usage("usage: %prog remove role1 role2 ...") + elif self.action == "list": + parser.set_usage("usage: %prog list [role_name]") + + # options that apply to more than one action + if self.action != "init": + 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"): + parser.add_option( + '-s', '--server', dest='api_server', default="galaxy.ansible.com", + help='The API server destination') + + if self.action in ("init","install"): + parser.add_option( + '-f', '--force', dest='force', action='store_true', default=False, + help='Force overwriting an existing role') + + # done, return the parser + options, args = parser.parse_args() + + if len(args) == 0 or len(args) > 1: + parser.print_help() + sys.exit(1) + + display.verbosity = options.verbosity + + return (options, args) + + def run(options, args): + + # execute the desired action + fn = getattr(self, "execute_%s" % self.action) + fn(args, options) + + def get_opt(options, k, defval=""): + """ + Returns an option from an Optparse values instance. + """ + try: + data = getattr(options, k) + except: + return defval + if k == "roles_path": + if os.pathsep in data: + data = data.split(os.pathsep)[0] + return data + + def exit_without_ignore(options, rc=1): + """ + Exits with the specified return code unless the + option --ignore-errors was specified + """ + + if not get_opt(options, "ignore_errors", False): + print '- you can use --ignore-errors to skip failed roles.' + sys.exit(rc) + + + + def execute_init(args, options, parser): + """ + Executes the init action, which creates the skeleton framework + of a role that complies with the galaxy metadata format. + """ + + init_path = get_opt(options, 'init_path', './') + api_server = get_opt(options, "api_server", "galaxy.ansible.com") + force = get_opt(options, 'force', False) + offline = get_opt(options, 'offline', False) + + if not offline: + api_config = api_get_config(api_server) + if not api_config: + print "- the API server (%s) is not responding, please try again later." % api_server + sys.exit(1) + + try: + role_name = args.pop(0).strip() + if role_name == "": + raise Exception("") + role_path = os.path.join(init_path, role_name) + if os.path.exists(role_path): + if os.path.isfile(role_path): + print "- the path %s already exists, but is a file - aborting" % role_path + sys.exit(1) + elif not force: + print "- the directory %s already exists." % role_path + print " you can use --force to re-initialize this directory,\n" + \ + " however it will reset any main.yml files that may have\n" + \ + " been modified there already." + sys.exit(1) + except Exception, e: + parser.print_help() + print "- no role name specified for init" + sys.exit(1) + + ROLE_DIRS = ('defaults','files','handlers','meta','tasks','templates','vars') + + # create the default README.md + if not os.path.exists(role_path): + os.makedirs(role_path) + readme_path = os.path.join(role_path, "README.md") + f = open(readme_path, "wb") + f.write(default_readme_template) + f.close + + for dir in ROLE_DIRS: + dir_path = os.path.join(init_path, role_name, dir) + main_yml_path = os.path.join(dir_path, 'main.yml') + # create the directory if it doesn't exist already + if not os.path.exists(dir_path): + os.makedirs(dir_path) + + # now create the main.yml file for that directory + if dir == "meta": + # create a skeleton meta/main.yml with a valid galaxy_info + # datastructure in place, plus with all of the available + # tags/platforms included (but commented out) and the + # dependencies section + platforms = [] + if not offline: + platforms = api_get_list(api_server, "platforms") or [] + categories = [] + if not offline: + categories = api_get_list(api_server, "categories") or [] + + # group the list of platforms from the api based + # on their names, with the release field being + # appended to a list of versions + platform_groups = defaultdict(list) + for platform in platforms: + platform_groups[platform['name']].append(platform['release']) + platform_groups[platform['name']].sort() + + inject = dict( + author = 'your name', + company = 'your company (optional)', + license = 'license (GPLv2, CC-BY, etc)', + issue_tracker_url = 'http://example.com/issue/tracker', + min_ansible_version = '1.2', + platforms = platform_groups, + categories = categories, + ) + rendered_meta = Environment().from_string(default_meta_template).render(inject) + f = open(main_yml_path, 'w') + f.write(rendered_meta) + f.close() + pass + elif dir not in ('files','templates'): + # just write a (mostly) empty YAML file for main.yml + f = open(main_yml_path, 'w') + f.write('---\n# %s file for %s\n' % (dir,role_name)) + f.close() + print "- %s was created successfully" % role_name + + def execute_info(args, options, parser): + """ + Executes the info action. This action prints out detailed + information about an installed role as well as info available + from the galaxy API. + """ + + if len(args) == 0: + # the user needs to specify a role + parser.print_help() + print "- you must specify a user/role name" + sys.exit(1) + + api_server = get_opt(options, "api_server", "galaxy.ansible.com") + api_config = api_get_config(api_server) + roles_path = get_opt(options, "roles_path") + + for role in args: + + role_info = {} + + install_info = get_galaxy_install_info(role, options) + if install_info: + if 'version' in install_info: + install_info['intalled_version'] = install_info['version'] + del install_info['version'] + role_info.update(install_info) + + remote_data = api_lookup_role_by_name(api_server, role, False) + if remote_data: + role_info.update(remote_data) + + metadata = get_role_metadata(role, options) + if metadata: + role_info.update(metadata) + + role_spec = ansible.utils.role_spec_parse(role) + if role_spec: + role_info.update(role_spec) + + if role_info: + print "- %s:" % (role) + for k in sorted(role_info.keys()): + + if k in SKIP_INFO_KEYS: + continue + + if isinstance(role_info[k], dict): + print "\t%s: " % (k) + for key in sorted(role_info[k].keys()): + if key in SKIP_INFO_KEYS: + continue + print "\t\t%s: %s" % (key, role_info[k][key]) + else: + print "\t%s: %s" % (k, role_info[k]) + else: + print "- the role %s was not found" % role + + def execute_install(args, options, parser): + """ + Executes the installation action. The args list contains the + roles to be installed, unless -f was specified. The list of roles + can be a name (which will be downloaded via the galaxy API and github), + or it can be a local .tar.gz file. + """ + + role_file = get_opt(options, "role_file", None) + + if len(args) == 0 and role_file is None: + # the user needs to specify one of either --role-file + # or specify a single user/role name + parser.print_help() + print "- you must specify a user/role name or a roles file" + sys.exit() + elif len(args) == 1 and not role_file is None: + # using a role file is mutually exclusive of specifying + # the role name on the command line + parser.print_help() + print "- please specify a user/role name, or a roles file, but not both" + sys.exit(1) + + api_server = get_opt(options, "api_server", "galaxy.ansible.com") + no_deps = get_opt(options, "no_deps", False) + roles_path = get_opt(options, "roles_path") + + roles_done = [] + if role_file: + f = open(role_file, 'r') + if role_file.endswith('.yaml') or role_file.endswith('.yml'): + roles_left = map(ansible.utils.role_yaml_parse, yaml.safe_load(f)) + else: + # roles listed in a file, one per line + roles_left = map(ansible.utils.role_spec_parse, f.readlines()) + f.close() + else: + # roles were specified directly, so we'll just go out grab them + # (and their dependencies, unless the user doesn't want us to). + roles_left = map(ansible.utils.role_spec_parse, args) + + while len(roles_left) > 0: + # query the galaxy API for the role data + role_data = None + role = roles_left.pop(0) + role_src = role.get("src") + role_scm = role.get("scm") + role_path = role.get("path") + + if role_path: + options.roles_path = role_path + else: + options.roles_path = roles_path + + if os.path.isfile(role_src): + # installing a local tar.gz + tmp_file = role_src + else: + if role_scm: + # create tar file from scm url + tmp_file = scm_archive_role(role_scm, role_src, role.get("version"), role.get("name")) + elif '://' in role_src: + # just download a URL - version will probably be in the URL + tmp_file = fetch_role(role_src, None, None, options) + else: + # installing from galaxy + api_config = api_get_config(api_server) + if not api_config: + print "- the API server (%s) is not responding, please try again later." % api_server + sys.exit(1) + + role_data = api_lookup_role_by_name(api_server, role_src) + if not role_data: + print "- sorry, %s was not found on %s." % (role_src, api_server) + exit_without_ignore(options) + continue + + role_versions = api_fetch_role_related(api_server, 'versions', role_data['id']) + if "version" not in role or role['version'] == '': + # convert the version names to LooseVersion objects + # and sort them to get the latest version. If there + # are no versions in the list, we'll grab the head + # of the master branch + if len(role_versions) > 0: + loose_versions = [LooseVersion(a.get('name',None)) for a in role_versions] + loose_versions.sort() + role["version"] = str(loose_versions[-1]) + else: + role["version"] = 'master' + elif role['version'] != 'master': + if role_versions and role["version"] not in [a.get('name', None) for a in role_versions]: + print 'role is %s' % role + print "- the specified version (%s) was not found in the list of available versions (%s)." % (role['version'], role_versions) + exit_without_ignore(options) + continue + + # download the role. if --no-deps was specified, we stop here, + # otherwise we recursively grab roles and all of their deps. + tmp_file = fetch_role(role_src, role["version"], role_data, options) + installed = False + if tmp_file: + installed = install_role(role.get("name"), role.get("version"), tmp_file, options) + # we're done with the temp file, clean it up + if tmp_file != role_src: + os.unlink(tmp_file) + # install dependencies, if we want them + if not no_deps and installed: + if not role_data: + role_data = get_role_metadata(role.get("name"), options) + role_dependencies = role_data['dependencies'] + else: + role_dependencies = role_data['summary_fields']['dependencies'] # api_fetch_role_related(api_server, 'dependencies', role_data['id']) + for dep in role_dependencies: + if isinstance(dep, basestring): + dep = ansible.utils.role_spec_parse(dep) + else: + dep = ansible.utils.role_yaml_parse(dep) + if not get_role_metadata(dep["name"], options): + if dep not in roles_left: + print '- adding dependency: %s' % dep["name"] + roles_left.append(dep) + else: + print '- dependency %s already pending installation.' % dep["name"] + else: + print '- dependency %s is already installed, skipping.' % dep["name"] + if not tmp_file or not installed: + print "- %s was NOT installed successfully." % role.get("name") + exit_without_ignore(options) + sys.exit(0) + + def execute_remove(args, options, parser): + """ + Executes the remove action. The args list contains the list + of roles to be removed. This list can contain more than one role. + """ + + if len(args) == 0: + parser.print_help() + print '- you must specify at least one role to remove.' + sys.exit() + + for role in args: + if get_role_metadata(role, options): + if remove_role(role, options): + print '- successfully removed %s' % role + else: + print "- failed to remove role: %s" % role + else: + print '- %s is not installed, skipping.' % role + sys.exit(0) + + def execute_list(args, options, parser): + """ + Executes the list action. The args list can contain zero + or one role. If one is specified, only that role will be + shown, otherwise all roles in the specified directory will + be shown. + """ + + if len(args) > 1: + print "- please specify only one role to list, or specify no roles to see a full list" + sys.exit(1) + + if len(args) == 1: + # show only the request role, if it exists + role_name = args[0] + metadata = get_role_metadata(role_name, options) + if metadata: + install_info = get_galaxy_install_info(role_name, options) + version = None + if install_info: + version = install_info.get("version", None) + if not version: + version = "(unknown version)" + # show some more info about single roles here + print "- %s, %s" % (role_name, version) + else: + print "- the role %s was not found" % role_name + else: + # show all valid roles in the roles_path directory + roles_path = get_opt(options, 'roles_path') + roles_path = os.path.expanduser(roles_path) + if not os.path.exists(roles_path): + parser.print_help() + print "- the path %s does not exist. Please specify a valid path with --roles-path" % roles_path + sys.exit(1) + elif not os.path.isdir(roles_path): + print "- %s exists, but it is not a directory. Please specify a valid path with --roles-path" % roles_path + parser.print_help() + sys.exit(1) + path_files = os.listdir(roles_path) + for path_file in path_files: + if get_role_metadata(path_file, options): + install_info = get_galaxy_install_info(path_file, options) + version = None + if install_info: + version = install_info.get("version", None) + if not version: + version = "(unknown version)" + print "- %s, %s" % (path_file, version) + sys.exit(0) + +#------------------------------------------------------------------------------------- +# The main entry point +#------------------------------------------------------------------------------------- + +#def main(): +# # parse the CLI options +# action = get_action(sys.argv) +# parser = build_option_parser(action) +# (options, args) = parser.parse_args() +# +# # execute the desired action +# if 1: #try: +# fn = globals()["execute_%s" % action] +# fn(args, options, parser) +# #except KeyError, e: +# # print "- error: %s is not a valid action. Valid actions are: %s" % (action, ", ".join(VALID_ACTIONS)) +# # sys.exit(1) + + +if __name__ == '__main__': + + display = Display() + + try: + cli = Cli(display=display) + cli.set_action(sys.argv) + (options, args) = cli.parse() + sys.exit(cli.run(options, args)) + except AnsibleError as e: + display.error(str(e)) + sys.exit(1) + except KeyboardInterrupt: + display.error("interrupted") + sys.exit(1)