| 1 |
#!/usr/bin/env python3 |
| 2 |
# Copyright: (c) 2013, James Cammarata <[email protected]> |
| 3 |
# Copyright: (c) 2018-2021, Ansible Project |
| 4 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# PYTHON_ARGCOMPLETE_OK |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
# ansible.cli needs to be imported first, to ensure the source bin/* scripts run that code first |
| 10 |
from ansible.cli import CLI |
| 11 |
|
| 12 |
import argparse |
| 13 |
import functools |
| 14 |
import json |
| 15 |
import os.path |
| 16 |
import pathlib |
| 17 |
import re |
| 18 |
import shutil |
| 19 |
import sys |
| 20 |
import textwrap |
| 21 |
import time |
| 22 |
import typing as t |
| 23 |
|
| 24 |
from dataclasses import dataclass |
| 25 |
from yaml.error import YAMLError |
| 26 |
|
| 27 |
import ansible.constants as C |
| 28 |
from ansible import context |
| 29 |
from ansible.cli.arguments import option_helpers as opt_help |
| 30 |
from ansible.errors import AnsibleError, AnsibleOptionsError |
| 31 |
from ansible.galaxy import Galaxy, get_collections_galaxy_meta_info |
| 32 |
from ansible.galaxy.api import GalaxyAPI, GalaxyError |
| 33 |
from ansible.galaxy.collection import ( |
| 34 |
build_collection, |
| 35 |
download_collections, |
| 36 |
find_existing_collections, |
| 37 |
install_collections, |
| 38 |
publish_collection, |
| 39 |
validate_collection_name, |
| 40 |
validate_collection_path, |
| 41 |
verify_collections, |
| 42 |
SIGNATURE_COUNT_RE, |
| 43 |
) |
| 44 |
from ansible.galaxy.collection.concrete_artifact_manager import ( |
| 45 |
ConcreteArtifactsManager, |
| 46 |
) |
| 47 |
from ansible.galaxy.collection.gpg import GPG_ERROR_MAP |
| 48 |
from ansible.galaxy.dependency_resolution.dataclasses import Requirement |
| 49 |
|
| 50 |
from ansible.galaxy.role import GalaxyRole |
| 51 |
from ansible.galaxy.token import BasicAuthToken, GalaxyToken, KeycloakToken, NoTokenSentinel |
| 52 |
from ansible.module_utils.ansible_release import __version__ as ansible_version |
| 53 |
from ansible.module_utils.common.collections import is_iterable |
| 54 |
from ansible.module_utils.common.yaml import yaml_dump, yaml_load |
| 55 |
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text |
| 56 |
from ansible._internal._datatag._tags import TrustedAsTemplate |
| 57 |
from ansible.parsing.dataloader import DataLoader |
| 58 |
from ansible.playbook.role.requirement import RoleRequirement |
| 59 |
from ansible._internal._templating._engine import TemplateEngine |
| 60 |
from ansible.template import trust_as_template |
| 61 |
from ansible.utils.collection_loader import AnsibleCollectionConfig |
| 62 |
from ansible.utils.display import Display |
| 63 |
from ansible.utils.plugin_docs import get_versioned_doclink |
| 64 |
from ansible.utils.vars import load_extra_vars |
| 65 |
|
| 66 |
display = Display() |
| 67 |
|
| 68 |
|
| 69 |
def with_collection_artifacts_manager(wrapped_method): |
| 70 |
"""Inject an artifacts manager if not passed explicitly. |
| 71 |
|
| 72 |
This decorator constructs a ConcreteArtifactsManager and maintains |
| 73 |
the related temporary directory auto-cleanup around the target |
| 74 |
method invocation. |
| 75 |
""" |
| 76 |
@functools.wraps(wrapped_method) |
| 77 |
def method_wrapper(*args, **kwargs): |
| 78 |
if 'artifacts_manager' in kwargs: |
| 79 |
return wrapped_method(*args, **kwargs) |
| 80 |
|
| 81 |
# configures validate_certs for type 'url' only |
| 82 |
# type 'galaxy' inherits and overrides resolved_validate_certs |
| 83 |
# type 'git' recalculates resolved_validate_certs |
| 84 |
# NOTE: .get used here for when this is used in a non-CLI context |
| 85 |
artifacts_manager_kwargs = {'validate_certs': context.CLIARGS.get('resolved_validate_certs', True)} |
| 86 |
|
| 87 |
keyring = context.CLIARGS.get('keyring', None) |
| 88 |
if keyring is not None: |
| 89 |
artifacts_manager_kwargs.update({ |
| 90 |
'keyring': GalaxyCLI._resolve_path(keyring), |
| 91 |
'required_signature_count': context.CLIARGS.get('required_valid_signature_count', None), |
| 92 |
'ignore_signature_errors': context.CLIARGS.get('ignore_gpg_errors', None), |
| 93 |
}) |
| 94 |
|
| 95 |
with ConcreteArtifactsManager.under_tmpdir( |
| 96 |
C.DEFAULT_LOCAL_TMP, |
| 97 |
**artifacts_manager_kwargs |
| 98 |
) as concrete_artifact_cm: |
| 99 |
kwargs['artifacts_manager'] = concrete_artifact_cm |
| 100 |
return wrapped_method(*args, **kwargs) |
| 101 |
return method_wrapper |
| 102 |
|
| 103 |
|
| 104 |
def _display_header(path, h1, h2, w1=10, w2=7): |
| 105 |
display.display('\n# {0}\n{1:{cwidth}} {2:{vwidth}}\n{3} {4}\n'.format( |
| 106 |
path, |
| 107 |
h1, |
| 108 |
h2, |
| 109 |
'-' * max([len(h1), w1]), # Make sure that the number of dashes is at least the width of the header |
| 110 |
'-' * max([len(h2), w2]), |
| 111 |
cwidth=w1, |
| 112 |
vwidth=w2, |
| 113 |
)) |
| 114 |
|
| 115 |
|
| 116 |
def _display_role(gr): |
| 117 |
install_info = gr.install_info |
| 118 |
version = None |
| 119 |
if install_info: |
| 120 |
version = install_info.get("version", None) |
| 121 |
if not version: |
| 122 |
version = "(unknown version)" |
| 123 |
display.display("- %s, %s" % (gr.name, version)) |
| 124 |
|
| 125 |
|
| 126 |
def _display_collection(collection, cwidth=10, vwidth=7, min_cwidth=10, min_vwidth=7): |
| 127 |
display.display('{fqcn:{cwidth}} {version:{vwidth}}'.format( |
| 128 |
fqcn=to_text(collection.fqcn), |
| 129 |
version=collection.ver, |
| 130 |
cwidth=max(cwidth, min_cwidth), # Make sure the width isn't smaller than the header |
| 131 |
vwidth=max(vwidth, min_vwidth) |
| 132 |
)) |
| 133 |
|
| 134 |
|
| 135 |
def _get_collection_widths(collections): |
| 136 |
if not is_iterable(collections): |
| 137 |
collections = (collections, ) |
| 138 |
|
| 139 |
fqcn_set = {to_text(c.fqcn) for c in collections} |
| 140 |
version_set = {to_text(c.ver) for c in collections} |
| 141 |
|
| 142 |
fqcn_length = len(max(fqcn_set or [''], key=len)) |
| 143 |
version_length = len(max(version_set or [''], key=len)) |
| 144 |
|
| 145 |
return fqcn_length, version_length |
| 146 |
|
| 147 |
|
| 148 |
def validate_signature_count(value): |
| 149 |
match = re.match(SIGNATURE_COUNT_RE, value) |
| 150 |
|
| 151 |
if match is None: |
| 152 |
raise ValueError(f"{value} is not a valid signature count value") |
| 153 |
|
| 154 |
return value |
| 155 |
|
| 156 |
|
| 157 |
@dataclass |
| 158 |
class RoleDistributionServer: |
| 159 |
_api: t.Union[GalaxyAPI, None] |
| 160 |
api_servers: list[GalaxyAPI] |
| 161 |
|
| 162 |
@property |
| 163 |
def api(self): |
| 164 |
if self._api: |
| 165 |
return self._api |
| 166 |
|
| 167 |
for server in self.api_servers: |
| 168 |
try: |
| 169 |
if u'v1' in server.available_api_versions: |
| 170 |
self._api = server |
| 171 |
break |
| 172 |
except Exception: |
| 173 |
continue |
| 174 |
|
| 175 |
if not self._api: |
| 176 |
self._api = self.api_servers[0] |
| 177 |
|
| 178 |
return self._api |
| 179 |
|
| 180 |
|
| 181 |
class GalaxyCLI(CLI): |
| 182 |
"""Command to manage Ansible roles and collections. |
| 183 |
|
| 184 |
None of the CLI tools are designed to run concurrently with themselves. |
| 185 |
Use an external scheduler and/or locking to ensure there are no clashing operations. |
| 186 |
""" |
| 187 |
|
| 188 |
name = 'ansible-galaxy' |
| 189 |
|
| 190 |
SKIP_INFO_KEYS = ("name", "description", "readme_html", "related", "summary_fields", "average_aw_composite", "average_aw_score", "url") |
| 191 |
|
| 192 |
def __init__(self, args): |
| 193 |
self._raw_args = args |
| 194 |
self._implicit_role = False |
| 195 |
|
| 196 |
if len(args) > 1: |
| 197 |
# Inject role into sys.argv[1] as a backwards compatibility step |
| 198 |
if args[1] not in ['-h', '--help', '--version'] and 'role' not in args and 'collection' not in args: |
| 199 |
# TODO: Should we add a warning here and eventually deprecate the implicit role subcommand choice |
| 200 |
args.insert(1, 'role') |
| 201 |
self._implicit_role = True |
| 202 |
# since argparse doesn't allow hidden subparsers, handle dead login arg from raw args after "role" normalization |
| 203 |
if args[1:3] == ['role', 'login']: |
| 204 |
display.error( |
| 205 |
"The login command was removed in late 2020. An API key is now required to publish roles or collections " |
| 206 |
"to Galaxy. The key can be found at https://galaxy.ansible.com/ui/token, and passed to the " |
| 207 |
"ansible-galaxy CLI via a file at {0} or (insecurely) via the `--token` " |
| 208 |
"command-line argument.".format(to_text(C.GALAXY_TOKEN_PATH))) |
| 209 |
sys.exit(1) |
| 210 |
|
| 211 |
self.api_servers = [] |
| 212 |
self.galaxy = None |
| 213 |
self.lazy_role_api = None |
| 214 |
super(GalaxyCLI, self).__init__(args) |
| 215 |
|
| 216 |
@property |
| 217 |
def collection_paths(self): |
| 218 |
""" |
| 219 |
Exclude lib/ansible/_internal/ansible_collections/. |
| 220 |
""" |
| 221 |
# exclude bundled collections, e.g. ansible._protomatter |
| 222 |
return [ |
| 223 |
path |
| 224 |
for path in AnsibleCollectionConfig.collection_paths |
| 225 |
if path != AnsibleCollectionConfig._internal_collections |
| 226 |
] |
| 227 |
|
| 228 |
def init_parser(self): |
| 229 |
""" create an options parser for bin/ansible """ |
| 230 |
|
| 231 |
super(GalaxyCLI, self).init_parser( |
| 232 |
desc="Perform various Role and Collection related operations.", |
| 233 |
) |
| 234 |
|
| 235 |
# Common arguments that apply to more than 1 action |
| 236 |
common = opt_help.ArgumentParser(add_help=False) |
| 237 |
common.add_argument('-s', '--server', dest='api_server', help='The Galaxy API server URL') |
| 238 |
common.add_argument('--api-version', type=int, choices=[2, 3], help=argparse.SUPPRESS) # Hidden argument that should only be used in our tests |
| 239 |
common.add_argument('--token', '--api-key', dest='api_key', |
| 240 |
help='The Ansible Galaxy API key which can be found at ' |
| 241 |
'https://galaxy.ansible.com/ui/token.') |
| 242 |
common.add_argument('-c', '--ignore-certs', action='store_true', dest='ignore_certs', help='Ignore SSL certificate validation errors.', default=None) |
| 243 |
|
| 244 |
# --timeout uses the default None to handle two different scenarios. |
| 245 |
# * --timeout > C.GALAXY_SERVER_TIMEOUT for non-configured servers |
| 246 |
# * --timeout > server-specific timeout > C.GALAXY_SERVER_TIMEOUT for configured servers. |
| 247 |
common.add_argument('--timeout', dest='timeout', type=int, |
| 248 |
help="The time to wait for operations against the galaxy server, defaults to 60s.") |
| 249 |
|
| 250 |
opt_help.add_verbosity_options(common) |
| 251 |
|
| 252 |
force = opt_help.ArgumentParser(add_help=False) |
| 253 |
force.add_argument('-f', '--force', dest='force', action='store_true', default=False, |
| 254 |
help='Force overwriting an existing role or collection') |
| 255 |
|
| 256 |
github = opt_help.ArgumentParser(add_help=False) |
| 257 |
github.add_argument('github_user', help='GitHub username') |
| 258 |
github.add_argument('github_repo', help='GitHub repository') |
| 259 |
|
| 260 |
offline = opt_help.ArgumentParser(add_help=False) |
| 261 |
offline.add_argument('--offline', dest='offline', default=False, action='store_true', |
| 262 |
help="Don't query the galaxy API when creating roles") |
| 263 |
|
| 264 |
default_roles_path = C.config.get_configuration_definition('DEFAULT_ROLES_PATH').get('default', '') |
| 265 |
roles_path = opt_help.ArgumentParser(add_help=False) |
| 266 |
roles_path.add_argument('-p', '--roles-path', dest='roles_path', type=opt_help.unfrack_path(pathsep=True), |
| 267 |
default=C.DEFAULT_ROLES_PATH, action=opt_help.PrependListAction, |
| 268 |
help='The path to the directory containing your roles. The default is the first ' |
| 269 |
'writable one configured via DEFAULT_ROLES_PATH: %s ' % default_roles_path) |
| 270 |
|
| 271 |
collections_path = opt_help.ArgumentParser(add_help=False) |
| 272 |
collections_path.add_argument('-p', '--collections-path', dest='collections_path', type=opt_help.unfrack_path(pathsep=True), |
| 273 |
action=opt_help.PrependListAction, |
| 274 |
help="One or more directories to search for collections in addition " |
| 275 |
"to the default COLLECTIONS_PATHS. Separate multiple paths " |
| 276 |
"with '{0}'.".format(os.path.pathsep)) |
| 277 |
|
| 278 |
cache_options = opt_help.ArgumentParser(add_help=False) |
| 279 |
cache_options.add_argument('--clear-response-cache', dest='clear_response_cache', action='store_true', |
| 280 |
default=False, help='Clear the existing server response cache.') |
| 281 |
cache_options.add_argument('--no-cache', dest='no_cache', action='store_true', default=False, |
| 282 |
help='Do not use the server response cache.') |
| 283 |
|
| 284 |
# Add sub parser for the Galaxy role type (role or collection) |
| 285 |
type_parser = self.parser.add_subparsers(metavar='TYPE', dest='type') |
| 286 |
type_parser.required = True |
| 287 |
|
| 288 |
# Add sub parser for the Galaxy collection actions |
| 289 |
collection = type_parser.add_parser('collection', help='Manage an Ansible Galaxy collection.') |
| 290 |
collection.set_defaults(func=self.execute_collection) # to satisfy doc build |
| 291 |
collection_parser = collection.add_subparsers(metavar='COLLECTION_ACTION', dest='action') |
| 292 |
collection_parser.required = True |
| 293 |
self.add_download_options(collection_parser, parents=[common, cache_options]) |
| 294 |
self.add_init_options(collection_parser, parents=[common, force]) |
| 295 |
self.add_build_options(collection_parser, parents=[common, force]) |
| 296 |
self.add_publish_options(collection_parser, parents=[common]) |
| 297 |
self.add_install_options(collection_parser, parents=[common, force, cache_options]) |
| 298 |
self.add_list_options(collection_parser, parents=[common, collections_path]) |
| 299 |
self.add_verify_options(collection_parser, parents=[common, collections_path]) |
| 300 |
|
| 301 |
# Add sub parser for the Galaxy role actions |
| 302 |
role = type_parser.add_parser('role', help='Manage an Ansible Galaxy role.') |
| 303 |
role.set_defaults(func=self.execute_role) # to satisfy doc build |
| 304 |
role_parser = role.add_subparsers(metavar='ROLE_ACTION', dest='action') |
| 305 |
role_parser.required = True |
| 306 |
self.add_init_options(role_parser, parents=[common, force, offline]) |
| 307 |
self.add_remove_options(role_parser, parents=[common, roles_path]) |
| 308 |
self.add_delete_options(role_parser, parents=[common, github]) |
| 309 |
self.add_list_options(role_parser, parents=[common, roles_path]) |
| 310 |
self.add_search_options(role_parser, parents=[common]) |
| 311 |
self.add_import_options(role_parser, parents=[common, github]) |
| 312 |
self.add_setup_options(role_parser, parents=[common, roles_path]) |
| 313 |
|
| 314 |
self.add_info_options(role_parser, parents=[common, roles_path, offline]) |
| 315 |
self.add_install_options(role_parser, parents=[common, force, roles_path]) |
| 316 |
|
| 317 |
def add_download_options(self, parser, parents=None): |
| 318 |
download_parser = parser.add_parser('download', parents=parents, |
| 319 |
help='Download collections and their dependencies as a tarball for an ' |
| 320 |
'offline install.') |
| 321 |
download_parser.set_defaults(func=self.execute_download) |
| 322 |
|
| 323 |
download_parser.add_argument('args', help='Collection(s)', metavar='collection', nargs='*') |
| 324 |
|
| 325 |
download_parser.add_argument('-n', '--no-deps', dest='no_deps', action='store_true', default=False, |
| 326 |
help="Don't download collection(s) listed as dependencies.") |
| 327 |
|
| 328 |
download_parser.add_argument('-p', '--download-path', dest='download_path', |
| 329 |
default='./collections', |
| 330 |
help='The directory to download the collections to.') |
| 331 |
download_parser.add_argument('-r', '--requirements-file', dest='requirements', |
| 332 |
help='A file containing a list of collections to be downloaded.') |
| 333 |
download_parser.add_argument('--pre', dest='allow_pre_release', action='store_true', |
| 334 |
help='Include pre-release versions. Semantic versioning pre-releases are ignored by default') |
| 335 |
|
| 336 |
def add_init_options(self, parser, parents=None): |
| 337 |
galaxy_type = 'collection' if parser.metavar == 'COLLECTION_ACTION' else 'role' |
| 338 |
|
| 339 |
init_parser = parser.add_parser('init', parents=parents, |
| 340 |
help='Initialize new {0} with the base structure of a ' |
| 341 |
'{0}.'.format(galaxy_type)) |
| 342 |
init_parser.set_defaults(func=self.execute_init) |
| 343 |
|
| 344 |
init_parser.add_argument('--init-path', dest='init_path', default='./', |
| 345 |
help='The path in which the skeleton {0} will be created. The default is the ' |
| 346 |
'current working directory.'.format(galaxy_type)) |
| 347 |
init_parser.add_argument('--{0}-skeleton'.format(galaxy_type), dest='{0}_skeleton'.format(galaxy_type), |
| 348 |
default=C.GALAXY_COLLECTION_SKELETON if galaxy_type == 'collection' else C.GALAXY_ROLE_SKELETON, |
| 349 |
help='The path to a {0} skeleton that the new {0} should be based ' |
| 350 |
'upon.'.format(galaxy_type)) |
| 351 |
|
| 352 |
obj_name_kwargs = {} |
| 353 |
if galaxy_type == 'collection': |
| 354 |
obj_name_kwargs['type'] = validate_collection_name |
| 355 |
init_parser.add_argument('{0}_name'.format(galaxy_type), help='{0} name'.format(galaxy_type.capitalize()), |
| 356 |
**obj_name_kwargs) |
| 357 |
|
| 358 |
if galaxy_type == 'role': |
| 359 |
init_parser.add_argument('--type', dest='role_type', action='store', default='default', |
| 360 |
help="Initialize using an alternate role type. Valid types include: 'container', " |
| 361 |
"'apb' and 'network'.") |
| 362 |
opt_help.add_runtask_options(init_parser) |
| 363 |
|
| 364 |
def add_remove_options(self, parser, parents=None): |
| 365 |
remove_parser = parser.add_parser('remove', parents=parents, help='Delete roles from roles_path.') |
| 366 |
remove_parser.set_defaults(func=self.execute_remove) |
| 367 |
|
| 368 |
remove_parser.add_argument('args', help='Role(s)', metavar='role', nargs='+') |
| 369 |
|
| 370 |
def add_delete_options(self, parser, parents=None): |
| 371 |
delete_parser = parser.add_parser('delete', parents=parents, |
| 372 |
help='Removes the role from Galaxy. It does not remove or alter the actual ' |
| 373 |
'GitHub repository.') |
| 374 |
delete_parser.set_defaults(func=self.execute_delete) |
| 375 |
|
| 376 |
def add_list_options(self, parser, parents=None): |
| 377 |
galaxy_type = 'role' |
| 378 |
if parser.metavar == 'COLLECTION_ACTION': |
| 379 |
galaxy_type = 'collection' |
| 380 |
|
| 381 |
list_parser = parser.add_parser('list', parents=parents, |
| 382 |
help='Show the name and version of each {0} installed in the {0}s_path.'.format(galaxy_type)) |
| 383 |
|
| 384 |
list_parser.set_defaults(func=self.execute_list) |
| 385 |
|
| 386 |
list_parser.add_argument(galaxy_type, help=galaxy_type.capitalize(), nargs='?', metavar=galaxy_type) |
| 387 |
|
| 388 |
if galaxy_type == 'collection': |
| 389 |
list_parser.add_argument('--format', dest='output_format', choices=('human', 'yaml', 'json'), default='human', |
| 390 |
help="Format to display the list of collections in.") |
| 391 |
|
| 392 |
def add_search_options(self, parser, parents=None): |
| 393 |
search_parser = parser.add_parser('search', parents=parents, |
| 394 |
help='Search the Galaxy database by tags, platforms, author and multiple ' |
| 395 |
'keywords.') |
| 396 |
search_parser.set_defaults(func=self.execute_search) |
| 397 |
|
| 398 |
search_parser.add_argument('--platforms', dest='platforms', help='list of OS platforms to filter by') |
| 399 |
search_parser.add_argument('--galaxy-tags', dest='galaxy_tags', help='list of galaxy tags to filter by') |
| 400 |
search_parser.add_argument('--author', dest='author', help='GitHub username') |
| 401 |
search_parser.add_argument('args', help='Search terms', metavar='searchterm', nargs='*') |
| 402 |
|
| 403 |
def add_import_options(self, parser, parents=None): |
| 404 |
import_parser = parser.add_parser('import', parents=parents, help='Import a role into a galaxy server') |
| 405 |
import_parser.set_defaults(func=self.execute_import) |
| 406 |
|
| 407 |
import_parser.add_argument('--no-wait', dest='wait', action='store_false', default=True, |
| 408 |
help="Don't wait for import results.") |
| 409 |
import_parser.add_argument('--branch', dest='reference', |
| 410 |
help='The name of a branch to import. Defaults to the repository\'s default branch ' |
| 411 |
'(usually master)') |
| 412 |
import_parser.add_argument('--role-name', dest='role_name', |
| 413 |
help='The name the role should have, if different than the repo name') |
| 414 |
import_parser.add_argument('--status', dest='check_status', action='store_true', default=False, |
| 415 |
help='Check the status of the most recent import request for given github_' |
| 416 |
'user/github_repo.') |
| 417 |
|
| 418 |
def add_setup_options(self, parser, parents=None): |
| 419 |
setup_parser = parser.add_parser('setup', parents=parents, |
| 420 |
help='Manage the integration between Galaxy and the given source.') |
| 421 |
setup_parser.set_defaults(func=self.execute_setup) |
| 422 |
|
| 423 |
setup_parser.add_argument('--remove', dest='remove_id', default=None, |
| 424 |
help='Remove the integration matching the provided ID value. Use --list to see ' |
| 425 |
'ID values.') |
| 426 |
setup_parser.add_argument('--list', dest="setup_list", action='store_true', default=False, |
| 427 |
help='List all of your integrations.') |
| 428 |
setup_parser.add_argument('source', help='Source') |
| 429 |
setup_parser.add_argument('github_user', help='GitHub username') |
| 430 |
setup_parser.add_argument('github_repo', help='GitHub repository') |
| 431 |
setup_parser.add_argument('secret', help='Secret') |
| 432 |
|
| 433 |
def add_info_options(self, parser, parents=None): |
| 434 |
info_parser = parser.add_parser('info', parents=parents, help='View more details about a specific role.') |
| 435 |
info_parser.set_defaults(func=self.execute_info) |
| 436 |
|
| 437 |
info_parser.add_argument('args', nargs='+', help='role', metavar='role_name[,version]') |
| 438 |
|
| 439 |
def add_verify_options(self, parser, parents=None): |
| 440 |
galaxy_type = 'collection' |
| 441 |
verify_parser = parser.add_parser('verify', parents=parents, help='Compare checksums with the collection(s) ' |
| 442 |
'found on the server and the installed copy. This does not verify dependencies.') |
| 443 |
verify_parser.set_defaults(func=self.execute_verify) |
| 444 |
|
| 445 |
verify_parser.add_argument('args', metavar='{0}_name'.format(galaxy_type), nargs='*', help='The installed collection(s) name. ' |
| 446 |
'This is mutually exclusive with --requirements-file.') |
| 447 |
verify_parser.add_argument('-i', '--ignore-errors', dest='ignore_errors', action='store_true', default=False, |
| 448 |
help='Ignore errors during verification and continue with the next specified collection.') |
| 449 |
verify_parser.add_argument('--offline', dest='offline', action='store_true', default=False, |
| 450 |
help='Validate collection integrity locally without contacting server for ' |
| 451 |
'canonical manifest hash.') |
| 452 |
verify_parser.add_argument('-r', '--requirements-file', dest='requirements', |
| 453 |
help='A file containing a list of collections to be verified.') |
| 454 |
verify_parser.add_argument('--keyring', dest='keyring', default=C.GALAXY_GPG_KEYRING, |
| 455 |
help='The keyring used during signature verification') # Eventually default to ~/.ansible/pubring.kbx? |
| 456 |
verify_parser.add_argument('--signature', dest='signatures', action='append', |
| 457 |
help='An additional signature source to verify the authenticity of the MANIFEST.json before using ' |
| 458 |
'it to verify the rest of the contents of a collection from a Galaxy server. Use in ' |
| 459 |
'conjunction with a positional collection name (mutually exclusive with --requirements-file).') |
| 460 |
valid_signature_count_help = 'The number of signatures that must successfully verify the collection. This should be a positive integer ' \ |
| 461 |
'or all to signify that all signatures must be used to verify the collection. ' \ |
| 462 |
'Prepend the value with + to fail if no valid signatures are found for the collection (e.g. +all).' |
| 463 |
ignore_gpg_status_help = 'A space separated list of status codes to ignore during signature verification (for example, NO_PUBKEY FAILURE). ' \ |
| 464 |
'Descriptions for the choices can be seen at L(https://github.com/gpg/gnupg/blob/master/doc/DETAILS#general-status-codes).' \ |
| 465 |
'Note: specify these after positional arguments or use -- to separate them.' |
| 466 |
verify_parser.add_argument('--required-valid-signature-count', dest='required_valid_signature_count', type=validate_signature_count, |
| 467 |
help=valid_signature_count_help, default=C.GALAXY_REQUIRED_VALID_SIGNATURE_COUNT) |
| 468 |
verify_parser.add_argument('--ignore-signature-status-code', dest='ignore_gpg_errors', type=str, action='append', |
| 469 |
help=opt_help.argparse.SUPPRESS, default=C.GALAXY_IGNORE_INVALID_SIGNATURE_STATUS_CODES, |
| 470 |
choices=list(GPG_ERROR_MAP.keys())) |
| 471 |
verify_parser.add_argument('--ignore-signature-status-codes', dest='ignore_gpg_errors', type=str, action='extend', nargs='+', |
| 472 |
help=ignore_gpg_status_help, default=C.GALAXY_IGNORE_INVALID_SIGNATURE_STATUS_CODES, |
| 473 |
choices=list(GPG_ERROR_MAP.keys())) |
| 474 |
|
| 475 |
def add_install_options(self, parser, parents=None): |
| 476 |
galaxy_type = 'collection' if parser.metavar == 'COLLECTION_ACTION' else 'role' |
| 477 |
|
| 478 |
args_kwargs = {} |
| 479 |
if galaxy_type == 'collection': |
| 480 |
args_kwargs['help'] = 'The collection(s) name or path/url to a tar.gz collection artifact. This is ' \ |
| 481 |
'mutually exclusive with --requirements-file.' |
| 482 |
ignore_errors_help = 'Ignore errors during installation and continue with the next specified ' \ |
| 483 |
'collection. This will not ignore dependency conflict errors.' |
| 484 |
else: |
| 485 |
args_kwargs['help'] = 'Role name, URL or tar file. This is mutually exclusive with -r.' |
| 486 |
ignore_errors_help = 'Ignore errors and continue with the next specified role.' |
| 487 |
|
| 488 |
if self._implicit_role: |
| 489 |
# might install both roles and collections |
| 490 |
description_text = ( |
| 491 |
'Install roles and collections from file(s), URL(s) or Ansible ' |
| 492 |
'Galaxy to the first entry in the config COLLECTIONS_PATH for collections ' |
| 493 |
'and first entry in the config ROLES_PATH for roles. ' |
| 494 |
'The first entry in the config ROLES_PATH can be overridden by --roles-path ' |
| 495 |
'or -p, but this will result in only roles being installed.' |
| 496 |
) |
| 497 |
prog = 'ansible-galaxy install' |
| 498 |
else: |
| 499 |
prog = f"ansible-galaxy {galaxy_type} install" |
| 500 |
description_text = ( |
| 501 |
'Install {0}(s) from file(s), URL(s) or Ansible ' |
| 502 |
'Galaxy to the first entry in the config {1}S_PATH ' |
| 503 |
'unless overridden by --{0}s-path.'.format(galaxy_type, galaxy_type.upper()) |
| 504 |
) |
| 505 |
install_parser = parser.add_parser('install', parents=parents, |
| 506 |
help='Install {0}(s) from file(s), URL(s) or Ansible ' |
| 507 |
'Galaxy'.format(galaxy_type), |
| 508 |
description=description_text, |
| 509 |
prog=prog,) |
| 510 |
install_parser.set_defaults(func=self.execute_install) |
| 511 |
|
| 512 |
install_parser.add_argument('args', metavar='{0}_name'.format(galaxy_type), nargs='*', **args_kwargs) |
| 513 |
install_parser.add_argument('-i', '--ignore-errors', dest='ignore_errors', action='store_true', default=False, |
| 514 |
help=ignore_errors_help) |
| 515 |
|
| 516 |
install_exclusive = install_parser.add_mutually_exclusive_group() |
| 517 |
install_exclusive.add_argument('-n', '--no-deps', dest='no_deps', action='store_true', default=False, |
| 518 |
help="Don't download {0}s listed as dependencies.".format(galaxy_type)) |
| 519 |
install_exclusive.add_argument('--force-with-deps', dest='force_with_deps', action='store_true', default=False, |
| 520 |
help="Force overwriting an existing {0} and its " |
| 521 |
"dependencies.".format(galaxy_type)) |
| 522 |
|
| 523 |
valid_signature_count_help = 'The number of signatures that must successfully verify the collection. This should be a positive integer ' \ |
| 524 |
'or -1 to signify that all signatures must be used to verify the collection. ' \ |
| 525 |
'Prepend the value with + to fail if no valid signatures are found for the collection (e.g. +all).' |
| 526 |
ignore_gpg_status_help = 'A space separated list of status codes to ignore during signature verification (for example, NO_PUBKEY FAILURE). ' \ |
| 527 |
'Descriptions for the choices can be seen at L(https://github.com/gpg/gnupg/blob/master/doc/DETAILS#general-status-codes).' \ |
| 528 |
'Note: specify these after positional arguments or use -- to separate them.' |
| 529 |
|
| 530 |
if galaxy_type == 'collection': |
| 531 |
install_parser.add_argument('-p', '--collections-path', dest='collections_path', |
| 532 |
default=self._get_default_collection_path(), |
| 533 |
help='The path to the directory containing your collections.') |
| 534 |
install_parser.add_argument('-r', '--requirements-file', dest='requirements', |
| 535 |
help='A file containing a list of collections to be installed.') |
| 536 |
install_parser.add_argument('--pre', dest='allow_pre_release', action='store_true', |
| 537 |
help='Include pre-release versions. Semantic versioning pre-releases are ignored by default') |
| 538 |
install_parser.add_argument('-U', '--upgrade', dest='upgrade', action='store_true', default=False, |
| 539 |
help='Upgrade installed collection artifacts. This will also update dependencies unless --no-deps is provided') |
| 540 |
install_parser.add_argument('--keyring', dest='keyring', default=C.GALAXY_GPG_KEYRING, |
| 541 |
help='The keyring used during signature verification') # Eventually default to ~/.ansible/pubring.kbx? |
| 542 |
install_parser.add_argument('--disable-gpg-verify', dest='disable_gpg_verify', action='store_true', |
| 543 |
default=C.GALAXY_DISABLE_GPG_VERIFY, |
| 544 |
help='Disable GPG signature verification when installing collections from a Galaxy server') |
| 545 |
install_parser.add_argument('--signature', dest='signatures', action='append', |
| 546 |
help='An additional signature source to verify the authenticity of the MANIFEST.json before ' |
| 547 |
'installing the collection from a Galaxy server. Use in conjunction with a positional ' |
| 548 |
'collection name (mutually exclusive with --requirements-file).') |
| 549 |
install_parser.add_argument('--required-valid-signature-count', dest='required_valid_signature_count', type=validate_signature_count, |
| 550 |
help=valid_signature_count_help, default=C.GALAXY_REQUIRED_VALID_SIGNATURE_COUNT) |
| 551 |
install_parser.add_argument('--ignore-signature-status-code', dest='ignore_gpg_errors', type=str, action='append', |
| 552 |
help=opt_help.argparse.SUPPRESS, default=C.GALAXY_IGNORE_INVALID_SIGNATURE_STATUS_CODES, |
| 553 |
choices=list(GPG_ERROR_MAP.keys())) |
| 554 |
install_parser.add_argument('--ignore-signature-status-codes', dest='ignore_gpg_errors', type=str, action='extend', nargs='+', |
| 555 |
help=ignore_gpg_status_help, default=C.GALAXY_IGNORE_INVALID_SIGNATURE_STATUS_CODES, |
| 556 |
choices=list(GPG_ERROR_MAP.keys())) |
| 557 |
install_parser.add_argument('--offline', dest='offline', action='store_true', default=False, |
| 558 |
help='Install collection artifacts (tarballs) without contacting any distribution servers. ' |
| 559 |
'This does not apply to collections in remote Git repositories or URLs to remote tarballs.' |
| 560 |
) |
| 561 |
else: |
| 562 |
if self._implicit_role: |
| 563 |
install_parser.add_argument('-r', '--role-file', dest='requirements', |
| 564 |
help='A file containing a list of collections and roles to be installed.') |
| 565 |
else: |
| 566 |
install_parser.add_argument('-r', '--role-file', dest='requirements', |
| 567 |
help='A file containing a list of roles to be installed.') |
| 568 |
|
| 569 |
r_re = re.compile(r'^(?<!-)-[a-zA-Z]*r[a-zA-Z]*') # -r, -fr |
| 570 |
contains_r = bool([a for a in self._raw_args if r_re.match(a)]) |
| 571 |
role_file_re = re.compile(r'--role-file($|=)') # --role-file foo, --role-file=foo |
| 572 |
contains_role_file = bool([a for a in self._raw_args if role_file_re.match(a)]) |
| 573 |
if self._implicit_role and (contains_r or contains_role_file): |
| 574 |
# Any collections in the requirements files will also be installed |
| 575 |
install_parser.add_argument('--keyring', dest='keyring', default=C.GALAXY_GPG_KEYRING, |
| 576 |
help='The keyring used during collection signature verification') |
| 577 |
install_parser.add_argument('--disable-gpg-verify', dest='disable_gpg_verify', action='store_true', |
| 578 |
default=C.GALAXY_DISABLE_GPG_VERIFY, |
| 579 |
help='Disable GPG signature verification when installing collections from a Galaxy server') |
| 580 |
install_parser.add_argument('--required-valid-signature-count', dest='required_valid_signature_count', type=validate_signature_count, |
| 581 |
help=valid_signature_count_help, default=C.GALAXY_REQUIRED_VALID_SIGNATURE_COUNT) |
| 582 |
install_parser.add_argument('--ignore-signature-status-code', dest='ignore_gpg_errors', type=str, action='append', |
| 583 |
help=opt_help.argparse.SUPPRESS, default=C.GALAXY_IGNORE_INVALID_SIGNATURE_STATUS_CODES, |
| 584 |
choices=list(GPG_ERROR_MAP.keys())) |
| 585 |
install_parser.add_argument('--ignore-signature-status-codes', dest='ignore_gpg_errors', type=str, action='extend', nargs='+', |
| 586 |
help=ignore_gpg_status_help, default=C.GALAXY_IGNORE_INVALID_SIGNATURE_STATUS_CODES, |
| 587 |
choices=list(GPG_ERROR_MAP.keys())) |
| 588 |
|
| 589 |
install_parser.add_argument('-g', '--keep-scm-meta', dest='keep_scm_meta', action='store_true', |
| 590 |
default=False, |
| 591 |
help='Use tar instead of the scm archive option when packaging the role.') |
| 592 |
|
| 593 |
def add_build_options(self, parser, parents=None): |
| 594 |
build_parser = parser.add_parser('build', parents=parents, |
| 595 |
help='Build an Ansible collection artifact that can be published to Ansible ' |
| 596 |
'Galaxy.') |
| 597 |
build_parser.set_defaults(func=self.execute_build) |
| 598 |
|
| 599 |
build_parser.add_argument('args', metavar='collection', nargs='*', default=('.',), |
| 600 |
help='Path to the collection(s) directory to build. This should be the directory ' |
| 601 |
'that contains the galaxy.yml file. The default is the current working ' |
| 602 |
'directory.') |
| 603 |
build_parser.add_argument('--output-path', dest='output_path', default='./', |
| 604 |
help='The path in which the collection is built to. The default is the current ' |
| 605 |
'working directory.') |
| 606 |
|
| 607 |
def add_publish_options(self, parser, parents=None): |
| 608 |
publish_parser = parser.add_parser('publish', parents=parents, |
| 609 |
help='Publish a collection artifact to Ansible Galaxy.') |
| 610 |
publish_parser.set_defaults(func=self.execute_publish) |
| 611 |
|
| 612 |
publish_parser.add_argument('args', metavar='collection_path', |
| 613 |
help='The path to the collection tarball to publish.') |
| 614 |
publish_parser.add_argument('--no-wait', dest='wait', action='store_false', default=True, |
| 615 |
help="Don't wait for import validation results.") |
| 616 |
publish_parser.add_argument('--import-timeout', dest='import_timeout', type=int, default=0, |
| 617 |
help="The time to wait for the collection import process to finish.") |
| 618 |
|
| 619 |
def post_process_args(self, options): |
| 620 |
options = super(GalaxyCLI, self).post_process_args(options) |
| 621 |
|
| 622 |
# ensure we have 'usable' cli option |
| 623 |
setattr(options, 'validate_certs', (None if options.ignore_certs is None else not options.ignore_certs)) |
| 624 |
# the default if validate_certs is None |
| 625 |
setattr(options, 'resolved_validate_certs', (options.validate_certs if options.validate_certs is not None else not C.GALAXY_IGNORE_CERTS)) |
| 626 |
|
| 627 |
display.verbosity = options.verbosity |
| 628 |
return options |
| 629 |
|
| 630 |
def run(self): |
| 631 |
|
| 632 |
super(GalaxyCLI, self).run() |
| 633 |
|
| 634 |
self.galaxy = Galaxy() |
| 635 |
|
| 636 |
# dynamically add per server config depending on declared servers |
| 637 |
C.config.load_galaxy_server_defs(C.GALAXY_SERVER_LIST) |
| 638 |
|
| 639 |
galaxy_options = {} |
| 640 |
for optional_key in ['clear_response_cache', 'no_cache']: |
| 641 |
if optional_key in context.CLIARGS: |
| 642 |
galaxy_options[optional_key] = context.CLIARGS[optional_key] |
| 643 |
|
| 644 |
config_servers = [] |
| 645 |
# Need to filter out empty strings or non truthy values as an empty server list env var is equal to ['']. |
| 646 |
server_list = [s for s in C.GALAXY_SERVER_LIST or [] if s] |
| 647 |
for server_priority, server_key in enumerate(server_list, start=1): |
| 648 |
|
| 649 |
# resolve the config created options above with existing config and user options |
| 650 |
server_options = C.config.get_plugin_options(plugin_type='galaxy_server', name=server_key) |
| 651 |
|
| 652 |
# auth_url is used to create the token, but not directly by GalaxyAPI, so |
| 653 |
# it doesn't need to be passed as kwarg to GalaxyApi, same for others we pop here |
| 654 |
auth_url = server_options.pop('auth_url') |
| 655 |
client_id = server_options.pop('client_id') |
| 656 |
client_secret = server_options.pop('client_secret') |
| 657 |
token_val = server_options['token'] or NoTokenSentinel |
| 658 |
username = server_options['username'] |
| 659 |
if server_options['validate_certs'] is None: |
| 660 |
server_options['validate_certs'] = context.CLIARGS['resolved_validate_certs'] |
| 661 |
validate_certs = server_options['validate_certs'] |
| 662 |
|
| 663 |
# default case if no auth info is provided. |
| 664 |
server_options['token'] = None |
| 665 |
|
| 666 |
if username: |
| 667 |
server_options['token'] = BasicAuthToken(username, server_options['password']) |
| 668 |
else: |
| 669 |
if auth_url: |
| 670 |
server_options['token'] = KeycloakToken( |
| 671 |
access_token=token_val, |
| 672 |
auth_url=auth_url, |
| 673 |
validate_certs=validate_certs, |
| 674 |
client_id=client_id, |
| 675 |
client_secret=client_secret, |
| 676 |
) |
| 677 |
elif token_val: |
| 678 |
# The galaxy v1 / github / django / 'Token' |
| 679 |
server_options['token'] = GalaxyToken(token=token_val) |
| 680 |
|
| 681 |
server_options.update(galaxy_options) |
| 682 |
config_servers.append(GalaxyAPI( |
| 683 |
self.galaxy, server_key, |
| 684 |
priority=server_priority, |
| 685 |
**server_options |
| 686 |
)) |
| 687 |
|
| 688 |
cmd_server = context.CLIARGS['api_server'] |
| 689 |
|
| 690 |
cmd_token = GalaxyToken(token=context.CLIARGS['api_key']) |
| 691 |
|
| 692 |
validate_certs = context.CLIARGS['resolved_validate_certs'] |
| 693 |
default_server_timeout = context.CLIARGS['timeout'] if context.CLIARGS['timeout'] is not None else C.GALAXY_SERVER_TIMEOUT |
| 694 |
if cmd_server: |
| 695 |
# Cmd args take precedence over the config entry but fist check if the arg was a name and use that config |
| 696 |
# entry, otherwise create a new API entry for the server specified. |
| 697 |
config_server = next((s for s in config_servers if s.name == cmd_server), None) |
| 698 |
if config_server: |
| 699 |
self.api_servers.append(config_server) |
| 700 |
else: |
| 701 |
self.api_servers.append(GalaxyAPI( |
| 702 |
self.galaxy, 'cmd_arg', cmd_server, token=cmd_token, |
| 703 |
priority=len(config_servers) + 1, |
| 704 |
validate_certs=validate_certs, |
| 705 |
timeout=default_server_timeout, |
| 706 |
**galaxy_options |
| 707 |
)) |
| 708 |
else: |
| 709 |
self.api_servers = config_servers |
| 710 |
|
| 711 |
# Default to C.GALAXY_SERVER if no servers were defined |
| 712 |
if len(self.api_servers) == 0: |
| 713 |
self.api_servers.append(GalaxyAPI( |
| 714 |
self.galaxy, 'default', C.GALAXY_SERVER, token=cmd_token, |
| 715 |
priority=0, |
| 716 |
validate_certs=validate_certs, |
| 717 |
timeout=default_server_timeout, |
| 718 |
**galaxy_options |
| 719 |
)) |
| 720 |
|
| 721 |
# checks api versions once a GalaxyRole makes an api call |
| 722 |
# self.api can be used to evaluate the best server immediately |
| 723 |
self.lazy_role_api = RoleDistributionServer(None, self.api_servers) |
| 724 |
|
| 725 |
return context.CLIARGS['func']() |
| 726 |
|
| 727 |
@property |
| 728 |
def api(self): |
| 729 |
return self.lazy_role_api.api |
| 730 |
|
| 731 |
def _get_default_collection_path(self): |
| 732 |
return C.COLLECTIONS_PATHS[0] |
| 733 |
|
| 734 |
def _parse_requirements_file(self, requirements_file, allow_old_format=True, artifacts_manager=None, validate_signature_options=True): |
| 735 |
""" |
| 736 |
Parses an Ansible requirement.yml file and returns all the roles and/or collections defined in it. There are 2 |
| 737 |
requirements file format: |
| 738 |
|
| 739 |
# v1 (roles only) |
| 740 |
- src: The source of the role, required if include is not set. Can be Galaxy role name, URL to a SCM repo or tarball. |
| 741 |
name: Downloads the role to the specified name, defaults to Galaxy name from Galaxy or name of repo if src is a URL. |
| 742 |
scm: If src is a URL, specify the SCM. Only git or hd are supported and defaults ot git. |
| 743 |
version: The version of the role to download. Can also be tag, commit, or branch name and defaults to master. |
| 744 |
include: Path to additional requirements.yml files. |
| 745 |
|
| 746 |
# v2 (roles and collections) |
| 747 |
--- |
| 748 |
roles: |
| 749 |
# Same as v1 format just under the roles key |
| 750 |
|
| 751 |
collections: |
| 752 |
- namespace.collection |
| 753 |
- name: namespace.collection |
| 754 |
version: version identifier, multiple identifiers are separated by ',' |
| 755 |
source: the URL or a predefined source name that relates to C.GALAXY_SERVER_LIST |
| 756 |
type: git|file|url|galaxy |
| 757 |
|
| 758 |
:param requirements_file: The path to the requirements file. |
| 759 |
:param allow_old_format: Will fail if a v1 requirements file is found and this is set to False. |
| 760 |
:param artifacts_manager: Artifacts manager. |
| 761 |
:return: a dict containing roles and collections to found in the requirements file. |
| 762 |
""" |
| 763 |
requirements = { |
| 764 |
'roles': [], |
| 765 |
'collections': [], |
| 766 |
} |
| 767 |
|
| 768 |
b_requirements_file = to_bytes(requirements_file, errors='surrogate_or_strict') |
| 769 |
if not os.path.exists(b_requirements_file): |
| 770 |
raise AnsibleError("The requirements file '%s' does not exist." % to_native(requirements_file)) |
| 771 |
|
| 772 |
display.vvv("Reading requirement file at '%s'" % requirements_file) |
| 773 |
with open(b_requirements_file, 'rb') as req_obj: |
| 774 |
try: |
| 775 |
file_requirements = yaml_load(req_obj) |
| 776 |
except YAMLError as err: |
| 777 |
raise AnsibleError( |
| 778 |
"Failed to parse the requirements yml at '%s' with the following error:\n%s" |
| 779 |
% (to_native(requirements_file), to_native(err))) |
| 780 |
|
| 781 |
if file_requirements is None: |
| 782 |
raise AnsibleError("No requirements found in file '%s'" % to_native(requirements_file)) |
| 783 |
|
| 784 |
def parse_role_req(requirement): |
| 785 |
if "include" not in requirement: |
| 786 |
role = RoleRequirement.role_yaml_parse(requirement) |
| 787 |
display.vvv("found role %s in yaml file" % to_text(role)) |
| 788 |
if "name" not in role and "src" not in role: |
| 789 |
raise AnsibleError("Must specify name or src for role") |
| 790 |
return [GalaxyRole(self.galaxy, self.lazy_role_api, **role)] |
| 791 |
else: |
| 792 |
b_include_path = to_bytes(requirement["include"], errors="surrogate_or_strict") |
| 793 |
if not os.path.isfile(b_include_path): |
| 794 |
raise AnsibleError("Failed to find include requirements file '%s' in '%s'" |
| 795 |
% (to_native(b_include_path), to_native(requirements_file))) |
| 796 |
|
| 797 |
with open(b_include_path, 'rb') as f_include: |
| 798 |
try: |
| 799 |
return [GalaxyRole(self.galaxy, self.lazy_role_api, **r) for r in |
| 800 |
(RoleRequirement.role_yaml_parse(i) for i in yaml_load(f_include))] |
| 801 |
except Exception as e: |
| 802 |
raise AnsibleError("Unable to load data from include requirements file: %s %s" |
| 803 |
% (to_native(requirements_file), to_native(e))) |
| 804 |
|
| 805 |
if isinstance(file_requirements, list): |
| 806 |
# Older format that contains only roles |
| 807 |
if not allow_old_format: |
| 808 |
raise AnsibleError("Expecting requirements file to be a dict with the key 'collections' that contains " |
| 809 |
"a list of collections to install") |
| 810 |
|
| 811 |
for role_req in file_requirements: |
| 812 |
requirements['roles'] += parse_role_req(role_req) |
| 813 |
|
| 814 |
elif isinstance(file_requirements, dict): |
| 815 |
# Newer format with a collections and/or roles key |
| 816 |
extra_keys = set(file_requirements.keys()).difference(set(['roles', 'collections'])) |
| 817 |
if extra_keys: |
| 818 |
raise AnsibleError("Expecting only 'roles' and/or 'collections' as base keys in the requirements " |
| 819 |
"file. Found: %s" % (to_native(", ".join(extra_keys)))) |
| 820 |
|
| 821 |
for role_req in file_requirements.get('roles') or []: |
| 822 |
requirements['roles'] += parse_role_req(role_req) |
| 823 |
|
| 824 |
requirements['collections'] = [ |
| 825 |
Requirement.from_requirement_dict( |
| 826 |
self._init_coll_req_dict(collection_req), |
| 827 |
artifacts_manager, |
| 828 |
validate_signature_options, |
| 829 |
) |
| 830 |
for collection_req in file_requirements.get('collections') or [] |
| 831 |
] |
| 832 |
|
| 833 |
else: |
| 834 |
raise AnsibleError(f"Expecting requirements yaml to be a list or dictionary but got {type(file_requirements).__name__}") |
| 835 |
|
| 836 |
return requirements |
| 837 |
|
| 838 |
def _init_coll_req_dict(self, coll_req): |
| 839 |
if not isinstance(coll_req, dict): |
| 840 |
# Assume it's a string: |
| 841 |
return {'name': coll_req} |
| 842 |
|
| 843 |
if ( |
| 844 |
'name' not in coll_req or |
| 845 |
not coll_req.get('source') or |
| 846 |
coll_req.get('type', 'galaxy') != 'galaxy' |
| 847 |
): |
| 848 |
return coll_req |
| 849 |
|
| 850 |
# Try and match up the requirement source with our list of Galaxy API |
| 851 |
# servers defined in the config, otherwise create a server with that |
| 852 |
# URL without any auth. |
| 853 |
coll_req['source'] = next( |
| 854 |
iter( |
| 855 |
srvr for srvr in self.api_servers |
| 856 |
if coll_req['source'] in {srvr.name, srvr.api_server} |
| 857 |
), |
| 858 |
GalaxyAPI( |
| 859 |
self.galaxy, |
| 860 |
'explicit_requirement_{name!s}'.format( |
| 861 |
name=coll_req['name'], |
| 862 |
), |
| 863 |
coll_req['source'], |
| 864 |
validate_certs=context.CLIARGS['resolved_validate_certs'], |
| 865 |
), |
| 866 |
) |
| 867 |
|
| 868 |
return coll_req |
| 869 |
|
| 870 |
@staticmethod |
| 871 |
def exit_without_ignore(rc=1): |
| 872 |
""" |
| 873 |
Exits with the specified return code unless the |
| 874 |
option --ignore-errors was specified |
| 875 |
""" |
| 876 |
if not context.CLIARGS['ignore_errors']: |
| 877 |
raise AnsibleError('- you can use --ignore-errors to skip failed roles and finish processing the list.') |
| 878 |
|
| 879 |
@staticmethod |
| 880 |
def _display_role_info(role_info): |
| 881 |
|
| 882 |
text = [u"", u"Role: %s" % to_text(role_info['name'])] |
| 883 |
|
| 884 |
# Get the top-level 'description' first, falling back to galaxy_info['galaxy_info']['description']. |
| 885 |
galaxy_info = role_info.get('galaxy_info', {}) |
| 886 |
description = role_info.get('description', galaxy_info.get('description', '')) |
| 887 |
text.append(u"\tdescription: %s" % description) |
| 888 |
|
| 889 |
for k in sorted(role_info.keys()): |
| 890 |
|
| 891 |
if k in GalaxyCLI.SKIP_INFO_KEYS: |
| 892 |
continue |
| 893 |
|
| 894 |
if isinstance(role_info[k], dict): |
| 895 |
text.append(u"\t%s:" % (k)) |
| 896 |
for key in sorted(role_info[k].keys()): |
| 897 |
if key in GalaxyCLI.SKIP_INFO_KEYS: |
| 898 |
continue |
| 899 |
text.append(u"\t\t%s: %s" % (key, role_info[k][key])) |
| 900 |
else: |
| 901 |
text.append(u"\t%s: %s" % (k, role_info[k])) |
| 902 |
|
| 903 |
# make sure we have a trailing newline returned |
| 904 |
text.append(u"") |
| 905 |
return u'\n'.join(text) |
| 906 |
|
| 907 |
@staticmethod |
| 908 |
def _resolve_path(path): |
| 909 |
return os.path.abspath(os.path.expanduser(os.path.expandvars(path))) |
| 910 |
|
| 911 |
@staticmethod |
| 912 |
def _get_skeleton_galaxy_yml(template_path, inject_data): |
| 913 |
with open(to_bytes(template_path, errors='surrogate_or_strict'), 'r') as template_obj: |
| 914 |
meta_template = TrustedAsTemplate().tag(to_text(template_obj.read(), errors='surrogate_or_strict')) |
| 915 |
|
| 916 |
galaxy_meta = get_collections_galaxy_meta_info() |
| 917 |
|
| 918 |
required_config = [] |
| 919 |
optional_config = [] |
| 920 |
for meta_entry in galaxy_meta: |
| 921 |
config_list = required_config if meta_entry.get('required', False) else optional_config |
| 922 |
|
| 923 |
value = inject_data.get(meta_entry['key'], None) |
| 924 |
if not value: |
| 925 |
meta_type = meta_entry.get('type', 'str') |
| 926 |
|
| 927 |
if meta_type == 'str': |
| 928 |
value = '' |
| 929 |
elif meta_type == 'list': |
| 930 |
value = [] |
| 931 |
elif meta_type == 'dict': |
| 932 |
value = {} |
| 933 |
|
| 934 |
meta_entry['value'] = value |
| 935 |
config_list.append(meta_entry) |
| 936 |
|
| 937 |
link_pattern = re.compile(r"L\(([^)]+),\s+([^)]+)\)") |
| 938 |
const_pattern = re.compile(r"C\(([^)]+)\)") |
| 939 |
|
| 940 |
def comment_ify(v): |
| 941 |
if isinstance(v, list): |
| 942 |
v = ". ".join([l.rstrip('.') for l in v]) |
| 943 |
|
| 944 |
v = link_pattern.sub(r"\1 <\2>", v) |
| 945 |
v = const_pattern.sub(r"'\1'", v) |
| 946 |
|
| 947 |
return textwrap.fill(v, width=117, initial_indent="# ", subsequent_indent="# ", break_on_hyphens=False) |
| 948 |
|
| 949 |
loader = DataLoader() |
| 950 |
templar = TemplateEngine(loader, variables={'required_config': required_config, 'optional_config': optional_config}) |
| 951 |
templar.environment.filters['comment_ify'] = comment_ify |
| 952 |
|
| 953 |
meta_value = templar.template(meta_template) |
| 954 |
|
| 955 |
return meta_value |
| 956 |
|
| 957 |
def _require_one_of_collections_requirements( |
| 958 |
self, collections, requirements_file, |
| 959 |
signatures=None, |
| 960 |
artifacts_manager=None, |
| 961 |
): |
| 962 |
if collections and requirements_file: |
| 963 |
raise AnsibleError("The positional collection_name arg and --requirements-file are mutually exclusive.") |
| 964 |
elif not collections and not requirements_file: |
| 965 |
raise AnsibleError("You must specify a collection name or a requirements file.") |
| 966 |
elif requirements_file: |
| 967 |
if signatures is not None: |
| 968 |
raise AnsibleError( |
| 969 |
"The --signatures option and --requirements-file are mutually exclusive. " |
| 970 |
"Use the --signatures with positional collection_name args or provide a " |
| 971 |
"'signatures' key for requirements in the --requirements-file." |
| 972 |
) |
| 973 |
requirements_file = GalaxyCLI._resolve_path(requirements_file) |
| 974 |
requirements = self._parse_requirements_file( |
| 975 |
requirements_file, |
| 976 |
allow_old_format=False, |
| 977 |
artifacts_manager=artifacts_manager, |
| 978 |
) |
| 979 |
else: |
| 980 |
requirements = { |
| 981 |
'collections': [ |
| 982 |
Requirement.from_string(coll_input, artifacts_manager, signatures) |
| 983 |
for coll_input in collections |
| 984 |
], |
| 985 |
'roles': [], |
| 986 |
} |
| 987 |
return requirements |
| 988 |
|
| 989 |
############################ |
| 990 |
# execute actions |
| 991 |
############################ |
| 992 |
|
| 993 |
def execute_role(self): |
| 994 |
""" |
| 995 |
Perform the action on an Ansible Galaxy role. Must be combined with a further action like delete/install/init |
| 996 |
as listed below. |
| 997 |
""" |
| 998 |
# To satisfy doc build |
| 999 |
pass |
| 1000 |
|
| 1001 |
def execute_collection(self): |
| 1002 |
""" |
| 1003 |
Perform the action on an Ansible Galaxy collection. Must be combined with a further action like init/install as |
| 1004 |
listed below. |
| 1005 |
""" |
| 1006 |
# To satisfy doc build |
| 1007 |
pass |
| 1008 |
|
| 1009 |
def execute_build(self): |
| 1010 |
""" |
| 1011 |
Build an Ansible Galaxy collection artifact that can be stored in a central repository like Ansible Galaxy. |
| 1012 |
By default, this command builds from the current working directory. You can optionally pass in the |
| 1013 |
collection input path (where the ``galaxy.yml`` file is). |
| 1014 |
""" |
| 1015 |
force = context.CLIARGS['force'] |
| 1016 |
output_path = GalaxyCLI._resolve_path(context.CLIARGS['output_path']) |
| 1017 |
b_output_path = to_bytes(output_path, errors='surrogate_or_strict') |
| 1018 |
|
| 1019 |
if not os.path.exists(b_output_path): |
| 1020 |
os.makedirs(b_output_path) |
| 1021 |
elif os.path.isfile(b_output_path): |
| 1022 |
raise AnsibleError("- the output collection directory %s is a file - aborting" % to_native(output_path)) |
| 1023 |
|
| 1024 |
for collection_path in context.CLIARGS['args']: |
| 1025 |
collection_path = GalaxyCLI._resolve_path(collection_path) |
| 1026 |
build_collection( |
| 1027 |
to_text(collection_path, errors='surrogate_or_strict'), |
| 1028 |
to_text(output_path, errors='surrogate_or_strict'), |
| 1029 |
force, |
| 1030 |
) |
| 1031 |
|
| 1032 |
@with_collection_artifacts_manager |
| 1033 |
def execute_download(self, artifacts_manager=None): |
| 1034 |
"""Download collections and their dependencies as a tarball for an offline install.""" |
| 1035 |
collections = context.CLIARGS['args'] |
| 1036 |
no_deps = context.CLIARGS['no_deps'] |
| 1037 |
download_path = context.CLIARGS['download_path'] |
| 1038 |
|
| 1039 |
requirements_file = context.CLIARGS['requirements'] |
| 1040 |
if requirements_file: |
| 1041 |
requirements_file = GalaxyCLI._resolve_path(requirements_file) |
| 1042 |
|
| 1043 |
requirements = self._require_one_of_collections_requirements( |
| 1044 |
collections, requirements_file, |
| 1045 |
artifacts_manager=artifacts_manager, |
| 1046 |
)['collections'] |
| 1047 |
|
| 1048 |
download_path = GalaxyCLI._resolve_path(download_path) |
| 1049 |
b_download_path = to_bytes(download_path, errors='surrogate_or_strict') |
| 1050 |
if not os.path.exists(b_download_path): |
| 1051 |
os.makedirs(b_download_path) |
| 1052 |
|
| 1053 |
download_collections( |
| 1054 |
requirements, download_path, self.api_servers, no_deps, |
| 1055 |
context.CLIARGS['allow_pre_release'], |
| 1056 |
artifacts_manager=artifacts_manager, |
| 1057 |
) |
| 1058 |
|
| 1059 |
return 0 |
| 1060 |
|
| 1061 |
def execute_init(self): |
| 1062 |
""" |
| 1063 |
Creates the skeleton framework of a role or collection that complies with the Galaxy metadata format. |
| 1064 |
Requires a role or collection name. The collection name must be in the format ``<namespace>.<collection>``. |
| 1065 |
""" |
| 1066 |
|
| 1067 |
galaxy_type = context.CLIARGS['type'] |
| 1068 |
init_path = context.CLIARGS['init_path'] |
| 1069 |
force = context.CLIARGS['force'] |
| 1070 |
obj_skeleton = context.CLIARGS['{0}_skeleton'.format(galaxy_type)] |
| 1071 |
|
| 1072 |
obj_name = context.CLIARGS['{0}_name'.format(galaxy_type)] |
| 1073 |
|
| 1074 |
inject_data = dict( |
| 1075 |
description='your {0} description'.format(galaxy_type), |
| 1076 |
ansible_plugin_list_dir=get_versioned_doclink('plugins/plugins.html'), |
| 1077 |
) |
| 1078 |
if galaxy_type == 'role': |
| 1079 |
inject_data.update(dict( |
| 1080 |
author='your name', |
| 1081 |
company='your company (optional)', |
| 1082 |
license='license (GPL-2.0-or-later, MIT, etc)', |
| 1083 |
role_name=obj_name, |
| 1084 |
role_type=context.CLIARGS['role_type'], |
| 1085 |
issue_tracker_url='http://example.com/issue/tracker', |
| 1086 |
repository_url='http://example.com/repository', |
| 1087 |
documentation_url='http://docs.example.com', |
| 1088 |
homepage_url='http://example.com', |
| 1089 |
min_ansible_version=ansible_version[:3], # x.y |
| 1090 |
dependencies=[], |
| 1091 |
)) |
| 1092 |
|
| 1093 |
skeleton_ignore_expressions = C.GALAXY_ROLE_SKELETON_IGNORE |
| 1094 |
obj_path = os.path.join(init_path, obj_name) |
| 1095 |
elif galaxy_type == 'collection': |
| 1096 |
namespace, collection_name = obj_name.split('.', 1) |
| 1097 |
|
| 1098 |
inject_data.update(dict( |
| 1099 |
namespace=namespace, |
| 1100 |
collection_name=collection_name, |
| 1101 |
version='1.0.0', |
| 1102 |
readme='README.md', |
| 1103 |
authors=['your name <[email protected]>'], |
| 1104 |
license=['GPL-2.0-or-later'], |
| 1105 |
repository='http://example.com/repository', |
| 1106 |
documentation='http://docs.example.com', |
| 1107 |
homepage='http://example.com', |
| 1108 |
issues='http://example.com/issue/tracker', |
| 1109 |
build_ignore=[], |
| 1110 |
)) |
| 1111 |
|
| 1112 |
skeleton_ignore_expressions = C.GALAXY_COLLECTION_SKELETON_IGNORE |
| 1113 |
obj_path = os.path.join(init_path, namespace, collection_name) |
| 1114 |
|
| 1115 |
b_obj_path = to_bytes(obj_path, errors='surrogate_or_strict') |
| 1116 |
|
| 1117 |
if os.path.exists(b_obj_path): |
| 1118 |
if os.path.isfile(obj_path): |
| 1119 |
raise AnsibleError("- the path %s already exists, but is a file - aborting" % to_native(obj_path)) |
| 1120 |
elif not force: |
| 1121 |
raise AnsibleError("- the directory %s already exists. " |
| 1122 |
"You can use --force to re-initialize this directory,\n" |
| 1123 |
"however it will reset any main.yml files that may have\n" |
| 1124 |
"been modified there already." % to_native(obj_path)) |
| 1125 |
|
| 1126 |
# delete the contents rather than the collection root in case init was run from the root (--init-path ../../) |
| 1127 |
for root, dirs, files in os.walk(b_obj_path, topdown=True): |
| 1128 |
for old_dir in dirs: |
| 1129 |
path = os.path.join(root, old_dir) |
| 1130 |
shutil.rmtree(path) |
| 1131 |
for old_file in files: |
| 1132 |
path = os.path.join(root, old_file) |
| 1133 |
os.unlink(path) |
| 1134 |
|
| 1135 |
if obj_skeleton is not None: |
| 1136 |
own_skeleton = False |
| 1137 |
else: |
| 1138 |
own_skeleton = True |
| 1139 |
obj_skeleton = self.galaxy.default_role_skeleton_path |
| 1140 |
skeleton_ignore_expressions = ['^.*/.git_keep$'] |
| 1141 |
|
| 1142 |
obj_skeleton = os.path.expanduser(obj_skeleton) |
| 1143 |
failed_re_expressions = "" |
| 1144 |
skeleton_ignore_re = [] |
| 1145 |
for x in skeleton_ignore_expressions: |
| 1146 |
try: |
| 1147 |
skeleton_ignore_re.append(re.compile(x)) |
| 1148 |
except re.error as e: |
| 1149 |
failed_re_expressions += f"- {x}: {str(e)}\n" |
| 1150 |
continue |
| 1151 |
if failed_re_expressions: |
| 1152 |
raise AnsibleError( |
| 1153 |
f"Failed to compile regular expressions for skeleton ignore: \n{failed_re_expressions}" |
| 1154 |
) |
| 1155 |
|
| 1156 |
if not os.path.exists(obj_skeleton): |
| 1157 |
raise AnsibleError("- the skeleton path '{0}' does not exist, cannot init {1}".format( |
| 1158 |
to_native(obj_skeleton), galaxy_type) |
| 1159 |
) |
| 1160 |
|
| 1161 |
loader = DataLoader() |
| 1162 |
inject_data.update(load_extra_vars(loader)) |
| 1163 |
templar = TemplateEngine(loader, variables=inject_data) |
| 1164 |
|
| 1165 |
# create role directory |
| 1166 |
if not os.path.exists(b_obj_path): |
| 1167 |
os.makedirs(b_obj_path) |
| 1168 |
|
| 1169 |
for root, dirs, files in os.walk(obj_skeleton, topdown=True): |
| 1170 |
rel_root = os.path.relpath(root, obj_skeleton) |
| 1171 |
rel_dirs = rel_root.split(os.sep) |
| 1172 |
rel_root_dir = rel_dirs[0] |
| 1173 |
if galaxy_type == 'collection': |
| 1174 |
# A collection can contain templates in playbooks/*/templates and roles/*/templates |
| 1175 |
in_templates_dir = rel_root_dir in ['playbooks', 'roles'] and 'templates' in rel_dirs |
| 1176 |
else: |
| 1177 |
in_templates_dir = rel_root_dir == 'templates' |
| 1178 |
|
| 1179 |
# Filter out ignored directory names |
| 1180 |
# Use [:] to mutate the list os.walk uses |
| 1181 |
dirs[:] = [d for d in dirs if not any(r.match(d) for r in skeleton_ignore_re)] |
| 1182 |
|
| 1183 |
for f in files: |
| 1184 |
filename, ext = os.path.splitext(f) |
| 1185 |
|
| 1186 |
if any(r.match(os.path.join(rel_root, f)) for r in skeleton_ignore_re): |
| 1187 |
continue |
| 1188 |
|
| 1189 |
if galaxy_type == 'collection' and own_skeleton and rel_root == '.' and f == 'galaxy.yml.j2': |
| 1190 |
# Special use case for galaxy.yml.j2 in our own default collection skeleton. We build the options |
| 1191 |
# dynamically which requires special options to be set. |
| 1192 |
|
| 1193 |
# The templated data's keys must match the key name but the inject data contains collection_name |
| 1194 |
# instead of name. We just make a copy and change the key back to name for this file. |
| 1195 |
template_data = inject_data.copy() |
| 1196 |
template_data['name'] = template_data.pop('collection_name') |
| 1197 |
|
| 1198 |
meta_value = GalaxyCLI._get_skeleton_galaxy_yml(os.path.join(root, rel_root, f), template_data) |
| 1199 |
b_dest_file = to_bytes(os.path.join(obj_path, rel_root, filename), errors='surrogate_or_strict') |
| 1200 |
with open(b_dest_file, 'wb') as galaxy_obj: |
| 1201 |
galaxy_obj.write(to_bytes(meta_value, errors='surrogate_or_strict')) |
| 1202 |
elif ext == ".j2" and not in_templates_dir: |
| 1203 |
src_template = os.path.join(root, f) |
| 1204 |
dest_file = os.path.join(obj_path, rel_root, filename) |
| 1205 |
template_data = trust_as_template(loader.get_text_file_contents(src_template)) |
| 1206 |
try: |
| 1207 |
b_rendered = to_bytes(templar.template(template_data), errors='surrogate_or_strict') |
| 1208 |
except AnsibleError as e: |
| 1209 |
shutil.rmtree(b_obj_path) |
| 1210 |
raise AnsibleError(f"Failed to create {galaxy_type.title()} {obj_name}. Templating {src_template} failed with the error: {e}") from e |
| 1211 |
with open(dest_file, 'wb') as df: |
| 1212 |
df.write(b_rendered) |
| 1213 |
else: |
| 1214 |
f_rel_path = os.path.relpath(os.path.join(root, f), obj_skeleton) |
| 1215 |
shutil.copyfile(os.path.join(root, f), os.path.join(obj_path, f_rel_path), follow_symlinks=False) |
| 1216 |
|
| 1217 |
for d in dirs: |
| 1218 |
b_dir_path = to_bytes(os.path.join(obj_path, rel_root, d), errors='surrogate_or_strict') |
| 1219 |
if os.path.exists(b_dir_path): |
| 1220 |
continue |
| 1221 |
b_src_dir = to_bytes(os.path.join(root, d), errors='surrogate_or_strict') |
| 1222 |
if os.path.islink(b_src_dir): |
| 1223 |
shutil.copyfile(b_src_dir, b_dir_path, follow_symlinks=False) |
| 1224 |
else: |
| 1225 |
os.makedirs(b_dir_path) |
| 1226 |
|
| 1227 |
display.display("- %s %s was created successfully" % (galaxy_type.title(), obj_name)) |
| 1228 |
|
| 1229 |
def execute_info(self): |
| 1230 |
""" |
| 1231 |
prints out detailed information about an installed role as well as info available from the galaxy API. |
| 1232 |
""" |
| 1233 |
|
| 1234 |
roles_path = context.CLIARGS['roles_path'] |
| 1235 |
|
| 1236 |
data = '' |
| 1237 |
for role in context.CLIARGS['args']: |
| 1238 |
|
| 1239 |
role_info = {'path': roles_path} |
| 1240 |
gr = GalaxyRole(self.galaxy, self.lazy_role_api, role) |
| 1241 |
|
| 1242 |
install_info = gr.install_info |
| 1243 |
if install_info: |
| 1244 |
if 'version' in install_info: |
| 1245 |
install_info['installed_version'] = install_info['version'] |
| 1246 |
del install_info['version'] |
| 1247 |
role_info.update(install_info) |
| 1248 |
|
| 1249 |
if not context.CLIARGS['offline']: |
| 1250 |
remote_data = None |
| 1251 |
try: |
| 1252 |
remote_data = self.api.lookup_role_by_name(role, False) |
| 1253 |
except GalaxyError as e: |
| 1254 |
if e.http_code == 400 and 'Bad Request' in e.message: |
| 1255 |
# Role does not exist in Ansible Galaxy |
| 1256 |
data = u"- the role %s was not found" % role |
| 1257 |
break |
| 1258 |
|
| 1259 |
raise AnsibleError("Unable to find info about '%s': %s" % (role, e)) |
| 1260 |
|
| 1261 |
if remote_data: |
| 1262 |
role_info.update(remote_data) |
| 1263 |
else: |
| 1264 |
data = u"- the role %s was not found" % role |
| 1265 |
break |
| 1266 |
|
| 1267 |
elif context.CLIARGS['offline'] and not gr._exists: |
| 1268 |
data = u"- the role %s was not found" % role |
| 1269 |
break |
| 1270 |
|
| 1271 |
if gr.metadata: |
| 1272 |
role_info.update(gr.metadata) |
| 1273 |
|
| 1274 |
req = RoleRequirement() |
| 1275 |
role_spec = req.role_yaml_parse({'role': role}) |
| 1276 |
if role_spec: |
| 1277 |
role_info.update(role_spec) |
| 1278 |
|
| 1279 |
data += self._display_role_info(role_info) |
| 1280 |
|
| 1281 |
self.pager(data) |
| 1282 |
|
| 1283 |
@with_collection_artifacts_manager |
| 1284 |
def execute_verify(self, artifacts_manager=None): |
| 1285 |
"""Compare checksums with the collection(s) found on the server and the installed copy. This does not verify dependencies.""" |
| 1286 |
|
| 1287 |
collections = context.CLIARGS['args'] |
| 1288 |
search_paths = self.collection_paths |
| 1289 |
ignore_errors = context.CLIARGS['ignore_errors'] |
| 1290 |
local_verify_only = context.CLIARGS['offline'] |
| 1291 |
requirements_file = context.CLIARGS['requirements'] |
| 1292 |
signatures = context.CLIARGS['signatures'] |
| 1293 |
if signatures is not None: |
| 1294 |
signatures = list(signatures) |
| 1295 |
|
| 1296 |
requirements = self._require_one_of_collections_requirements( |
| 1297 |
collections, requirements_file, |
| 1298 |
signatures=signatures, |
| 1299 |
artifacts_manager=artifacts_manager, |
| 1300 |
)['collections'] |
| 1301 |
|
| 1302 |
resolved_paths = [validate_collection_path(GalaxyCLI._resolve_path(path)) for path in search_paths] |
| 1303 |
|
| 1304 |
results = verify_collections( |
| 1305 |
requirements, resolved_paths, |
| 1306 |
self.api_servers, ignore_errors, |
| 1307 |
local_verify_only=local_verify_only, |
| 1308 |
artifacts_manager=artifacts_manager, |
| 1309 |
) |
| 1310 |
|
| 1311 |
if any(result for result in results if not result.success): |
| 1312 |
return 1 |
| 1313 |
|
| 1314 |
return 0 |
| 1315 |
|
| 1316 |
@with_collection_artifacts_manager |
| 1317 |
def execute_install(self, artifacts_manager=None): |
| 1318 |
""" |
| 1319 |
Install one or more roles(``ansible-galaxy role install``), or one or more collections(``ansible-galaxy collection install``). |
| 1320 |
You can pass in a list (roles or collections) or use the file |
| 1321 |
option listed below (these are mutually exclusive). If you pass in a list, it |
| 1322 |
can be a name (which will be downloaded via the galaxy API and github), or it can be a local tar archive file. |
| 1323 |
""" |
| 1324 |
install_items = context.CLIARGS['args'] |
| 1325 |
requirements_file = context.CLIARGS['requirements'] |
| 1326 |
collection_path = None |
| 1327 |
signatures = context.CLIARGS.get('signatures') |
| 1328 |
if signatures is not None: |
| 1329 |
signatures = list(signatures) |
| 1330 |
|
| 1331 |
if requirements_file: |
| 1332 |
requirements_file = GalaxyCLI._resolve_path(requirements_file) |
| 1333 |
|
| 1334 |
two_type_warning = "The requirements file '%s' contains {0}s which will be ignored. To install these {0}s " \ |
| 1335 |
"run 'ansible-galaxy {0} install -r' or to install both at the same time run " \ |
| 1336 |
"'ansible-galaxy install -r' without a custom install path." % to_text(requirements_file) |
| 1337 |
|
| 1338 |
# TODO: Would be nice to share the same behaviour with args and -r in collections and roles. |
| 1339 |
collection_requirements = [] |
| 1340 |
role_requirements = [] |
| 1341 |
if context.CLIARGS['type'] == 'collection': |
| 1342 |
collection_path = GalaxyCLI._resolve_path(context.CLIARGS['collections_path']) |
| 1343 |
requirements = self._require_one_of_collections_requirements( |
| 1344 |
install_items, requirements_file, |
| 1345 |
signatures=signatures, |
| 1346 |
artifacts_manager=artifacts_manager, |
| 1347 |
) |
| 1348 |
|
| 1349 |
collection_requirements = requirements['collections'] |
| 1350 |
if requirements['roles']: |
| 1351 |
display.vvv(two_type_warning.format('role')) |
| 1352 |
else: |
| 1353 |
if not install_items and requirements_file is None: |
| 1354 |
raise AnsibleOptionsError("- you must specify a user/role name or a roles file") |
| 1355 |
|
| 1356 |
if requirements_file: |
| 1357 |
if not (requirements_file.endswith('.yaml') or requirements_file.endswith('.yml')): |
| 1358 |
raise AnsibleError("Invalid role requirements file, it must end with a .yml or .yaml extension") |
| 1359 |
|
| 1360 |
galaxy_args = self._raw_args |
| 1361 |
will_install_collections = self._implicit_role and '-p' not in galaxy_args and '--roles-path' not in galaxy_args |
| 1362 |
|
| 1363 |
requirements = self._parse_requirements_file( |
| 1364 |
requirements_file, |
| 1365 |
artifacts_manager=artifacts_manager, |
| 1366 |
validate_signature_options=will_install_collections, |
| 1367 |
) |
| 1368 |
role_requirements = requirements['roles'] |
| 1369 |
|
| 1370 |
# We can only install collections and roles at the same time if the type wasn't specified and the -p |
| 1371 |
# argument was not used. If collections are present in the requirements then at least display a msg. |
| 1372 |
if requirements['collections'] and (not self._implicit_role or '-p' in galaxy_args or |
| 1373 |
'--roles-path' in galaxy_args): |
| 1374 |
|
| 1375 |
# We only want to display a warning if 'ansible-galaxy install -r ... -p ...'. Other cases the user |
| 1376 |
# was explicit about the type and shouldn't care that collections were skipped. |
| 1377 |
display_func = display.warning if self._implicit_role else display.vvv |
| 1378 |
display_func(two_type_warning.format('collection')) |
| 1379 |
else: |
| 1380 |
collection_path = self._get_default_collection_path() |
| 1381 |
collection_requirements = requirements['collections'] |
| 1382 |
else: |
| 1383 |
# roles were specified directly, so we'll just go out grab them |
| 1384 |
# (and their dependencies, unless the user doesn't want us to). |
| 1385 |
for rname in context.CLIARGS['args']: |
| 1386 |
role = RoleRequirement.role_yaml_parse(rname.strip()) |
| 1387 |
role_requirements.append(GalaxyRole(self.galaxy, self.lazy_role_api, **role)) |
| 1388 |
|
| 1389 |
if not role_requirements and not collection_requirements: |
| 1390 |
display.display("Skipping install, no requirements found") |
| 1391 |
return |
| 1392 |
|
| 1393 |
if role_requirements: |
| 1394 |
display.display("Starting galaxy role install process") |
| 1395 |
self._execute_install_role(role_requirements) |
| 1396 |
|
| 1397 |
if collection_requirements: |
| 1398 |
display.display("Starting galaxy collection install process") |
| 1399 |
# Collections can technically be installed even when ansible-galaxy is in role mode so we need to pass in |
| 1400 |
# the install path as context.CLIARGS['collections_path'] won't be set (default is calculated above). |
| 1401 |
self._execute_install_collection( |
| 1402 |
collection_requirements, collection_path, |
| 1403 |
artifacts_manager=artifacts_manager, |
| 1404 |
) |
| 1405 |
|
| 1406 |
def _execute_install_collection( |
| 1407 |
self, requirements, path, artifacts_manager, |
| 1408 |
): |
| 1409 |
force = context.CLIARGS['force'] |
| 1410 |
ignore_errors = context.CLIARGS['ignore_errors'] |
| 1411 |
no_deps = context.CLIARGS['no_deps'] |
| 1412 |
force_with_deps = context.CLIARGS['force_with_deps'] |
| 1413 |
try: |
| 1414 |
disable_gpg_verify = context.CLIARGS['disable_gpg_verify'] |
| 1415 |
except KeyError: |
| 1416 |
if self._implicit_role: |
| 1417 |
raise AnsibleError( |
| 1418 |
'Unable to properly parse command line arguments. Please use "ansible-galaxy collection install" ' |
| 1419 |
'instead of "ansible-galaxy install".' |
| 1420 |
) |
| 1421 |
raise |
| 1422 |
|
| 1423 |
# If `ansible-galaxy install` is used, collection-only options aren't available to the user and won't be in context.CLIARGS |
| 1424 |
allow_pre_release = context.CLIARGS.get('allow_pre_release', False) |
| 1425 |
upgrade = context.CLIARGS.get('upgrade', False) |
| 1426 |
|
| 1427 |
collections_path = C.COLLECTIONS_PATHS |
| 1428 |
|
| 1429 |
managed_paths = set(validate_collection_path(p) for p in C.COLLECTIONS_PATHS) |
| 1430 |
read_req_paths = set(validate_collection_path(p) for p in self.collection_paths) |
| 1431 |
|
| 1432 |
unexpected_path = C.GALAXY_COLLECTIONS_PATH_WARNING and not any(p.startswith(path) for p in managed_paths) |
| 1433 |
if unexpected_path and any(p.startswith(path) for p in read_req_paths): |
| 1434 |
display.warning( |
| 1435 |
f"The specified collections path '{path}' appears to be part of the pip Ansible package. " |
| 1436 |
"Managing these directly with ansible-galaxy could break the Ansible package. " |
| 1437 |
"Install collections to a configured collections path, which will take precedence over " |
| 1438 |
"collections found in the PYTHONPATH." |
| 1439 |
) |
| 1440 |
elif unexpected_path: |
| 1441 |
display.warning("The specified collections path '%s' is not part of the configured Ansible " |
| 1442 |
"collections paths '%s'. The installed collection will not be picked up in an Ansible " |
| 1443 |
"run, unless within a playbook-adjacent collections directory." % (to_text(path), to_text(":".join(collections_path)))) |
| 1444 |
|
| 1445 |
output_path = validate_collection_path(path) |
| 1446 |
b_output_path = to_bytes(output_path, errors='surrogate_or_strict') |
| 1447 |
if not os.path.exists(b_output_path): |
| 1448 |
os.makedirs(b_output_path) |
| 1449 |
|
| 1450 |
install_collections( |
| 1451 |
requirements, output_path, self.api_servers, ignore_errors, |
| 1452 |
no_deps, force, force_with_deps, upgrade, |
| 1453 |
allow_pre_release=allow_pre_release, |
| 1454 |
artifacts_manager=artifacts_manager, |
| 1455 |
disable_gpg_verify=disable_gpg_verify, |
| 1456 |
offline=context.CLIARGS.get('offline', False), |
| 1457 |
read_requirement_paths=read_req_paths, |
| 1458 |
) |
| 1459 |
|
| 1460 |
return 0 |
| 1461 |
|
| 1462 |
def _execute_install_role(self, requirements): |
| 1463 |
role_file = context.CLIARGS['requirements'] |
| 1464 |
no_deps = context.CLIARGS['no_deps'] |
| 1465 |
force_deps = context.CLIARGS['force_with_deps'] |
| 1466 |
force = context.CLIARGS['force'] or force_deps |
| 1467 |
|
| 1468 |
for role in requirements: |
| 1469 |
# only process roles in roles files when names matches if given |
| 1470 |
if role_file and context.CLIARGS['args'] and role.name not in context.CLIARGS['args']: |
| 1471 |
display.vvv('Skipping role %s' % role.name) |
| 1472 |
continue |
| 1473 |
|
| 1474 |
display.vvv('Processing role %s ' % role.name) |
| 1475 |
|
| 1476 |
# query the galaxy API for the role data |
| 1477 |
|
| 1478 |
if role.install_info is not None: |
| 1479 |
if role.install_info['version'] != role.version or force: |
| 1480 |
if force: |
| 1481 |
display.display('- changing role %s from %s to %s' % |
| 1482 |
(role.name, role.install_info['version'], role.version or "unspecified")) |
| 1483 |
role.remove() |
| 1484 |
else: |
| 1485 |
display.warning('- %s (%s) is already installed - use --force to change version to %s' % |
| 1486 |
(role.name, role.install_info['version'], role.version or "unspecified")) |
| 1487 |
continue |
| 1488 |
else: |
| 1489 |
if not force: |
| 1490 |
display.display('- %s is already installed, skipping.' % str(role)) |
| 1491 |
continue |
| 1492 |
|
| 1493 |
try: |
| 1494 |
installed = role.install() |
| 1495 |
except AnsibleError as e: |
| 1496 |
display.warning(u"- %s was NOT installed successfully: %s " % (role.name, to_text(e))) |
| 1497 |
self.exit_without_ignore() |
| 1498 |
continue |
| 1499 |
|
| 1500 |
# install dependencies, if we want them |
| 1501 |
if not no_deps and installed: |
| 1502 |
if not role.metadata: |
| 1503 |
# NOTE: the meta file is also required for installing the role, not just dependencies |
| 1504 |
display.warning("Meta file %s is empty. Skipping dependencies." % role.path) |
| 1505 |
else: |
| 1506 |
role_dependencies = role.metadata_dependencies + role.requirements |
| 1507 |
for dep in role_dependencies: |
| 1508 |
display.debug('Installing dep %s' % dep) |
| 1509 |
dep_req = RoleRequirement() |
| 1510 |
dep_info = dep_req.role_yaml_parse(dep) |
| 1511 |
dep_role = GalaxyRole(self.galaxy, self.lazy_role_api, **dep_info) |
| 1512 |
if '.' not in dep_role.name and '.' not in dep_role.src and dep_role.scm is None: |
| 1513 |
# we know we can skip this, as it's not going to |
| 1514 |
# be found on galaxy.ansible.com |
| 1515 |
continue |
| 1516 |
if dep_role.install_info is None: |
| 1517 |
if dep_role not in requirements: |
| 1518 |
display.display('- adding dependency: %s' % to_text(dep_role)) |
| 1519 |
requirements.append(dep_role) |
| 1520 |
else: |
| 1521 |
display.display('- dependency %s already pending installation.' % dep_role.name) |
| 1522 |
else: |
| 1523 |
if dep_role.install_info['version'] != dep_role.version: |
| 1524 |
if force_deps: |
| 1525 |
display.display('- changing dependent role %s from %s to %s' % |
| 1526 |
(dep_role.name, dep_role.install_info['version'], dep_role.version or "unspecified")) |
| 1527 |
dep_role.remove() |
| 1528 |
requirements.append(dep_role) |
| 1529 |
else: |
| 1530 |
display.warning('- dependency %s (%s) from role %s differs from already installed version (%s), skipping' % |
| 1531 |
(to_text(dep_role), dep_role.version, role.name, dep_role.install_info['version'])) |
| 1532 |
else: |
| 1533 |
if force_deps: |
| 1534 |
requirements.append(dep_role) |
| 1535 |
else: |
| 1536 |
display.display('- dependency %s is already installed, skipping.' % dep_role.name) |
| 1537 |
|
| 1538 |
if not installed: |
| 1539 |
display.warning("- %s was NOT installed successfully." % role.name) |
| 1540 |
self.exit_without_ignore() |
| 1541 |
|
| 1542 |
return 0 |
| 1543 |
|
| 1544 |
def execute_remove(self): |
| 1545 |
""" |
| 1546 |
removes the list of roles passed as arguments from the local system. |
| 1547 |
""" |
| 1548 |
|
| 1549 |
if not context.CLIARGS['args']: |
| 1550 |
raise AnsibleOptionsError('- you must specify at least one role to remove.') |
| 1551 |
|
| 1552 |
for role_name in context.CLIARGS['args']: |
| 1553 |
role = GalaxyRole(self.galaxy, self.api, role_name) |
| 1554 |
try: |
| 1555 |
if role.remove(): |
| 1556 |
display.display('- successfully removed %s' % role_name) |
| 1557 |
else: |
| 1558 |
display.display('- %s is not installed, skipping.' % role_name) |
| 1559 |
except Exception as e: |
| 1560 |
raise AnsibleError("Failed to remove role %s: %s" % (role_name, to_native(e))) |
| 1561 |
|
| 1562 |
return 0 |
| 1563 |
|
| 1564 |
def execute_list(self): |
| 1565 |
""" |
| 1566 |
List installed collections or roles |
| 1567 |
""" |
| 1568 |
|
| 1569 |
if context.CLIARGS['type'] == 'role': |
| 1570 |
self.execute_list_role() |
| 1571 |
elif context.CLIARGS['type'] == 'collection': |
| 1572 |
self.execute_list_collection() |
| 1573 |
|
| 1574 |
def execute_list_role(self): |
| 1575 |
""" |
| 1576 |
List all roles installed on the local system or a specific role |
| 1577 |
""" |
| 1578 |
|
| 1579 |
path_found = False |
| 1580 |
role_found = False |
| 1581 |
warnings = [] |
| 1582 |
roles_search_paths = context.CLIARGS['roles_path'] |
| 1583 |
role_name = context.CLIARGS['role'] |
| 1584 |
|
| 1585 |
for path in roles_search_paths: |
| 1586 |
role_path = GalaxyCLI._resolve_path(path) |
| 1587 |
if os.path.isdir(path): |
| 1588 |
path_found = True |
| 1589 |
else: |
| 1590 |
warnings.append("- the configured path {0} does not exist.".format(path)) |
| 1591 |
continue |
| 1592 |
|
| 1593 |
if role_name: |
| 1594 |
# show the requested role, if it exists |
| 1595 |
gr = GalaxyRole(self.galaxy, self.lazy_role_api, role_name, path=os.path.join(role_path, role_name)) |
| 1596 |
if os.path.isdir(gr.path): |
| 1597 |
role_found = True |
| 1598 |
display.display('# %s' % os.path.dirname(gr.path)) |
| 1599 |
_display_role(gr) |
| 1600 |
break |
| 1601 |
warnings.append("- the role %s was not found" % role_name) |
| 1602 |
else: |
| 1603 |
if not os.path.exists(role_path): |
| 1604 |
warnings.append("- the configured path %s does not exist." % role_path) |
| 1605 |
continue |
| 1606 |
|
| 1607 |
if not os.path.isdir(role_path): |
| 1608 |
warnings.append("- the configured path %s, exists, but it is not a directory." % role_path) |
| 1609 |
continue |
| 1610 |
|
| 1611 |
display.display('# %s' % role_path) |
| 1612 |
path_files = os.listdir(role_path) |
| 1613 |
for path_file in path_files: |
| 1614 |
gr = GalaxyRole(self.galaxy, self.lazy_role_api, path_file, path=path) |
| 1615 |
if gr.metadata: |
| 1616 |
_display_role(gr) |
| 1617 |
|
| 1618 |
# Do not warn if the role was found in any of the search paths |
| 1619 |
if role_found and role_name: |
| 1620 |
warnings = [] |
| 1621 |
|
| 1622 |
for w in warnings: |
| 1623 |
display.warning(w) |
| 1624 |
|
| 1625 |
if not path_found: |
| 1626 |
display.warning( |
| 1627 |
"None of the provided paths were usable. Please specify a valid path with --{0}s-path.".format(context.CLIARGS['type']) |
| 1628 |
) |
| 1629 |
|
| 1630 |
return 0 |
| 1631 |
|
| 1632 |
@with_collection_artifacts_manager |
| 1633 |
def execute_list_collection(self, artifacts_manager=None): |
| 1634 |
""" |
| 1635 |
List all collections installed on the local system |
| 1636 |
|
| 1637 |
:param artifacts_manager: Artifacts manager. |
| 1638 |
""" |
| 1639 |
if artifacts_manager is not None: |
| 1640 |
artifacts_manager.require_build_metadata = False |
| 1641 |
|
| 1642 |
output_format = context.CLIARGS['output_format'] |
| 1643 |
collection_name = context.CLIARGS['collection'] |
| 1644 |
default_collections_path = set(C.COLLECTIONS_PATHS) |
| 1645 |
collections_search_paths = ( |
| 1646 |
set(context.CLIARGS['collections_path'] or []) | default_collections_path | set(self.collection_paths) |
| 1647 |
) |
| 1648 |
collections_in_paths = {} |
| 1649 |
|
| 1650 |
warnings = [] |
| 1651 |
path_found = False |
| 1652 |
collection_found = False |
| 1653 |
|
| 1654 |
namespace_filter = None |
| 1655 |
collection_filter = None |
| 1656 |
if collection_name: |
| 1657 |
# list a specific collection |
| 1658 |
|
| 1659 |
validate_collection_name(collection_name) |
| 1660 |
namespace_filter, collection_filter = collection_name.split('.') |
| 1661 |
|
| 1662 |
collections = list(find_existing_collections( |
| 1663 |
list(collections_search_paths), |
| 1664 |
artifacts_manager, |
| 1665 |
namespace_filter=namespace_filter, |
| 1666 |
collection_filter=collection_filter, |
| 1667 |
dedupe=False |
| 1668 |
)) |
| 1669 |
|
| 1670 |
seen = set() |
| 1671 |
fqcn_width, version_width = _get_collection_widths(collections) |
| 1672 |
for collection in sorted(collections, key=lambda c: c.src): |
| 1673 |
collection_found = True |
| 1674 |
collection_path = pathlib.Path(to_text(collection.src)).parent.parent.as_posix() |
| 1675 |
|
| 1676 |
if output_format in {'yaml', 'json'}: |
| 1677 |
collections_in_paths.setdefault(collection_path, {}) |
| 1678 |
collections_in_paths[collection_path][collection.fqcn] = {'version': collection.ver} |
| 1679 |
else: |
| 1680 |
if collection_path not in seen: |
| 1681 |
_display_header( |
| 1682 |
collection_path, |
| 1683 |
'Collection', |
| 1684 |
'Version', |
| 1685 |
fqcn_width, |
| 1686 |
version_width |
| 1687 |
) |
| 1688 |
seen.add(collection_path) |
| 1689 |
_display_collection(collection, fqcn_width, version_width) |
| 1690 |
|
| 1691 |
path_found = False |
| 1692 |
for path in collections_search_paths: |
| 1693 |
if not os.path.exists(path): |
| 1694 |
if path in default_collections_path: |
| 1695 |
# don't warn for missing default paths |
| 1696 |
continue |
| 1697 |
warnings.append("- the configured path {0} does not exist.".format(path)) |
| 1698 |
elif os.path.exists(path) and not os.path.isdir(path): |
| 1699 |
warnings.append("- the configured path {0}, exists, but it is not a directory.".format(path)) |
| 1700 |
else: |
| 1701 |
path_found = True |
| 1702 |
|
| 1703 |
# Do not warn if the specific collection was found in any of the search paths |
| 1704 |
if collection_found and collection_name: |
| 1705 |
warnings = [] |
| 1706 |
|
| 1707 |
for w in warnings: |
| 1708 |
display.warning(w) |
| 1709 |
|
| 1710 |
if not collections and not path_found: |
| 1711 |
display.warning( |
| 1712 |
"None of the provided paths were usable. Please specify a valid path with --{0}s-path.".format(context.CLIARGS['type']) |
| 1713 |
) |
| 1714 |
|
| 1715 |
if output_format == 'json': |
| 1716 |
display.display(json.dumps(collections_in_paths)) |
| 1717 |
elif output_format == 'yaml': |
| 1718 |
display.display(yaml_dump(collections_in_paths)) |
| 1719 |
|
| 1720 |
return 0 |
| 1721 |
|
| 1722 |
def execute_publish(self): |
| 1723 |
""" |
| 1724 |
Publish a collection into Ansible Galaxy. Requires the path to the collection tarball to publish. |
| 1725 |
""" |
| 1726 |
collection_path = GalaxyCLI._resolve_path(context.CLIARGS['args']) |
| 1727 |
wait = context.CLIARGS['wait'] |
| 1728 |
timeout = context.CLIARGS['import_timeout'] |
| 1729 |
|
| 1730 |
publish_collection(collection_path, self.api, wait, timeout) |
| 1731 |
|
| 1732 |
def execute_search(self): |
| 1733 |
""" searches for roles on the Ansible Galaxy server""" |
| 1734 |
page_size = 1000 |
| 1735 |
search = None |
| 1736 |
|
| 1737 |
if context.CLIARGS['args']: |
| 1738 |
search = '+'.join(context.CLIARGS['args']) |
| 1739 |
|
| 1740 |
if not search and not context.CLIARGS['platforms'] and not context.CLIARGS['galaxy_tags'] and not context.CLIARGS['author']: |
| 1741 |
raise AnsibleError("Invalid query. At least one search term, platform, galaxy tag or author must be provided.") |
| 1742 |
|
| 1743 |
response = self.api.search_roles(search, platforms=context.CLIARGS['platforms'], |
| 1744 |
tags=context.CLIARGS['galaxy_tags'], author=context.CLIARGS['author'], page_size=page_size) |
| 1745 |
|
| 1746 |
if response['count'] == 0: |
| 1747 |
display.warning("No roles match your search.") |
| 1748 |
return 0 |
| 1749 |
|
| 1750 |
data = [u''] |
| 1751 |
|
| 1752 |
if response['count'] > page_size: |
| 1753 |
data.append(u"Found %d roles matching your search. Showing first %s." % (response['count'], page_size)) |
| 1754 |
else: |
| 1755 |
data.append(u"Found %d roles matching your search:" % response['count']) |
| 1756 |
|
| 1757 |
max_len = [] |
| 1758 |
for role in response['results']: |
| 1759 |
max_len.append(len(role['username'] + '.' + role['name'])) |
| 1760 |
name_len = max(max_len) |
| 1761 |
format_str = u" %%-%ds %%s" % name_len |
| 1762 |
data.append(u'') |
| 1763 |
data.append(format_str % (u"Name", u"Description")) |
| 1764 |
data.append(format_str % (u"----", u"-----------")) |
| 1765 |
for role in response['results']: |
| 1766 |
data.append(format_str % (u'%s.%s' % (role['username'], role['name']), role['description'])) |
| 1767 |
|
| 1768 |
data = u'\n'.join(data) |
| 1769 |
self.pager(data) |
| 1770 |
|
| 1771 |
return 0 |
| 1772 |
|
| 1773 |
_task_check_delay_sec = 10 # allows unit test override |
| 1774 |
|
| 1775 |
def execute_import(self): |
| 1776 |
""" used to import a role into Ansible Galaxy """ |
| 1777 |
|
| 1778 |
colors = { |
| 1779 |
'INFO': 'normal', |
| 1780 |
'WARNING': C.COLOR_WARN, |
| 1781 |
'ERROR': C.COLOR_ERROR, |
| 1782 |
'SUCCESS': C.COLOR_OK, |
| 1783 |
'FAILED': C.COLOR_ERROR, |
| 1784 |
} |
| 1785 |
|
| 1786 |
github_user = to_text(context.CLIARGS['github_user'], errors='surrogate_or_strict') |
| 1787 |
github_repo = to_text(context.CLIARGS['github_repo'], errors='surrogate_or_strict') |
| 1788 |
|
| 1789 |
rc = 0 |
| 1790 |
if context.CLIARGS['check_status']: |
| 1791 |
task = self.api.get_import_task(github_user=github_user, github_repo=github_repo) |
| 1792 |
else: |
| 1793 |
# Submit an import request |
| 1794 |
task = self.api.create_import_task(github_user, github_repo, |
| 1795 |
reference=context.CLIARGS['reference'], |
| 1796 |
role_name=context.CLIARGS['role_name']) |
| 1797 |
|
| 1798 |
if len(task) > 1: |
| 1799 |
# found multiple roles associated with github_user/github_repo |
| 1800 |
display.display("WARNING: More than one Galaxy role associated with Github repo %s/%s." % (github_user, github_repo), |
| 1801 |
color='yellow') |
| 1802 |
display.display("The following Galaxy roles are being updated:" + u'\n', color=C.COLOR_CHANGED) |
| 1803 |
for t in task: |
| 1804 |
display.display('%s.%s' % (t['summary_fields']['role']['namespace'], t['summary_fields']['role']['name']), color=C.COLOR_CHANGED) |
| 1805 |
display.display(u'\nTo properly namespace this role, remove each of the above and re-import %s/%s from scratch' % (github_user, github_repo), |
| 1806 |
color=C.COLOR_CHANGED) |
| 1807 |
return rc |
| 1808 |
# found a single role as expected |
| 1809 |
display.display("Successfully submitted import request %d" % task[0]['id']) |
| 1810 |
if not context.CLIARGS['wait']: |
| 1811 |
display.display("Role name: %s" % task[0]['summary_fields']['role']['name']) |
| 1812 |
display.display("Repo: %s/%s" % (task[0]['github_user'], task[0]['github_repo'])) |
| 1813 |
|
| 1814 |
if context.CLIARGS['check_status'] or context.CLIARGS['wait']: |
| 1815 |
# Get the status of the import |
| 1816 |
msg_list = [] |
| 1817 |
finished = False |
| 1818 |
while not finished: |
| 1819 |
task = self.api.get_import_task(task_id=task[0]['id']) |
| 1820 |
for msg in task[0]['summary_fields']['task_messages']: |
| 1821 |
if msg['id'] not in msg_list: |
| 1822 |
display.display(msg['message_text'], color=colors[msg['message_type']]) |
| 1823 |
msg_list.append(msg['id']) |
| 1824 |
if (state := task[0]['state']) in ['SUCCESS', 'FAILED']: |
| 1825 |
rc = ['SUCCESS', 'FAILED'].index(state) |
| 1826 |
finished = True |
| 1827 |
else: |
| 1828 |
time.sleep(self._task_check_delay_sec) |
| 1829 |
|
| 1830 |
return rc |
| 1831 |
|
| 1832 |
def execute_setup(self): |
| 1833 |
""" Setup an integration from Github or Travis for Ansible Galaxy roles""" |
| 1834 |
|
| 1835 |
if context.CLIARGS['setup_list']: |
| 1836 |
# List existing integration secrets |
| 1837 |
secrets = self.api.list_secrets() |
| 1838 |
if len(secrets) == 0: |
| 1839 |
# None found |
| 1840 |
display.display("No integrations found.") |
| 1841 |
return 0 |
| 1842 |
display.display(u'\n' + "ID Source Repo", color=C.COLOR_OK) |
| 1843 |
display.display("---------- ---------- ----------", color=C.COLOR_OK) |
| 1844 |
for secret in secrets: |
| 1845 |
display.display("%-10s %-10s %s/%s" % (secret['id'], secret['source'], secret['github_user'], |
| 1846 |
secret['github_repo']), color=C.COLOR_OK) |
| 1847 |
return 0 |
| 1848 |
|
| 1849 |
if context.CLIARGS['remove_id']: |
| 1850 |
# Remove a secret |
| 1851 |
self.api.remove_secret(context.CLIARGS['remove_id']) |
| 1852 |
display.display("Secret removed. Integrations using this secret will not longer work.", color=C.COLOR_OK) |
| 1853 |
return 0 |
| 1854 |
|
| 1855 |
source = context.CLIARGS['source'] |
| 1856 |
github_user = context.CLIARGS['github_user'] |
| 1857 |
github_repo = context.CLIARGS['github_repo'] |
| 1858 |
secret = context.CLIARGS['secret'] |
| 1859 |
|
| 1860 |
resp = self.api.add_secret(source, github_user, github_repo, secret) |
| 1861 |
display.display("Added integration for %s %s/%s" % (resp['source'], resp['github_user'], resp['github_repo'])) |
| 1862 |
|
| 1863 |
return 0 |
| 1864 |
|
| 1865 |
def execute_delete(self): |
| 1866 |
""" Delete a role from Ansible Galaxy. """ |
| 1867 |
|
| 1868 |
github_user = context.CLIARGS['github_user'] |
| 1869 |
github_repo = context.CLIARGS['github_repo'] |
| 1870 |
resp = self.api.delete_role(github_user, github_repo) |
| 1871 |
|
| 1872 |
if len(resp['deleted_roles']) > 1: |
| 1873 |
display.display("Deleted the following roles:") |
| 1874 |
display.display("ID User Name") |
| 1875 |
display.display("------ --------------- ----------") |
| 1876 |
for role in resp['deleted_roles']: |
| 1877 |
display.display("%-8s %-15s %s" % (role.id, role.namespace, role.name)) |
| 1878 |
|
| 1879 |
display.display(resp['status']) |
| 1880 |
|
| 1881 |
return 0 |
| 1882 |
|
| 1883 |
|
| 1884 |
def main(args=None): |
| 1885 |
GalaxyCLI.cli_executor(args) |
| 1886 |
|
| 1887 |
|
| 1888 |
if __name__ == '__main__': |
| 1889 |
main() |