diff --git a/.flake8 b/.flake8 index da14ecc7516..b309f6bffe4 100644 --- a/.flake8 +++ b/.flake8 @@ -15,9 +15,7 @@ exclude = doc build_scripts src/command_modules/azure-cli-storage - src/command_modules/azure-cli-lab src/command_modules/azure-cli-rdbms - src/command_modules/azure-cli-lab src/command_modules/azure-cli-sql src/command_modules/azure-cli-vm src/command_modules/azure-cli-acs diff --git a/scripts/ci/test_static.sh b/scripts/ci/test_static.sh index e44ba9738a1..b1dda9a9e5f 100755 --- a/scripts/ci/test_static.sh +++ b/scripts/ci/test_static.sh @@ -58,7 +58,7 @@ run_style azure.cli.command_modules.find run_style azure.cli.command_modules.interactive #run_style azure.cli.command_modules.iot run_style azure.cli.command_modules.keyvault -#run_style azure.cli.command_modules.lab +run_style azure.cli.command_modules.lab #run_style azure.cli.command_modules.monitor run_style azure.cli.command_modules.network #run_style azure.cli.command_modules.nspkg diff --git a/src/azure-cli-core/azure/cli/core/__init__.py b/src/azure-cli-core/azure/cli/core/__init__.py index c7bafd81cb0..640aab6ca74 100644 --- a/src/azure-cli-core/azure/cli/core/__init__.py +++ b/src/azure-cli-core/azure/cli/core/__init__.py @@ -317,8 +317,8 @@ def _cli_command(self, name, operation=None, handler=None, argument_loader=None, name = ' '.join(name.split()) command_type = kwargs.get('command_type', None) - client_factory = command_type.settings.get('client_factory', None) if command_type \ - else kwargs.get('client_factory', None) + client_factory = kwargs.get('client_factory', None) or command_type and \ + command_type.settings.get('client_factory', None) def default_command_handler(command_args): from azure.cli.core.util import get_arg_list diff --git a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/__init__.py b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/__init__.py index 187fbeab3e4..4f07e68ac75 100644 --- a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/__init__.py +++ b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/__init__.py @@ -3,12 +3,27 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- +from azure.cli.core import AzCommandsLoader + import azure.cli.command_modules.lab._help # pylint: disable=unused-import -def load_params(_): - import azure.cli.command_modules.lab._params # pylint: disable=redefined-outer-name, unused-variable +class DevTestLabCommandsLoader(AzCommandsLoader): + + def __init__(self, cli_ctx=None): + from azure.cli.core.commands import CliCommandType + lab_custom = CliCommandType(operations_tmpl='azure.cli.command_modules.lab.custom#{}') + super(DevTestLabCommandsLoader, self).__init__(cli_ctx=cli_ctx, custom_command_type=lab_custom, + min_profile='2017-03-10-profile') + + def load_command_table(self, args): + from azure.cli.command_modules.lab.commands import load_command_table + load_command_table(self, args) + return self.command_table + + def load_arguments(self, command): + from azure.cli.command_modules.lab._params import load_arguments + load_arguments(self, command) -def load_commands(): - import azure.cli.command_modules.lab.commands # pylint: disable=redefined-outer-name, unused-variable +COMMAND_LOADER_CLS = DevTestLabCommandsLoader diff --git a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/_client_factory.py b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/_client_factory.py index 7eae61c6441..0e3cf77e479 100644 --- a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/_client_factory.py +++ b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/_client_factory.py @@ -5,51 +5,51 @@ # MANAGEMENT CLIENT FACTORIES -def get_devtestlabs_management_client(_): +def get_devtestlabs_management_client(cli_ctx, _): from azure.mgmt.devtestlabs import DevTestLabsClient from azure.cli.core.commands.client_factory import get_mgmt_service_client - return get_mgmt_service_client(DevTestLabsClient) + return get_mgmt_service_client(cli_ctx, DevTestLabsClient) -def get_devtestlabs_virtual_machine_operation(kwargs): - return get_devtestlabs_management_client(kwargs).virtual_machines +def get_devtestlabs_virtual_machine_operation(cli_ctx, _): + return get_devtestlabs_management_client(cli_ctx, _).virtual_machines -def get_devtestlabs_lab_operation(kwargs): - return get_devtestlabs_management_client(kwargs).labs +def get_devtestlabs_lab_operation(cli_ctx, _): + return get_devtestlabs_management_client(cli_ctx, _).labs -def get_devtestlabs_custom_image_operation(kwargs): - return get_devtestlabs_management_client(kwargs).custom_images +def get_devtestlabs_custom_image_operation(cli_ctx, _): + return get_devtestlabs_management_client(cli_ctx, _).custom_images -def get_devtestlabs_gallery_image_operation(kwargs): - return get_devtestlabs_management_client(kwargs).gallery_images +def get_devtestlabs_gallery_image_operation(cli_ctx, _): + return get_devtestlabs_management_client(cli_ctx, _).gallery_images -def get_devtestlabs_artifact_operation(kwargs): - return get_devtestlabs_management_client(kwargs).artifacts +def get_devtestlabs_artifact_operation(cli_ctx, _): + return get_devtestlabs_management_client(cli_ctx, _).artifacts -def get_devtestlabs_artifact_source_operation(kwargs): - return get_devtestlabs_management_client(kwargs).artifact_sources +def get_devtestlabs_artifact_source_operation(cli_ctx, _): + return get_devtestlabs_management_client(cli_ctx, _).artifact_sources -def get_devtestlabs_virtual_network_operation(kwargs): - return get_devtestlabs_management_client(kwargs).virtual_networks +def get_devtestlabs_virtual_network_operation(cli_ctx, _): + return get_devtestlabs_management_client(cli_ctx, _).virtual_networks -def get_devtestlabs_formula_operation(kwargs): - return get_devtestlabs_management_client(kwargs).formulas +def get_devtestlabs_formula_operation(cli_ctx, _): + return get_devtestlabs_management_client(cli_ctx, _).formulas -def get_devtestlabs_secret_operation(kwargs): - return get_devtestlabs_management_client(kwargs).secrets +def get_devtestlabs_secret_operation(cli_ctx, _): + return get_devtestlabs_management_client(cli_ctx, _).secrets -def get_devtestlabs_environment_operation(kwargs): - return get_devtestlabs_management_client(kwargs).environments +def get_devtestlabs_environment_operation(cli_ctx, _): + return get_devtestlabs_management_client(cli_ctx, _).environments -def get_devtestlabs_arm_template_operation(kwargs): - return get_devtestlabs_management_client(kwargs).arm_templates +def get_devtestlabs_arm_template_operation(cli_ctx, _): + return get_devtestlabs_management_client(cli_ctx, _).arm_templates diff --git a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/_format.py b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/_format.py new file mode 100644 index 00000000000..a2b48091275 --- /dev/null +++ b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/_format.py @@ -0,0 +1,59 @@ +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + + +from collections import OrderedDict + + +def export_artifacts(formula): + """ Exports artifacts from the given formula. This method removes some of the properties of the + artifact model as they do not play important part for users in create or read context. + """ + artifacts = [] + if formula and formula.formula_content and formula.formula_content.artifacts: + artifacts = formula.formula_content.artifacts + for artifact in formula.formula_content.artifacts: + del artifact.status + del artifact.deployment_status_message + del artifact.vm_extension_status_message + del artifact.install_time + return artifacts + + +def transform_artifact_source_list(artifact_source_list): + return [transform_artifact_source(v) for v in artifact_source_list] + + +def transform_artifact_source(result): + return OrderedDict([('name', result['name']), + ('sourceType', result['sourceType']), + ('status', result.get('status')), + ('uri', result.get('uri'))]) + + +def transform_arm_template_list(arm_template_list): + return [transform_arm_template(v) for v in arm_template_list] + + +def transform_arm_template(result): + return OrderedDict([('name', result['name']), + ('resourceGroup', result['resourceGroup']), + ('publisher', result.get('publisher'))]) + + +def transform_vm_list(vm_list): + return [_transform_vm_dict(v) for v in vm_list] + + +def _transform_vm_dict(result): + return OrderedDict([('name', result['name']), + ('location', result['location']), + ('osType', result['osType'])]) + + +def transform_vm(result): + return OrderedDict([('name', result.name), + ('location', result.location), + ('osType', result.os_type)]) diff --git a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/_params.py b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/_params.py index c7dde28523c..0570adb956f 100644 --- a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/_params.py +++ b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/_params.py @@ -3,116 +3,78 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -from azure.cli.command_modules.lab.validators import (validate_lab_vm_create, - validate_lab_vm_list, - validate_user_name, - validate_template_id, - validate_claim_vm, - _validate_artifacts) -from azure.cli.core.commands.parameters import resource_group_name_type -from azure.cli.core.commands import ParametersContext +from azure.cli.command_modules.lab.validators import validate_artifacts, validate_template_id from azure.cli.core.util import get_json_object -with ParametersContext(command='lab') as c: - c.argument('resource_group', arg_type=resource_group_name_type, - help='Name of lab\'s resource group. You can configure the default group ' - 'using \'az configure --defaults group=\'') +def load_arguments(self, _): + with self.argument_context('lab custom-image create') as c: + c.argument('name', options_list=['--name', '-n']) -with ParametersContext(command='lab custom-image create') as c: - c.register_alias('resource_group', ('--resource-group', '-g')) - c.register_alias('name', ('--name', '-n')) + with self.argument_context('lab vm create') as c: + c.argument('name', options_list=['--name', '-n']) -with ParametersContext(command='lab vm create') as c: - c.register_alias('resource_group', ('--resource-group', '-g'), validator=validate_lab_vm_create) - c.register_alias('name', ('--name', '-n')) + # Authentication related arguments + for arg_name in ['admin_username', 'admin_password', 'authentication_type', 'ssh_key', 'generate_ssh_keys', + 'saved_secret']: + c.argument(arg_name, arg_group='Authentication') + c.argument('generate_ssh_keys', action='store_true') - # Authentication related arguments - authentication_group_name = 'Authentication' - c.argument('admin_username', arg_group=authentication_group_name) - c.argument('admin_password', arg_group=authentication_group_name) - c.argument('authentication_type', arg_group=authentication_group_name) - c.argument('ssh_key', arg_group=authentication_group_name) - c.argument('generate_ssh_keys', action='store_true', arg_group=authentication_group_name) - c.argument('saved_secret', arg_group=authentication_group_name) + # Add Artifacts from json object + c.argument('artifacts', type=get_json_object) - # Add Artifacts from json object - c.argument('artifacts', type=get_json_object) + # Image related arguments + c.ignore('os_type', 'gallery_image_reference', 'custom_image_id') - # Image related arguments - c.ignore('os_type') - c.ignore('gallery_image_reference') - c.ignore('custom_image_id') - c.argument('image') + # Network related arguments + for arg_name in ['ip_configuration', 'subnet', 'vnet_name']: + c.argument(arg_name, arg_group='Network') - # Network related arguments - network_group_name = 'Network' - c.argument('ip_configuration', arg_group=network_group_name) - c.argument('subnet', arg_group=network_group_name) - c.argument('vnet_name', arg_group=network_group_name) - c.ignore('lab_subnet_name') - c.ignore('lab_virtual_network_id') - c.ignore('disallow_public_ip_address') - c.ignore('network_interface') + c.ignore('lab_subnet_name', 'lab_virtual_network_id', 'disallow_public_ip_address', 'network_interface') - # Creating VM in the different location then lab is an officially unsupported scenario - c.ignore('location') + # Creating VM in the different location then lab is an officially unsupported scenario + c.ignore('location') + c.argument('allow_claim', action='store_true') - c.argument('expiration_date') - c.argument('formula') - c.argument('allow_claim', action='store_true') + with self.argument_context('lab vm list') as c: + for arg_name in ['filters', 'all', 'claimable', 'environment']: + c.argument(arg_name, arg_group='Filter') + for arg_name in ['all', 'claimable']: + c.argument(arg_name, action='store_true') -with ParametersContext(command='lab vm list') as c: - filter_arg_group_name = 'Filter' - c.argument('filters', arg_group=filter_arg_group_name) - c.argument('all', action='store_true', arg_group=filter_arg_group_name) - c.argument('claimable', action='store_true', arg_group=filter_arg_group_name) - c.argument('environment', arg_group=filter_arg_group_name) - c.register_alias('resource_group', ('--resource-group', '-g'), validator=validate_lab_vm_list) + with self.argument_context('lab vm claim') as c: + c.argument('name', options_list=['--name', '-n'], id_part='child_name_1') + c.argument('lab_name', id_part='name') + with self.argument_context('lab vm apply-artifacts') as c: + c.argument('artifacts', type=get_json_object, validator=validate_artifacts) + c.argument('name', options_list=['--name', '-n']) -with ParametersContext(command='lab vm claim') as c: - c.register_alias('resource_group', ('--resource-group', '-g'), validator=validate_claim_vm) - c.register_alias('name', ('--name', '-n'), id_part='child_name_1') - c.argument('lab_name', id_part='name') + with self.argument_context('lab formula') as c: + c.argument('name', options_list=['--name', '-n']) + with self.argument_context('lab secret') as c: + from azure.mgmt.devtestlabs.models.secret import Secret -with ParametersContext(command='lab vm apply-artifacts') as c: - c.register('artifacts', ('--artifacts',), type=get_json_object, validator=_validate_artifacts) - c.register_alias('name', ('--name', '-n')) + c.argument('name', options_list=['--name', '-n']) + c.argument('secret', options_list=['--value'], type=lambda x: Secret(value=x)) + c.ignore('user_name') + with self.argument_context('lab formula export-artifacts') as c: + # Exporting artifacts does not need expand filter + c.ignore('expand') -with ParametersContext(command='lab formula') as c: - c.register_alias('name', ('--name', '-n')) + with self.argument_context('lab environment') as c: + c.argument('name', options_list=['--name', '-n']) + c.ignore('user_name') + with self.argument_context('lab environment create') as c: + c.argument('arm_template', validator=validate_template_id) + c.argument('parameters', type=get_json_object) -with ParametersContext(command='lab secret') as c: - from azure.mgmt.devtestlabs.models.secret import Secret + with self.argument_context('lab arm-template') as c: + c.argument('name', options_list=['--name', '-n']) - c.register_alias('name', ('--name', '-n')) - c.register_alias('secret', ('--value', ), type=lambda x: Secret(value=x)) - c.ignore('user_name') - c.argument('lab_name', validator=validate_user_name) - - -with ParametersContext(command='lab formula export-artifacts') as c: - # Exporting artifacts does not need expand filter - c.ignore('expand') - - -with ParametersContext(command='lab environment') as c: - c.register_alias('name', ('--name', '-n')) - c.ignore('user_name') - c.argument('lab_name', validator=validate_user_name) - - -with ParametersContext(command='lab environment create') as c: - c.argument('arm_template', validator=validate_template_id) - c.argument('parameters', type=get_json_object) - -with ParametersContext(command='lab arm-template') as c: - c.register_alias('name', ('--name', '-n')) - -with ParametersContext(command='lab arm-template show') as c: - c.argument('export_parameters', action='store_true') + with self.argument_context('lab arm-template show') as c: + c.argument('export_parameters', action='store_true') diff --git a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/commands.py b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/commands.py index 7de7a38cab1..1140a45f22b 100644 --- a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/commands.py +++ b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/commands.py @@ -3,9 +3,7 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -from collections import OrderedDict -from azure.cli.core.profiles import supported_api_version, PROFILE_TYPE -from azure.cli.core.commands import (ServiceGroup, create_service_adapter) +from azure.cli.core.commands import CliCommandType from ._client_factory import (get_devtestlabs_virtual_machine_operation, get_devtestlabs_custom_image_operation, get_devtestlabs_gallery_image_operation, @@ -17,205 +15,138 @@ get_devtestlabs_secret_operation, get_devtestlabs_environment_operation, get_devtestlabs_arm_template_operation) - -if not supported_api_version(PROFILE_TYPE, max_api='2017-03-09-profile'): - custom_path = 'azure.cli.command_modules.lab.custom' - mgmt_operations_path = 'azure.mgmt.devtestlabs.operations.{}' - - def _export_artifacts(formula): - """ Exports artifacts from the given formula. This method removes some of the properties of the - artifact model as they do not play important part for users in create or read context. - """ - artifacts = [] - if formula and formula.formula_content and formula.formula_content.artifacts: - artifacts = formula.formula_content.artifacts - for artifact in formula.formula_content.artifacts: - del artifact.status - del artifact.deployment_status_message - del artifact.vm_extension_status_message - del artifact.install_time - return artifacts - - def transform_artifact_source_list(artifact_source_list): - return [transform_artifact_source(v) for v in artifact_source_list] - - def transform_artifact_source(result): - return OrderedDict([('name', result['name']), - ('sourceType', result['sourceType']), - ('status', result.get('status')), - ('uri', result.get('uri'))]) - - def transform_arm_template_list(arm_template_list): - return [transform_arm_template(v) for v in arm_template_list] - - def transform_arm_template(result): - return OrderedDict([('name', result['name']), - ('resourceGroup', result['resourceGroup']), - ('publisher', result.get('publisher'))]) - - def transform_vm_list(vm_list): - return [transform_vm(v) for v in vm_list] - - def transform_vm(result): - return OrderedDict([('name', result['name']), - ('location', result['location']), - ('osType', result['osType'])]) - - # Custom Command's service adapter - custom_operations = create_service_adapter(custom_path) +from .validators import validate_lab_vm_create, validate_lab_vm_list, validate_claim_vm, validate_user_name +from ._format import (transform_artifact_source_list, transform_artifact_source, transform_arm_template_list, + transform_arm_template, transform_vm_list, transform_vm, export_artifacts) + + +# pylint: disable=too-many-locals, too-many-statements +def load_command_table(self, _): + + virtual_machine_operations = CliCommandType( + operations_tmpl='azure.mgmt.devtestlabs.operations.virtual_machines_operations#VirtualMachinesOperations.{}', + client_factory=get_devtestlabs_virtual_machine_operation + ) + + lab_operations = CliCommandType( + operations_tmpl='azure.mgmt.devtestlabs.operations.labs_operations#LabsOperations.{}', + client_factory=get_devtestlabs_lab_operation + ) + + custom_image_operations = CliCommandType( + operations_tmpl='azure.mgmt.devtestlabs.operations.custom_images_operations#CustomImagesOperations.{}', + client_factory=get_devtestlabs_custom_image_operation + ) + + gallery_image_operations = CliCommandType( + operations_tmpl='azure.mgmt.devtestlabs.operations.gallery_images_operations#GalleryImagesOperations.{}', + client_factory=get_devtestlabs_gallery_image_operation + ) + + artifact_operations = CliCommandType( + operations_tmpl='azure.mgmt.devtestlabs.operations.artifacts_operations#ArtifactsOperations.{}', + client_factory=get_devtestlabs_artifact_operation + ) + + artifact_source_operations = CliCommandType( + operations_tmpl='azure.mgmt.devtestlabs.operations.artifact_sources_operations#ArtifactSourcesOperations.{}', + client_factory=get_devtestlabs_artifact_source_operation + ) + + virtual_network_operations = CliCommandType( + operations_tmpl='azure.mgmt.devtestlabs.operations.virtual_networks_operations#VirtualNetworksOperations.{}', + client_factory=get_devtestlabs_virtual_network_operation + ) + + formula_operations = CliCommandType( + operations_tmpl='azure.mgmt.devtestlabs.operations.formulas_operations#FormulasOperations.{}', + client_factory=get_devtestlabs_formula_operation + ) + + secret_operations = CliCommandType( + operations_tmpl='azure.mgmt.devtestlabs.operations.secrets_operations#SecretsOperations.{}', + client_factory=get_devtestlabs_secret_operation, + validator=validate_user_name + ) + + environment_operations = CliCommandType( + operations_tmpl='azure.mgmt.devtestlabs.operations.environments_operations#EnvironmentsOperations.{}', + client_factory=get_devtestlabs_environment_operation, + validator=validate_user_name + ) + + arm_template_operations = CliCommandType( + operations_tmpl='azure.mgmt.devtestlabs.operations.arm_templates_operations#ArmTemplatesOperations.{}', + client_factory=get_devtestlabs_arm_template_operation + ) # Virtual Machine Operations Commands - virtual_machine_operations = create_service_adapter( - mgmt_operations_path.format('virtual_machines_operations'), - 'VirtualMachinesOperations') - - with ServiceGroup(__name__, get_devtestlabs_virtual_machine_operation, - virtual_machine_operations) as s: - with s.group('lab vm') as c: - c.command('show', 'get', table_transformer=transform_vm) - c.command('delete', 'delete') - c.command('start', 'start') - c.command('stop', 'stop') - c.command('apply-artifacts', 'apply_artifacts') - - # Virtual Machine Operations Custom Commands - with ServiceGroup(__name__, get_devtestlabs_virtual_machine_operation, - custom_operations) as s: - with s.group('lab vm') as c: - c.command('list', 'list_vm', table_transformer=transform_vm_list) - c.command('claim', 'claim_vm') - - # Lab Operations Custom Commands - with ServiceGroup(__name__, get_devtestlabs_lab_operation, - custom_operations) as s: - with s.group('lab vm') as c: - c.command('create', 'create_lab_vm') - - lab_operations = create_service_adapter(mgmt_operations_path.format('labs_operations'), - 'LabsOperations') + with self.command_group('lab vm', virtual_machine_operations, + client_factory=get_devtestlabs_virtual_machine_operation) as g: + g.command('show', 'get', transform=transform_vm) + g.command('delete', 'delete') + g.command('start', 'start') + g.command('stop', 'stop') + g.command('apply-artifacts', 'apply_artifacts') + g.custom_command('list', 'list_vm', validator=validate_lab_vm_list, table_transformer=transform_vm_list) + g.custom_command('claim', 'claim_vm', validator=validate_claim_vm) + g.custom_command('create', 'create_lab_vm', client_factory=get_devtestlabs_lab_operation, + validator=validate_lab_vm_create) # Lab Operations Commands - with ServiceGroup(__name__, get_devtestlabs_lab_operation, - lab_operations) as s: - with s.group('lab') as c: - c.command('get', 'get') - c.command('delete', 'delete') + with self.command_group('lab', lab_operations) as g: + g.command('get', 'get') + g.command('delete', 'delete') # Custom Image Operations Commands - custom_image_operations = create_service_adapter( - mgmt_operations_path.format('custom_images_operations'), - 'CustomImagesOperations') - - with ServiceGroup(__name__, get_devtestlabs_custom_image_operation, - custom_image_operations) as s: - with s.group('lab custom-image') as c: - c.command('show', 'get') - c.command('list', 'list') - c.command('delete', 'delete') - - with ServiceGroup(__name__, get_devtestlabs_custom_image_operation, custom_operations) as s: - with s.group('lab custom-image') as c: - c.command('create', 'create_custom_image') + with self.command_group('lab custom-image', custom_image_operations) as g: + g.command('show', 'get') + g.command('list', 'list') + g.command('delete', 'delete') + g.custom_command('create', 'create_custom_image', client_factory=get_devtestlabs_custom_image_operation) # Gallery Image Operations Commands - gallery_image_operations = create_service_adapter( - mgmt_operations_path.format('gallery_images_operations'), - 'GalleryImagesOperations') - - with ServiceGroup(__name__, get_devtestlabs_gallery_image_operation, - gallery_image_operations) as s: - with s.group('lab gallery-image') as c: - c.command('list', 'list') + with self.command_group('lab gallery-image', gallery_image_operations) as g: + g.command('list', 'list') # Artifact Operations Commands - artifact_operations = create_service_adapter( - mgmt_operations_path.format('artifacts_operations'), - 'ArtifactsOperations') - - with ServiceGroup(__name__, get_devtestlabs_artifact_operation, - artifact_operations) as s: - with s.group('lab artifact') as c: - c.command('list', 'list') + with self.command_group('lab artifact', artifact_operations) as g: + g.command('list', 'list') # Artifact Source Operations Commands - artifact_source_operations = create_service_adapter( - mgmt_operations_path.format('artifact_sources_operations'), - 'ArtifactSourcesOperations') - - with ServiceGroup(__name__, get_devtestlabs_artifact_source_operation, - artifact_source_operations) as s: - with s.group('lab artifact-source') as c: - c.command('list', 'list', table_transformer=transform_artifact_source_list) - c.command('show', 'get', table_transformer=transform_artifact_source) + with self.command_group('lab artifact-source', artifact_source_operations) as g: + g.command('list', 'list', table_transformer=transform_artifact_source_list) + g.command('show', 'get', transform=transform_artifact_source) # Virtual Network Operations Commands - virtual_network_operations = create_service_adapter( - mgmt_operations_path.format('virtual_networks_operations'), - 'VirtualNetworksOperations') - - with ServiceGroup(__name__, get_devtestlabs_virtual_network_operation, - virtual_network_operations) as s: - with s.group('lab vnet') as c: - c.command('list', 'list') - c.command('get', 'get') + with self.command_group('lab vnet', virtual_network_operations) as g: + g.command('list', 'list') + g.command('get', 'get') # Formula Operations Commands - formula_operations = create_service_adapter( - mgmt_operations_path.format('formulas_operations'), - 'FormulasOperations') - - with ServiceGroup(__name__, get_devtestlabs_formula_operation, - formula_operations) as s: - with s.group('lab formula') as c: - c.command('show', 'get') - c.command('list', 'list') - c.command('delete', 'delete') - c.command('export-artifacts', 'get', transform=_export_artifacts) + with self.command_group('lab formula', formula_operations) as g: + g.command('show', 'get') + g.command('list', 'list') + g.command('delete', 'delete') + g.command('export-artifacts', 'get', transform=export_artifacts) # Secret Operations Commands - secret_operations = create_service_adapter( - mgmt_operations_path.format('secrets_operations'), - 'SecretsOperations') - - with ServiceGroup(__name__, get_devtestlabs_secret_operation, - secret_operations) as s: - with s.group('lab secret') as c: - c.command('set', 'create_or_update') - c.command('show', 'get') - c.command('list', 'list') - c.command('delete', 'delete') + with self.command_group('lab secret', secret_operations) as g: + g.command('set', 'create_or_update') + g.command('show', 'get') + g.command('list', 'list') + g.command('delete', 'delete') # Environment Operations Commands - environment_operations = create_service_adapter( - mgmt_operations_path.format('environments_operations'), - 'EnvironmentsOperations') - - with ServiceGroup(__name__, get_devtestlabs_environment_operation, - environment_operations) as s: - with s.group('lab environment') as c: - c.command('show', 'get') - c.command('list', 'list') - c.command('delete', 'delete') - c.command('create', 'create_or_update') - - # Environment Operations Custom Commands - with ServiceGroup(__name__, get_devtestlabs_environment_operation, - custom_operations) as s: - with s.group('lab environment') as c: - c.command('create', 'create_environment') + with self.command_group('lab environment', environment_operations) as g: + g.command('show', 'get') + g.command('list', 'list') + g.command('delete', 'delete') + g.command('create', 'create_or_update') + g.custom_command('create', 'create_environment', client_factory=get_devtestlabs_environment_operation) # ARM Templates Operations Commands - arm_template_operations = create_service_adapter( - mgmt_operations_path.format('arm_templates_operations'), - 'ArmTemplatesOperations') - - with ServiceGroup(__name__, get_devtestlabs_arm_template_operation, - arm_template_operations) as s: - with s.group('lab arm-template') as c: - c.command('list', 'list', table_transformer=transform_arm_template_list) - - # ARM Templates Operations Custom Commands - with ServiceGroup(__name__, get_devtestlabs_arm_template_operation, - custom_operations) as s: - with s.group('lab arm-template') as c: - c.command('show', 'show_arm_template', table_transformer=transform_arm_template) + with self.command_group('lab arm-template', arm_template_operations) as g: + g.command('list', 'list', table_transformer=transform_arm_template_list) + g.custom_command('show', 'show_arm_template', transform=transform_arm_template, + client_factory=get_devtestlabs_arm_template_operation) diff --git a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/custom.py b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/custom.py index ca06a6c3e84..8868d25dce4 100644 --- a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/custom.py +++ b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/custom.py @@ -12,7 +12,7 @@ # pylint: disable=too-many-locals, unused-argument, too-many-statements -def create_custom_image(client, resource_group, lab_name, name, source_vm_id, os_type, os_state, +def create_custom_image(client, resource_group_name, lab_name, name, source_vm_id, os_type, os_state, author=None, description=None): """ Command to create a custom image from a source VM, managed image, or VHD """ @@ -27,10 +27,10 @@ def create_custom_image(client, resource_group, lab_name, name, source_vm_id, os author=author, description=description) - return client.create_or_update(resource_group, lab_name, name, customImage) + return client.create_or_update(resource_group_name, lab_name, name, customImage) -def create_lab_vm(client, resource_group, lab_name, name, notes=None, image=None, image_type=None, +def create_lab_vm(client, resource_group_name, lab_name, name, notes=None, image=None, image_type=None, size=None, admin_username=getpass.getuser(), admin_password=None, ssh_key=None, authentication_type='password', vnet_name=None, subnet=None, disallow_public_ip_address=None, artifacts=None, @@ -64,31 +64,30 @@ def create_lab_vm(client, resource_group, lab_name, name, notes=None, image=None allow_claim=allow_claim, storage_type=disk_type, expiration_date=expiration_date) - - return client.create_environment(resource_group, lab_name, lab_virtual_machine) + return client.create_environment(resource_group_name, lab_name, lab_virtual_machine) # pylint: disable=redefined-builtin -def list_vm(client, resource_group, lab_name, order_by=None, top=None, +def list_vm(client, resource_group_name, lab_name, order_by=None, top=None, filters=None, all=None, claimable=None, environment=None, expand=None, object_id=None): """ Command to list vms by resource group in the Azure DevTest Lab """ - return client.list(resource_group, lab_name, + return client.list(resource_group_name, lab_name, expand=expand, filter=filters, top=top, order_by=order_by) -def claim_vm(client, lab_name=None, name=None, resource_group=None): +def claim_vm(cmd, client, lab_name=None, name=None, resource_group_name=None): """ Command to claim a VM in the Azure DevTest Lab""" if name is not None: - return client.claim(resource_group, lab_name, name) + return client.claim(resource_group_name, lab_name, name) from ._client_factory import get_devtestlabs_lab_operation - return get_devtestlabs_lab_operation(None).claim_any_vm(resource_group, lab_name) + return get_devtestlabs_lab_operation(cmd.cli_ctx, None).claim_any_vm(resource_group_name, lab_name) # pylint: disable=too-many-locals, unused-argument -def create_environment(client, resource_group, lab_name, name, arm_template, parameters=None, +def create_environment(client, resource_group_name, lab_name, name, arm_template, parameters=None, artifact_source_name=None, user_name=None, tags=None): """ Command to create an environment the Azure DevTest Lab """ @@ -100,14 +99,14 @@ def create_environment(client, resource_group, lab_name, name, arm_template, par dtl_environment = DtlEnvironment(tags=tags, deployment_properties=environment_deployment_properties) - return client.create_or_update(resource_group, lab_name, user_name, name, dtl_environment) + return client.create_or_update(resource_group_name, lab_name, user_name, name, dtl_environment) -def show_arm_template(client, resource_group, lab_name, name, +def show_arm_template(client, resource_group_name, lab_name, name, artifact_source_name, export_parameters=False): """ Command to show azure resource manager template in the Azure DevTest Lab """ - arm_template = client.get(resource_group, lab_name, artifact_source_name, name) + arm_template = client.get(resource_group_name, lab_name, artifact_source_name, name) if export_parameters: return _export_parameters(arm_template) return arm_template diff --git a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/tests/docdbenv_paramters.json b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/tests/docdbenv_parameters.json similarity index 100% rename from src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/tests/docdbenv_paramters.json rename to src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/tests/docdbenv_parameters.json diff --git a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/tests/test_lab.py b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/tests/test_lab.py index df1b1569c59..7b40b834055 100644 --- a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/tests/test_lab.py +++ b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/tests/test_lab.py @@ -4,137 +4,144 @@ # -------------------------------------------------------------------------------------------- import os -from azure.cli.testsdk.vcr_test_base import ResourceGroupVCRTestBase, JMESPathCheck, NoneCheck from azure.cli.testsdk import record_only +from azure.cli.testsdk import ScenarioTest, ResourceGroupPreparer -TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) -TEMPLATE = '{}/lab_template.json'.format(TEST_DIR) -ENV_PARAMTERS = '@{}/docdbenv_paramters.json'.format(TEST_DIR) +TEST_DIR = os.path.dirname(os.path.realpath(__file__)) +TEMPLATE = os.path.join(TEST_DIR, 'lab_template.json').replace('\\', '\\\\') +ENV_PARAMETERS = os.path.join('@' + TEST_DIR, 'lab_template.json').replace('\\', '\\\\') LAB_NAME = 'cliautomationlab' -class LabGalleryVMMgmtScenarioTest(ResourceGroupVCRTestBase): - - def __init__(self, test_method): - super(LabGalleryVMMgmtScenarioTest, self).__init__(__file__, test_method, - resource_group='cliautomation') +class LabGalleryVMMgmtScenarioTest(ScenarioTest): @record_only() - def test_lab_gallery_vm_mgmt(self): - self.execute() - - def body(self): - rg = self.resource_group - linux_vm_name = 'ubuntuvm5367' - linux_image = 'Ubuntu\ Server\ 16.04\ LTS' - windows_vm_name = 'winvm5367' - windows_image = 'Windows\ Server\ 2008\ R2\ SP1' - image_type = 'gallery' - size = 'Standard_DS1_v2' - password = 'SecretPassword123' - - self.cmd('group deployment create -g {} --template-file {}' - .format(rg, TEMPLATE), - checks=[JMESPathCheck('properties.provisioningState', 'Succeeded')]) + @ResourceGroupPreparer(name_prefix='cliautomation') + def test_lab_gallery_vm_mgmt(self, resource_group): + self.kwargs.update({ + 'linux_vm_name': 'ubuntuvm5367', + 'linux_image': '\"Ubuntu Server 16.04 LTS\"', + 'windows_vm_name': 'winvm5367', + 'windows_image': '\"Windows Server 2008 R2 SP1\"', + 'image_type': 'gallery', + 'size': 'Standard_DS1_v2', + 'password': 'SecretPassword123', + 'template': TEMPLATE, + 'lab_name': LAB_NAME + }) + + self.cmd('group deployment create -g {rg} --template-file {template}', checks=[ + self.check('properties.provisioningState', 'Succeeded') + ]) # Create claimable linux vm in the lab - self.cmd('lab vm create -g {} --lab-name {} --name {} ' - '--image {} --image-type {} --size {} --admin-password {} --allow-claim' - .format(rg, LAB_NAME, linux_vm_name, linux_image, image_type, size, password), - checks=[NoneCheck()]) - - self.cmd('lab vm show -g {} --lab-name {} --name {}' - .format(rg, LAB_NAME, linux_vm_name), - checks=[ - JMESPathCheck('name', linux_vm_name), - JMESPathCheck('provisioningState', 'Succeeded'), - JMESPathCheck('osType', 'Linux'), - JMESPathCheck('virtualMachineCreationSource', 'FromGalleryImage'), - JMESPathCheck('size', size), - JMESPathCheck('disallowPublicIpAddress', True), - JMESPathCheck('artifactDeploymentStatus.totalArtifacts', 0), - JMESPathCheck('galleryImageReference.publisher', 'Canonical') - ]) + self.cmd('lab vm create -g {rg} --lab-name {lab_name} --name {linux_vm_name} --image {linux_image}' + ' --image-type {image_type} --size {size} --admin-password {password} --allow-claim', checks=[ + self.is_empty()]) + + self.cmd('lab vm show -g {rg} --lab-name {lab_name} --name {linux_vm_name}', checks=[ + self.check('name', '{linux_vm_name}'), + self.check('provisioningState', 'Succeeded'), + self.check('osType', 'Linux'), + self.check('virtualMachineCreationSource', 'FromGalleryImage'), + self.check('size', '{size}'), + self.check('disallowPublicIpAddress', True), + self.check('artifactDeploymentStatus.totalArtifacts', 0), + self.check('galleryImageReference.publisher', 'Canonical') + ]) # Create windows vm in the lab - self.cmd('lab vm create -g {} --lab-name {} --name {} ' - '--image {} --image-type {} --size {} --admin-password {} --allow-claim' - .format(rg, LAB_NAME, windows_vm_name, windows_image, image_type, size, password), - checks=[NoneCheck()]) - - self.cmd('lab vm show -g {} --lab-name {} --name {} ' - .format(rg, LAB_NAME, windows_vm_name), - checks=[ - JMESPathCheck('name', windows_vm_name), - JMESPathCheck('provisioningState', 'Succeeded'), - JMESPathCheck('osType', 'Windows'), - JMESPathCheck('virtualMachineCreationSource', 'FromGalleryImage'), - JMESPathCheck('size', size), - JMESPathCheck('disallowPublicIpAddress', True), - JMESPathCheck('artifactDeploymentStatus.totalArtifacts', 0), - JMESPathCheck('galleryImageReference.publisher', 'MicrosoftWindowsServer') - ]) + self.cmd('lab vm create -g {rg} --lab-name {lab_name} --name {windows_vm_name} ' + '--image {windows_image} --image-type {image_type} --size {size} --admin-password {password} ' + '--allow-claim', checks=[ + self.is_empty()]) + + self.cmd('lab vm show -g {rg} --lab-name {lab_name} --name {windows_vm_name} ', checks=[ + self.check('name', '{windows_vm_name}'), + self.check('provisioningState', 'Succeeded'), + self.check('osType', 'Windows'), + self.check('virtualMachineCreationSource', 'FromGalleryImage'), + self.check('size', '{size}'), + self.check('disallowPublicIpAddress', True), + self.check('artifactDeploymentStatus.totalArtifacts', 0), + self.check('galleryImageReference.publisher', 'MicrosoftWindowsServer') + ]) # List claimable vms - self.cmd('lab vm list -g {} --lab-name {} --claimable' - .format(rg, LAB_NAME), checks=[JMESPathCheck('length(@)', 2)]) + self.cmd('lab vm list -g {rg} --lab-name {lab_name} --claimable', checks=[ + self.check('length(@)', 2) + ]) # claim a specific vm - self.cmd('lab vm claim -g {} --lab-name {} --name {}' - .format(rg, LAB_NAME, linux_vm_name), checks=[NoneCheck()]) + self.cmd('lab vm claim -g {rg} --lab-name {lab_name} --name {linux_vm_name}', checks=[ + self.is_empty() + ]) # List my vms - we have already claimed one VM - self.cmd('lab vm list -g {} --lab-name {}' - .format(rg, LAB_NAME), checks=[JMESPathCheck('length(@)', 1)]) + self.cmd('lab vm list -g {rg} --lab-name {lab_name}', checks=[ + self.check('length(@)', 1) + ]) # claim any vm - self.cmd('lab vm claim -g {} --lab-name {}'.format(rg, LAB_NAME), checks=[NoneCheck()]) + self.cmd('lab vm claim -g {rg} --lab-name {lab_name}', checks=[ + self.is_empty() + ]) # List my vms - we have claimed both VMs - self.cmd('lab vm list -g {} --lab-name {}' - .format(rg, LAB_NAME), checks=[JMESPathCheck('length(@)', 2)]) + self.cmd('lab vm list -g {rg} --lab-name {lab_name}', checks=[ + self.check('length(@)', 2) + ]) # Delete all the vms - self.cmd('lab vm delete -g {} --lab-name {} --name {}' - .format(rg, LAB_NAME, linux_vm_name), checks=[NoneCheck()]) - self.cmd('lab vm delete -g {} --lab-name {} --name {}' - .format(rg, LAB_NAME, windows_vm_name), checks=[NoneCheck()]) + self.cmd('lab vm delete -g {rg} --lab-name {lab_name} --name {linux_vm_name}', checks=[ + self.is_empty() + ]) + self.cmd('lab vm delete -g {rg} --lab-name {lab_name} --name {windows_vm_name}', checks=[ + self.is_empty() + ]) # Delete the lab - self.cmd('lab delete -g {} --name {}'.format(rg, LAB_NAME), checks=[NoneCheck()]) - - -class LabEnvironmentMgmtScenarioTest(ResourceGroupVCRTestBase): + self.cmd('lab delete -g {rg} --name {lab_name}', checks=[ + self.is_empty() + ]) - def __init__(self, test_method): - super(LabEnvironmentMgmtScenarioTest, self).__init__(__file__, test_method, - resource_group='cliautomation01') +class LabEnvironmentMgmtScenarioTest(ScenarioTest): @record_only() - def test_lab_environment_mgmt(self): - self.execute() - - def body(self): - rg = self.resource_group - env_name = 'docdbenv' - arm_template = 'documentdb-webapp' - - self.cmd('group deployment create -g {} --template-file {}'.format(rg, TEMPLATE), - checks=[JMESPathCheck('properties.provisioningState', 'Succeeded')]) - - artifact_sources = self.cmd('lab artifact-source list -g {} --lab-name {}' - .format(rg, LAB_NAME)) + @ResourceGroupPreparer(name_prefix='cliautomation01') + def test_lab_environment_mgmt(self, resource_group): + self.kwargs.update({ + 'env_name': 'docdbenv', + 'arm_template': 'documentdb-webapp', + 'password': 'SecretPassword123', + 'template': TEMPLATE, + 'lab_name': LAB_NAME, + 'env_params': ENV_PARAMETERS + }) + + self.cmd('group deployment create -g {rg} --template-file {template}', checks=[ + self.check('properties.provisioningState', 'Succeeded') + ]) + + artifact_sources = self.cmd('lab artifact-source list -g {rg} --lab-name {lab_name}') \ + .get_output_in_json() + + self.kwargs.update({ + 'artifact_source_name': artifact_sources[0]['name'] + }) # Create environment in the lab - self.cmd('lab environment create -g {} --lab-name {} --name {} ' - '--arm-template {} --artifact-source-name {} --parameters {}' - .format(rg, LAB_NAME, env_name, arm_template, artifact_sources[0]['name'], ENV_PARAMTERS), - checks=[JMESPathCheck('provisioningState', 'Succeeded'), - JMESPathCheck('type', 'Microsoft.DevTestLab/labs/users/environments')]) + self.cmd('lab environment create -g {rg} --lab-name {lab_name} --name {env_name} --arm-template ' + '{arm_template} --artifact-source-name {artifact_source_name} --parameters {env_params}', checks=[ + self.check('provisioningState', 'Succeeded'), + self.check('type', 'Microsoft.DevTestLab/labs/users/environments')]) # Delete environment from the lab - self.cmd('lab environment delete -g {} --lab-name {} --name {}' - .format(rg, LAB_NAME, env_name), checks=[NoneCheck()]) + self.cmd('lab environment delete -g {rg} --lab-name {lab_name} --name {env_name}', checks=[ + self.is_empty() + ]) # Delete the lab - self.cmd('lab delete -g {} --name {}'.format(rg, LAB_NAME), checks=[NoneCheck()]) + self.cmd('lab delete -g {rg} --name {lab_name}', checks=[ + self.is_empty() + ]) diff --git a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/tests/test_validators.py b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/tests/test_validators.py index 72f45fa746f..3ce1b190525 100644 --- a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/tests/test_validators.py +++ b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/tests/test_validators.py @@ -5,8 +5,8 @@ import unittest from knack.util import CLIError -from azure.cli.core.commands.arm import is_valid_resource_id -from azure.cli.command_modules.lab.validators import (_update_artifacts) +from msrestazure.tools import is_valid_resource_id +from azure.cli.command_modules.lab.validators import _update_artifacts class ValidatorsCommandTest(unittest.TestCase): diff --git a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/validators.py b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/validators.py index e4187d50344..a2043351ff0 100644 --- a/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/validators.py +++ b/src/command_modules/azure-cli-lab/azure/cli/command_modules/lab/validators.py @@ -7,7 +7,9 @@ import datetime import dateutil.parser from msrestazure.azure_exceptions import CloudError +from msrestazure.tools import resource_id, is_valid_resource_id from knack.util import CLIError +from knack.log import get_logger from azure.mgmt.devtestlabs.models.gallery_image_reference import GalleryImageReference from azure.mgmt.devtestlabs.models.network_interface_properties import NetworkInterfaceProperties from azure.mgmt.devtestlabs.models.shared_public_ip_address_configuration import \ @@ -16,15 +18,15 @@ from azure.graphrbac import GraphRbacManagementClient from ._client_factory import (get_devtestlabs_management_client) +logger = get_logger(__name__) # Odata filter for name ODATA_NAME_FILTER = "name eq '{}'" -def validate_lab_vm_create(namespace): +def validate_lab_vm_create(cmd, namespace): """ Validates parameters for lab vm create and updates namespace. """ formula = None - collection = [namespace.image, namespace.formula] if not _single(collection): raise CLIError("usage error: [--image name --image-type type | --formula name]") @@ -32,18 +34,18 @@ def validate_lab_vm_create(namespace): raise CLIError("usage error: [--image name --image-type type | --formula name]") if namespace.formula: - formula = _get_formula(namespace) + formula = _get_formula(cmd.cli_ctx, namespace) - _validate_location(namespace) + _validate_location(cmd.cli_ctx, namespace) _validate_expiration_date(namespace) _validate_other_parameters(namespace, formula) - _validate_artifacts(namespace) - _validate_image_argument(namespace, formula) - _validate_network_parameters(namespace, formula) + validate_artifacts(cmd, namespace) + _validate_image_argument(cmd.cli_ctx, namespace, formula) + _validate_network_parameters(cmd.cli_ctx, namespace, formula) validate_authentication_type(namespace, formula) -def validate_lab_vm_list(namespace): +def validate_lab_vm_list(cmd, namespace): """ Validates parameters for lab vm list and updates namespace. """ collection = [namespace.filters, namespace.all, namespace.claimable] if _any(collection) and not _single(collection): @@ -66,18 +68,18 @@ def validate_lab_vm_list(namespace): else: # Find out owner object id if not namespace.object_id: - namespace.filters = "Properties/ownerObjectId eq '{}'".format(_get_owner_object_id()) + namespace.filters = "Properties/ownerObjectId eq '{}'".format(_get_owner_object_id(cmd.cli_ctx)) if namespace.environment: if not is_valid_resource_id(namespace.environment): from azure.cli.core.commands.client_factory import get_subscription_id - namespace.environment = resource_id(subscription=get_subscription_id(), - resource_group=namespace.resource_group, + namespace.environment = resource_id(subscription=get_subscription_id(cmd.cli_ctx), + resource_group=namespace.resource_group_name, namespace='Microsoft.DevTestLab', type='labs', name=namespace.lab_name, child_type_1='users', - child_name_1=_get_owner_object_id(), + child_name_1=_get_owner_object_id(cmd.cli_ctx), child_type_2='environments', child_name_2=namespace.environment) if namespace.filters is None: @@ -91,15 +93,15 @@ def validate_user_name(namespace): namespace.user_name = "@me" -def validate_template_id(namespace): +def validate_template_id(cmd, namespace): from azure.cli.core.commands.client_factory import get_subscription_id if not is_valid_resource_id(namespace.arm_template): if not namespace.artifact_source_name: raise CLIError("--artifact-source-name is required when name is " "provided for --arm-template") - namespace.arm_template = resource_id(subscription=get_subscription_id(), - resource_group=namespace.resource_group, + namespace.arm_template = resource_id(subscription=get_subscription_id(cmd.cli_ctx), + resource_group=namespace.resource_group_name, namespace='Microsoft.DevTestLab', type='labs', name=namespace.lab_name, @@ -110,20 +112,20 @@ def validate_template_id(namespace): def validate_claim_vm(namespace): - if namespace.name is None and namespace.lab_name is None or namespace.resource_group is None: + if namespace.name is None and namespace.lab_name is None or namespace.resource_group_name is None: raise CLIError("usage error: --ids IDs | --lab-name LabName --resource-group ResourceGroup --name VMName" " | --lab-name LabName --resource-group ResourceGroup") -def _get_owner_object_id(): - from azure.cli.core._profile import Profile, CLOUD +def _get_owner_object_id(cli_ctx): + from azure.cli.core._profile import Profile from azure.graphrbac.models import GraphErrorException - profile = Profile() + profile = Profile(cli_ctx) cred, _, tenant_id = profile.get_login_credentials( - resource=CLOUD.endpoints.active_directory_graph_resource_id) + resource=cli_ctx.cloud.endpoints.active_directory_graph_resource_id) graph_client = GraphRbacManagementClient(cred, tenant_id, - base_url=CLOUD.endpoints.active_directory_graph_resource_id) + base_url=cli_ctx.cloud.endpoints.active_directory_graph_resource_id) subscription = profile.get_subscription() try: return _get_current_user_object_id(graph_client) @@ -132,13 +134,13 @@ def _get_owner_object_id(): # pylint: disable=no-member -def _validate_location(namespace): +def _validate_location(cli_ctx, namespace): """ Selects the default location of the lab when location is not provided. """ if namespace.location is None: - lab_operation = get_devtestlabs_management_client(None).labs - lab = lab_operation.get(namespace.resource_group, namespace.lab_name) + lab_operation = get_devtestlabs_management_client(cli_ctx, None).labs + lab = lab_operation.get(namespace.resource_group_name, namespace.lab_name) namespace.location = lab.location @@ -151,9 +153,9 @@ def _validate_expiration_date(namespace): # pylint: disable=no-member -def _validate_network_parameters(namespace, formula=None): +def _validate_network_parameters(cli_ctx, namespace, formula=None): """ Updates namespace for virtual network and subnet parameters """ - vnet_operation = get_devtestlabs_management_client(None).virtual_networks + vnet_operation = get_devtestlabs_management_client(cli_ctx, None).virtual_networks lab_vnet = None if formula and formula.formula_content: @@ -169,7 +171,7 @@ def _validate_network_parameters(namespace, formula=None): # User did not provide vnet and not selected from formula if not namespace.vnet_name: - lab_vnets = list(vnet_operation.list(namespace.resource_group, namespace.lab_name, top=1)) + lab_vnets = list(vnet_operation.list(namespace.resource_group_name, namespace.lab_name, top=1)) if not lab_vnets: err = "Unable to find any virtual network in the '{}' lab.".format(namespace.lab_name) raise CLIError(err) @@ -179,7 +181,7 @@ def _validate_network_parameters(namespace, formula=None): namespace.lab_virtual_network_id = lab_vnet.id # User did provide vnet or has been selected from formula else: - lab_vnet = vnet_operation.get(namespace.resource_group, namespace.lab_name, namespace.vnet_name) + lab_vnet = vnet_operation.get(namespace.resource_group_name, namespace.lab_name, namespace.vnet_name) namespace.lab_virtual_network_id = lab_vnet.id # User did not provide subnet and not selected from formula @@ -236,7 +238,7 @@ def _inbound_rule_from_os(namespace): # pylint: disable=no-member -def _validate_image_argument(namespace, formula=None): +def _validate_image_argument(cli_ctx, namespace, formula=None): """ Update namespace for image based on image or formula """ if formula and formula.formula_content: if formula.formula_content.gallery_image_reference: @@ -255,20 +257,20 @@ def _validate_image_argument(namespace, formula=None): namespace.image_type = 'custom' if namespace.image_type == 'gallery': - _use_gallery_image(namespace) + _use_gallery_image(cli_ctx, namespace) elif namespace.image_type == 'custom': - _use_custom_image(namespace) + _use_custom_image(cli_ctx, namespace) else: raise CLIError("incorrect value for image-type: '{}'. Allowed values: gallery or custom" .format(namespace.image_type)) # pylint: disable=no-member -def _use_gallery_image(namespace): +def _use_gallery_image(cli_ctx, namespace): """ Retrieve gallery image from lab and update namespace """ - gallery_image_operation = get_devtestlabs_management_client(None).gallery_images + gallery_image_operation = get_devtestlabs_management_client(cli_ctx, None).gallery_images odata_filter = ODATA_NAME_FILTER.format(namespace.image) - gallery_images = list(gallery_image_operation.list(namespace.resource_group, + gallery_images = list(gallery_image_operation.list(namespace.resource_group_name, namespace.lab_name, filter=odata_filter)) @@ -290,14 +292,14 @@ def _use_gallery_image(namespace): # pylint: disable=no-member -def _use_custom_image(namespace): +def _use_custom_image(cli_ctx, namespace): """ Retrieve custom image from lab and update namespace """ if is_valid_resource_id(namespace.image): namespace.custom_image_id = namespace.image else: - custom_image_operation = get_devtestlabs_management_client(None).custom_images + custom_image_operation = get_devtestlabs_management_client(cli_ctx, None).custom_images odata_filter = ODATA_NAME_FILTER.format(namespace.image) - custom_images = list(custom_image_operation.list(namespace.resource_group, + custom_images = list(custom_image_operation.list(namespace.resource_group_name, namespace.lab_name, filter=odata_filter)) if not custom_images: @@ -322,11 +324,11 @@ def _use_custom_image(namespace): namespace.os_type = os_type -def _get_formula(namespace): +def _get_formula(cli_ctx, namespace): """ Retrieve formula image from lab """ - formula_operation = get_devtestlabs_management_client(None).formulas + formula_operation = get_devtestlabs_management_client(cli_ctx, None).formulas odata_filter = ODATA_NAME_FILTER.format(namespace.formula) - formula_images = list(formula_operation.list(namespace.resource_group, + formula_images = list(formula_operation.list(namespace.resource_group_name, namespace.lab_name, filter=odata_filter)) if not formula_images: @@ -351,7 +353,7 @@ def _validate_other_parameters(namespace, formula=None): namespace.os_type = formula.os_type -def _validate_artifacts(namespace): +def validate_artifacts(cmd, namespace): if namespace.artifacts: from azure.cli.core.commands.client_factory import get_subscription_id if hasattr(namespace, 'resource_group'): @@ -360,7 +362,7 @@ def _validate_artifacts(namespace): # some SDK methods have parameter name as 'resource_group_name' resource_group = namespace.resource_group_name - lab_resource_id = resource_id(subscription=get_subscription_id(), + lab_resource_id = resource_id(subscription=get_subscription_id(cmd.cli_ctx), resource_group=resource_group, namespace='Microsoft.DevTestLab', type='labs',