ansible-galaxy 33.1 KB
Newer Older
1 2 3 4
#!/usr/bin/env python

########################################################################
#
Michael DeHaan committed
5
# (C) 2013, James Cammarata <jcammarata@ansible.com>
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#
# 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 <http://www.gnu.org/licenses/>.
#
########################################################################

import datetime
import json
import os
import os.path
import shutil
29
import subprocess
30 31 32
import sys
import tarfile
import tempfile
33
import urllib
34 35 36 37 38 39 40 41
import urllib2
import yaml

from collections import defaultdict
from distutils.version import LooseVersion
from jinja2 import Environment
from optparse import OptionParser

42
import ansible.constants as C
43
import ansible.utils
44
from ansible.errors import AnsibleError
45

46 47 48 49 50
default_meta_template = """---
galaxy_info:
  author: {{ author }}
  description: {{description}}
  company: {{ company }}
51 52 53 54 55 56 57
  # Some suggested licenses:
  # - BSD (default)
  # - MIT
  # - GPLv2
  # - GPLv3
  # - Apache
  # - CC-BY
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
  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 %}
82
dependencies: []
83 84
  # List your role dependencies here, one per line. Only
  # dependencies available via galaxy should be listed here.
85 86
  # Be sure to remove the '[]' above if you add dependencies
  # to this list.
87 88 89 90 91 92
  {% for dependency in dependencies %}
  #- {{ dependency }}
  {% endfor %}

"""

93
default_readme_template = """Role Name
John Dewey committed
94
=========
95 96 97 98 99 100

A brief description of the role goes here.

Requirements
------------

101
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.
102 103 104 105 106 107 108 109 110 111 112

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.

113
Example Playbook
John Dewey committed
114
----------------
115 116 117 118 119 120 121

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 }

122 123 124
License
-------

125
BSD
126 127 128 129 130 131 132

Author Information
------------------

An optional section for the role authors to include contact information, or a website (HTML is not allowed).
"""

133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
#-------------------------------------------------------------------------------------
# Utility functions for parsing actions/options
#-------------------------------------------------------------------------------------

VALID_ACTIONS = ("init", "info", "install", "list", "remove")

def get_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]
            return arg
    return None

def build_option_parser(action):
    """
    Builds an option parser object based on the action
    the user wants to execute.
    """

157 158 159 160
    usage = "usage: %%prog [%s] [--help] [options] ..." % "|".join(VALID_ACTIONS)
    epilog = "\nSee '%s <command> --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)
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175

    if not action:
        parser.print_help()
        sys.exit()

    # options for all actions
    # - none yet

    # options specific to actions
    if action == "info":
        parser.set_usage("usage: %prog info [options] role_name[,version]")
    elif action == "init":
        parser.set_usage("usage: %prog init [options] role_name")
        parser.add_option(
            '-p', '--init-path', dest='init_path', default="./",
176
            help='The path in which the skeleton role will be created. '
177
                 'The default is the current working directory.')
178 179 180
        parser.add_option(
            '--offline', dest='offline', default=False, action='store_true',
            help="Don't query the galaxy API when creating roles")
181
    elif action == "install":
182
        parser.set_usage("usage: %prog install [options] [-r FILE | role_name(s)[,version] | scm+role_repo_url[,version] | tar_file(s)]")
183 184 185 186 187 188 189
        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(
190
            '-r', '--role-file', dest='role_file',
191 192 193 194 195 196 197 198 199
            help='A file containing a list of roles to be imported')
    elif action == "remove":
        parser.set_usage("usage: %prog remove role1 role2 ...")
    elif action == "list":
        parser.set_usage("usage: %prog list [role_name]")
        
    # options that apply to more than one action
    if action != "init":
        parser.add_option(
200
            '-p', '--roles-path', dest='roles_path', default=C.DEFAULT_ROLES_PATH,
201
            help='The path to the directory containing your roles. '
202 203 204 205 206
                 'The default is the roles_path configured in your '
                 'ansible.cfg file (/etc/ansible/roles if not configured)')

    if action in ("info","init","install"):
        parser.add_option(
207
            '-s', '--server', dest='api_server', default="galaxy.ansible.com",
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
            help='The API server destination')

    if 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
    return parser

def get_opt(options, k, defval=""):
    """
    Returns an option from an Optparse values instance.
    """
    try:
        data = getattr(options, k)
    except:
        return defval
225
    if k == "roles_path":
226 227
        if os.pathsep in data:
            data = data.split(os.pathsep)[0]
228 229 230 231 232 233 234 235 236
    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):
237
        print '- you can use --ignore-errors to skip failed roles.'
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
        sys.exit(rc)

#-------------------------------------------------------------------------------------
# Galaxy API functions
#-------------------------------------------------------------------------------------

def api_get_config(api_server):
    """
    Fetches the Galaxy API current version to ensure
    the API server is up and reachable.
    """

    try:
        url = 'https://%s/api/' % api_server
        data = json.load(urllib2.urlopen(url))
        if not data.get("current_version",None):
            return None
        else:
            return data
    except:
        return None

def api_lookup_role_by_name(api_server, role_name):
    """
    Uses the Galaxy API to do a lookup on the role owner/name.
    """

265 266
    role_name = urllib.quote(role_name)

267
    try:
268 269 270
        parts = role_name.split(".")
        user_name = ".".join(parts[0:-1])
        role_name = parts[-1]
271
        print "- downloading role '%s', owned by %s" % (role_name, user_name)
272
    except:
273
        parser.print_help()
274
        print "- invalid role name (%s). Specify role as format: username.rolename" % role_name
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
        sys.exit(1)

    url = 'https://%s/api/v1/roles/?owner__username=%s&name=%s' % (api_server,user_name,role_name)
    try:
        data = json.load(urllib2.urlopen(url))
        if len(data["results"]) == 0:
            return None
        else:
            return data["results"][0]
    except:
        return None

def api_fetch_role_related(api_server, related, role_id):
    """
    Uses the Galaxy API to fetch the list of related items for
    the given role. The url comes from the 'related' field of 
    the role. 
    """

    try:
        url = 'https://%s/api/v1/roles/%d/%s/?page_size=50' % (api_server, int(role_id), related)
        data = json.load(urllib2.urlopen(url))
        results = data['results']
        done = (data.get('next', None) == None)
        while not done:
            url = 'https://%s%s' % (api_server, data['next'])
            print url
            data = json.load(urllib2.urlopen(url))
            results += data['results']
            done = (data.get('next', None) == None)
        return results
    except:
        return None

def api_get_list(api_server, what):
    """
    Uses the Galaxy API to fetch the list of items specified.
    """

    try:
        url = 'https://%s/api/v1/%s/?page_size' % (api_server, what)
        data = json.load(urllib2.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 = 'https://%s%s' % (api_server, data['next'])
            print url
            data = json.load(urllib2.urlopen(url))
            results += data['results']
            done = (data.get('next', None) == None)
        return results
    except:
332
        print "- failed to download the %s list" % what
333 334 335
        return None

#-------------------------------------------------------------------------------------
336 337 338
# scm repo utility functions
#-------------------------------------------------------------------------------------

339
def scm_archive_role(scm, role_url, role_version, role_name):
340
    if scm not in ['hg', 'git']:
341
        print "- scm %s is not currently supported" % scm
342
        return False
343
    tempdir = tempfile.mkdtemp()
344
    clone_cmd = [scm, 'clone', role_url, role_name]
345
    with open('/dev/null', 'w') as devnull:
346
        try:
347
            print "- executing: %s" % " ".join(clone_cmd)
348 349 350
            popen = subprocess.Popen(clone_cmd, cwd=tempdir, stdout=devnull, stderr=devnull)
        except:
            raise AnsibleError("error executing: %s" % " ".join(clone_cmd))
351 352
        rc = popen.wait()
    if rc != 0:
353 354
        print "- command %s failed" % ' '.join(clone_cmd)
        print "  in directory %s" % tempdir
355
        return False
356

357
    temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.tar')
358 359 360 361 362 363 364 365 366 367 368 369 370
    if scm == 'hg':
        archive_cmd = ['hg', 'archive', '--prefix', "%s/" % role_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/' % role_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:
371
        print "- executing: %s" % " ".join(archive_cmd)
372 373 374 375
        popen = subprocess.Popen(archive_cmd, cwd=os.path.join(tempdir, role_name),
                                 stderr=devnull, stdout=devnull)
        rc = popen.wait()
    if rc != 0:
376 377
        print "- command %s failed" % ' '.join(archive_cmd)
        print "  in directory %s" % tempdir
378
        return False
379 380 381 382 383 384 385

    shutil.rmtree(tempdir)

    return temp_file.name


#-------------------------------------------------------------------------------------
386 387 388 389 390 391 392 393
# Role utility functions
#-------------------------------------------------------------------------------------

def get_role_path(role_name, options):
    """
    Returns the role path based on the roles_path option
    and the role name.
    """
394
    roles_path = get_opt(options,'roles_path')
395 396 397
    roles_path = os.path.join(roles_path, role_name)
    roles_path = os.path.expanduser(roles_path)
    return roles_path
398 399 400 401 402 403

def get_role_metadata(role_name, options):
    """
    Returns the metadata as YAML, if the file 'meta/main.yml'
    exists in the specified role_path
    """
404
    role_path = os.path.join(get_role_path(role_name, options), 'meta/main.yml')
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
    try:
        if os.path.isfile(role_path):
            f = open(role_path, 'r')
            meta_data = yaml.safe_load(f)
            f.close()
            return meta_data
        else:
            return None
    except:
        return None    

def get_galaxy_install_info(role_name, options):
    """
    Returns the YAML data contained in 'meta/.galaxy_install_info',
    if it exists.
    """

    try:
        info_path = os.path.join(get_role_path(role_name, options), 'meta/.galaxy_install_info')
        if os.path.isfile(info_path):
            f = open(info_path, 'r')
            info_data = yaml.safe_load(f)
            f.close()
            return info_data
        else:
            return None
    except:
        return None    

def write_galaxy_install_info(role_name, role_version, options):
    """
    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 = role_version,
        install_date = datetime.datetime.utcnow().strftime("%c"),
    )
    try:
        info_path = os.path.join(get_role_path(role_name, options), 'meta/.galaxy_install_info')
        f = open(info_path, 'w+')
        info_data = yaml.safe_dump(info, f)
        f.close()
    except:
        return False
    return True


def remove_role(role_name, options):
    """
    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 get_role_metadata(role_name, options):
462 463
        role_path = get_role_path(role_name, options)
        shutil.rmtree(role_path)
464 465 466 467 468 469 470 471 472 473 474
        return True
    else:
        return False

def fetch_role(role_name, target, role_data, options):
    """
    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
475 476 477 478
    if '://' in role_name:
        archive_url = role_name
    else: 
        archive_url = 'https://github.com/%s/%s/archive/%s.tar.gz' % (role_data["github_user"], role_data["github_repo"], target)
479
    print "- downloading role from %s" % archive_url
480 481 482 483 484 485 486 487 488 489 490 491 492

    try:
        url_file = urllib2.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 Exception, e:
        # TODO: better urllib2 error handling for error 
        #       messages that are more exact
493
        print "- error: failed to download the file."
494 495 496 497 498
        return False

def install_role(role_name, role_version, role_filename, options):
    # the file is a tar, so open it that way and extract it
    # to the specified (or default) roles directory
499

500
    if not tarfile.is_tarfile(role_filename):
501
        print "- error: the file downloaded was not a tar.gz"
502 503
        return False
    else:
504 505 506 507
        if role_filename.endswith('.gz'):
            role_tar_file = tarfile.open(role_filename, "r:gz")
        else:
            role_tar_file = tarfile.open(role_filename, "r")
508 509 510
        # verify the role's meta file
        meta_file = None
        members = role_tar_file.getmembers()
511
        # next find the metadata file
512 513 514 515 516
        for member in members:
            if "/meta/main.yml" in member.name:
                meta_file = member
                break
        if not meta_file:
517
            print "- error: this role does not appear to have a meta/main.yml file."
518 519 520 521 522
            return False
        else:
            try:
                meta_file_data = yaml.safe_load(role_tar_file.extractfile(meta_file))
            except:
523
                print "- error: this role does not appear to have a valid meta/main.yml file."
524 525 526 527 528
                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
529
        role_path = os.path.join(get_opt(options, 'roles_path'), role_name)
530
        role_path = os.path.expanduser(role_path)
531
        print "- extracting %s to %s" % (role_name, role_path)
532 533 534
        try:
            if os.path.exists(role_path):
                if not os.path.isdir(role_path):
535
                    print "- error: the specified roles path exists and is not a directory."
536 537
                    return False
                elif not get_opt(options, "force", False):
538
                    print "- error: the specified role %s appears to already exist. Use --force to replace it." % role_name
539 540 541 542
                    return False
                else:
                    # using --force, remove the old path
                    if not remove_role(role_name, options):
543 544
                        print "- error: %s doesn't appear to contain a role." % role_path
                        print "  please remove this directory manually if you really want to put the role here."
545 546 547 548 549 550
                        return False
            else:
                os.makedirs(role_path)

            # now we do the actual extraction to the role_path
            for member in members:
551 552 553
                # 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
554
                if member.isreg():
555 556 557 558 559 560
                    parts = member.name.split("/")[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)
561 562 563 564 565
                    role_tar_file.extract(member, role_path)

            # write out the install info file for later use
            write_galaxy_install_info(role_name, role_version, options)
        except OSError, e:
566
            print "- error: you do not have permission to modify files in %s" % role_path
567 568 569
            return False

        # return the parsed yaml metadata
570
        print "- %s was installed successfully" % role_name
571 572 573 574 575 576
        return meta_file_data

#-------------------------------------------------------------------------------------
# Action functions
#-------------------------------------------------------------------------------------

577
def execute_init(args, options, parser):
578 579 580 581 582 583
    """
    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', './')
584
    api_server = get_opt(options, "api_server", "galaxy.ansible.com")
585
    force      = get_opt(options, 'force', False)
586
    offline    = get_opt(options, 'offline', False)
587

588 589 590
    if not offline:
        api_config = api_get_config(api_server)
        if not api_config:
591
            print "- the API server (%s) is not responding, please try again later." % api_server
592
            sys.exit(1)
593 594 595 596 597 598 599 600

    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):
601
                print "- the path %s already exists, but is a file - aborting" % role_path
602 603
                sys.exit(1)
            elif not force:
604 605 606 607
                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."
608 609
                sys.exit(1)
    except Exception, e:
610
        parser.print_help()
611
        print "- no role name specified for init"
612 613 614
        sys.exit(1)

    ROLE_DIRS = ('defaults','files','handlers','meta','tasks','templates','vars')
615 616 617 618 619 620 621 622 623

    # 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

624 625 626 627 628 629
    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)
630

631 632 633 634 635 636
        # 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
637 638 639 640 641 642
            platforms = []
            if not offline:
                platforms = api_get_list(api_server, "platforms") or []
            categories = []
            if not offline:
                categories = api_get_list(api_server, "categories") or []
643 644 645 646 647 648 649 650 651 652 653 654 655
            
            # 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)',
656
                min_ansible_version = '1.2',
657 658 659 660 661 662 663 664
                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
665
        elif dir not in ('files','templates'):
666 667 668 669
            # 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()
670
    print "- %s was created successfully" % role_name
671

672
def execute_info(args, options, parser):
673 674 675 676 677 678 679 680
    """
    Executes the info action. This action prints out detailed
    information about an installed role as well as info available
    from the galaxy API.
    """

    pass

681
def execute_install(args, options, parser):
682 683 684 685 686 687 688 689
    """
    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)
690
    api_server = get_opt(options, "api_server", "galaxy.ansible.com")
691
    no_deps    = get_opt(options, "no_deps", False)
692
    roles_path = get_opt(options, "roles_path")
693 694 695 696

    if len(args) == 0 and not role_file:
        # the user needs to specify one of either --role-file
        # or specify a single user/role name
697
        parser.print_help()
698
        print "- you must specify a user/role name or a roles file"
699 700 701 702
        sys.exit()
    elif len(args) == 1 and role_file:
        # using a role file is mutually exclusive of specifying
        # the role name on the command line
703
        parser.print_help()
704
        print "- please specify a user/role name, or a roles file, but not both"
705 706 707 708 709
        sys.exit(1)

    roles_done = []
    if role_file:
        f = open(role_file, 'r')
710 711 712 713 714
        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())
715 716 717 718
        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).
719
        roles_left = map(ansible.utils.role_spec_parse, args)
720 721 722

    while len(roles_left) > 0:
        # query the galaxy API for the role data
723
        role_data = None
724 725 726
        role = roles_left.pop(0)
        role_src = role.get("src")
        role_scm = role.get("scm")
727 728 729 730 731 732
        role_path = role.get("path")

        if role_path:
            options.roles_path = role_path
        else:
            options.roles_path = roles_path
733

734
        if os.path.isfile(role_src):
735
            # installing a local tar.gz
736
            tmp_file = role_src
737
        else:
738
            if role_scm:
739
                # create tar file from scm url
740
                tmp_file = scm_archive_role(role_scm, role_src, role.get("version"), role.get("name"))
741 742 743
            elif '://' in role_src:
                # just download a URL - version will probably be in the URL
                tmp_file = fetch_role(role_src, None, None, options)
744
            else:
745
                # installing from galaxy
746 747
                api_config = api_get_config(api_server)
                if not api_config:
748
                    print "- the API server (%s) is not responding, please try again later." % api_server
749 750
                    sys.exit(1)

751
                role_data = api_lookup_role_by_name(api_server, role_src)
752
                if not role_data:
753
                    print "- sorry, %s was not found on %s." % (role_src, api_server)
754 755
                    continue

756
                role_versions = api_fetch_role_related(api_server, 'versions', role_data['id'])
757
                if "version" not in role:
758 759 760 761 762 763 764
                    # 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()
765
                        role["version"] = str(loose_versions[-1])
766
                    else:
767
                        role["version"] = 'master'
768
                else:
769
                    if role_versions and role["version"] not in [a.get('name',None) for a in role_versions]:
770
                        print "- the specified version (%s) was not found in the list of available versions." % role.version
771 772 773 774 775
                        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.
776
                tmp_file = fetch_role(role_src, role["version"], role_data, options)
777 778
        installed = False
        if tmp_file:
779
            installed = install_role(role.get("name"), role.get("version"), tmp_file, options)
780 781 782
            # we're done with the temp file, clean it up
            os.unlink(tmp_file)
            # install dependencies, if we want them
783
            if not no_deps and installed:
784
                if not role_data:
785
                    role_data = get_role_metadata(role.get("name"), options)
786 787 788
                    role_dependencies = role_data['dependencies']
                else:
                    role_dependencies = role_data['summary_fields']['dependencies'] # api_fetch_role_related(api_server, 'dependencies', role_data['id'])
789
                for dep in role_dependencies:
790
                    if isinstance(dep, basestring):
791 792 793 794
                        dep = ansible.utils.role_spec_parse(dep)
                    else:
                        dep = ansible.utils.role_yaml_parse(dep)
                    if not get_role_metadata(dep["name"], options):
795 796 797 798 799
                        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"]
800
                    else:
801 802
                        print '- dependency %s is already installed, skipping.' % dep["name"]
        if not tmp_file or not installed:
803
            if tmp_file and installed:
804
                os.unlink(tmp_file)
805
            print "- %s was NOT installed successfully." % role.get("name")
806
            exit_without_ignore(options)
807 808
    sys.exit(0)

809
def execute_remove(args, options, parser):
810 811 812 813 814 815
    """
    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:
816
        parser.print_help()
817
        print '- you must specify at least one role to remove.'
818 819 820 821 822
        sys.exit()

    for role in args:
        if get_role_metadata(role, options):
            if remove_role(role, options):
823
                print '- successfully removed %s' % role
824
            else:
825
                print "- failed to remove role: %s" % role
826
        else:
827
            print '- %s is not installed, skipping.' % role
828 829
    sys.exit(0)

830
def execute_list(args, options, parser):
831 832 833 834 835 836 837 838
    """
    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:
839
        print "- please specify only one role to list, or specify no roles to see a full list"
840 841 842 843 844 845 846 847 848 849 850 851 852 853
        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
854
            print "- %s, %s" % (role_name, version)
855
        else:
856
            print "- the role %s was not found" % role_name
857 858
    else:
        # show all valid roles in the roles_path directory
859
        roles_path = get_opt(options, 'roles_path')
860
        roles_path = os.path.expanduser(roles_path)
861
        if not os.path.exists(roles_path):
862
            parser.print_help()
863
            print "- the path %s does not exist. Please specify a valid path with --roles-path" % roles_path
864 865
            sys.exit(1)
        elif not os.path.isdir(roles_path):
866
            print "- %s exists, but it is not a directory. Please specify a valid path with --roles-path" % roles_path
867
            parser.print_help()
868 869 870 871 872 873 874 875 876 877
            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)"
878
                print "- %s, %s" % (path_file, version)
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
    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]
894
        fn(args, options, parser)
895
    #except KeyError, e:
896
    #    print "- error: %s is not a valid action. Valid actions are: %s" % (action, ", ".join(VALID_ACTIONS))
897 898 899 900
    #    sys.exit(1)

if __name__ == "__main__":
    main()