diff --git a/requirements.txt b/requirements.txt index 7de5b3becef..76ff9317ff8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,7 +7,7 @@ mock==1.3.0 paramiko==2.0.2 pip==9.0.1 pygments==2.1.3 -pylint==1.5.4 +pylint==1.7.1 pyOpenSSL==16.2.0 pyyaml==3.11 requests==2.9.1 diff --git a/scripts/build.sh b/scripts/build.sh index e1b685504b2..b9d72e67a85 100755 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -16,14 +16,7 @@ python -m azure.cli -h --debug # Ensure tokens are erased from VCR recordings python -m automation.tests.check_vcr_recordings -# PyLint does not yet support Python 3.6 https://github.com/PyCQA/pylint/issues/1241 - -LOCAL_PYTHON_VERSION=$(python -c 'import sys; print("{0}.{1}".format(sys.version_info[0], sys.version_info[1]))') -if [[ "$TRAVIS_PYTHON_VERSION" == "3.6" || "$LOCAL_PYTHON_VERSION" == "3.6" ]]; then - echo 'Skipping check_style since it is not supported in python 3.6' -else - check_style --ci; -fi +check_style --ci; if [ "$CODE_COVERAGE" == "True" ]; then echo "Run tests with code coverage." diff --git a/src/azure-cli-core/azure/cli/core/_config.py b/src/azure-cli-core/azure/cli/core/_config.py index da4dd293126..636e8094c41 100644 --- a/src/azure-cli-core/azure/cli/core/_config.py +++ b/src/azure-cli-core/azure/cli/core/_config.py @@ -22,10 +22,7 @@ def get_config_parser(): import sys python_version = sys.version_info.major - if python_version == 3: - return configparser.ConfigParser() - else: - return configparser.SafeConfigParser() + return configparser.ConfigParser() if python_version == 3 else configparser.SafeConfigParser() class AzConfig(object): diff --git a/src/azure-cli-core/azure/cli/core/_environment.py b/src/azure-cli-core/azure/cli/core/_environment.py index 552a17394ae..228addf0ba9 100644 --- a/src/azure-cli-core/azure/cli/core/_environment.py +++ b/src/azure-cli-core/azure/cli/core/_environment.py @@ -3,11 +3,7 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -import os - def get_config_dir(): - if os.getenv('AZURE_CONFIG_DIR'): - return os.getenv('AZURE_CONFIG_DIR') - else: - return os.path.expanduser(os.path.join('~', '.azure')) + import os + return os.getenv('AZURE_CONFIG_DIR', None) or os.path.expanduser(os.path.join('~', '.azure')) diff --git a/src/azure-cli-core/azure/cli/core/_help.py b/src/azure-cli-core/azure/cli/core/_help.py index a893c96c957..a7b5eb017bd 100644 --- a/src/azure-cli-core/azure/cli/core/_help.py +++ b/src/azure-cli-core/azure/cli/core/_help.py @@ -45,7 +45,7 @@ def show_help(nouns, parser, is_group): help_file.load(parser) - if len(nouns) == 0: + if not nouns: print("\nFor version info, use 'az --version'") help_file.command = '' @@ -80,7 +80,7 @@ def print_detailed_help(help_file): elif help_file.type == 'group': _print_groups(help_file) - if len(help_file.examples) > 0: + if help_file.examples: _print_examples(help_file) @@ -104,7 +104,7 @@ def print_arguments(help_file): _print_indent('') return - if len(help_file.parameters) == 0: + if not help_file.parameters: _print_indent('none', indent) required_tag = ' [Required]' max_name_length = max(len(p.name) + (len(required_tag) if p.required else 0) @@ -207,7 +207,7 @@ def _print_items(items): indent = 1 max_name_length = max(len(c.name) for c in help_file.children) \ - if len(help_file.children) > 0 \ + if help_file.children \ else 0 subgroups = [c for c in help_file.children if isinstance(c, GroupHelpFile)] subcommands = [c for c in help_file.children if c not in subgroups] @@ -275,7 +275,7 @@ class HelpFile(HelpObject): # pylint: disable=too-few-public-methods,too-many-i def __init__(self, delimiters): super(HelpFile, self).__init__() self.delimiters = delimiters - self.name = delimiters.split()[-1] if len(delimiters) > 0 else delimiters + self.name = delimiters.split()[-1] if delimiters else delimiters self.command = delimiters self.type = '' self.short_summary = '' diff --git a/src/azure-cli-core/azure/cli/core/_output.py b/src/azure-cli-core/azure/cli/core/_output.py index e1445b5689c..bdddb0f6043 100644 --- a/src/azure-cli-core/azure/cli/core/_output.py +++ b/src/azure-cli-core/azure/cli/core/_output.py @@ -29,10 +29,10 @@ def _decode_str(output): class ComplexEncoder(json.JSONEncoder): - def default(self, obj): # pylint: disable=method-hidden - if isinstance(obj, bytes) and not isinstance(obj, str): - return obj.decode() - return json.JSONEncoder.default(self, obj) + def default(self, o): # pylint: disable=method-hidden + if isinstance(o, bytes) and not isinstance(o, str): + return o.decode() + return json.JSONEncoder.default(self, o) def format_json(obj): @@ -134,7 +134,7 @@ def __init__(self, should_sort_keys=False): @staticmethod def _capitalize_first_char(x): - return x[0].upper() + x[1:] if x and len(x) > 0 else x + return x[0].upper() + x[1:] if x else x def _auto_table_item(self, item): new_entry = OrderedDict() @@ -160,8 +160,7 @@ def _auto_table(self, result): for item in result: new_result.append(self._auto_table_item(item)) return new_result - else: - return self._auto_table_item(result) + return self._auto_table_item(result) def dump(self, data): table_data = self._auto_table(data) @@ -218,7 +217,7 @@ def _dump_obj(data, stream): @staticmethod def _dump_row(data, stream): separator = '' - if isinstance(data, dict) or isinstance(data, list): + if isinstance(data, (dict, list)): if isinstance(data, OrderedDict): values = data.values() elif isinstance(data, dict): diff --git a/src/azure-cli-core/azure/cli/core/_profile.py b/src/azure-cli-core/azure/cli/core/_profile.py index cea1cbb7c9e..ef6ef84a25e 100644 --- a/src/azure-cli-core/azure/cli/core/_profile.py +++ b/src/azure-cli-core/azure/cli/core/_profile.py @@ -314,9 +314,8 @@ def _retrieve_token(): if user_type == _USER: return self._creds_cache.retrieve_token_for_user(username_or_sp_id, account[_TENANT_ID], resource) - else: - return self._creds_cache.retrieve_token_for_service_principal(username_or_sp_id, - resource) + return self._creds_cache.retrieve_token_for_service_principal(username_or_sp_id, resource) + from azure.cli.core.adal_authentication import AdalAuthentication auth_object = AdalAuthentication(_retrieve_token) @@ -395,9 +394,7 @@ def __init__(self, auth_context_factory, adal_token_cache, arm_client_factory=No def create_arm_client_factory(config): if arm_client_factory: return arm_client_factory(config) - else: - return change_ssl_cert_verification(SubscriptionClient( - config, base_url=CLOUD.endpoints.resource_manager)) + return change_ssl_cert_verification(SubscriptionClient(config, base_url=CLOUD.endpoints.resource_manager)) self._arm_client_factory = create_arm_client_factory self.tenants = [] @@ -635,12 +632,9 @@ def __init__(self, password_arg_value): def acquire_token(self, authentication_context, resource, client_id): if hasattr(self, 'secret'): - return authentication_context.acquire_token_with_client_credentials(resource, - client_id, - self.secret) - else: - return authentication_context.acquire_token_with_client_certificate( - resource, client_id, self.cert_file_string, self.thumbprint) + return authentication_context.acquire_token_with_client_credentials(resource, client_id, self.secret) + return authentication_context.acquire_token_with_client_certificate(resource, client_id, self.cert_file_string, + self.thumbprint) def get_entry_to_persist(self, sp_id, tenant): entry = { diff --git a/src/azure-cli-core/azure/cli/core/_session.py b/src/azure-cli-core/azure/cli/core/_session.py index 3c595aaf980..d348c428133 100644 --- a/src/azure-cli-core/azure/cli/core/_session.py +++ b/src/azure-cli-core/azure/cli/core/_session.py @@ -23,6 +23,7 @@ class Session(collections.MutableMapping): ''' def __init__(self, encoding=None): + super(Session, self).__init__() self.filename = None self.data = {} self._encoding = encoding if encoding else 'utf-8-sig' diff --git a/src/azure-cli-core/azure/cli/core/application.py b/src/azure-cli-core/azure/cli/core/application.py index 3f57ce95bb7..ff8b728dd27 100644 --- a/src/azure-cli-core/azure/cli/core/application.py +++ b/src/azure-cli-core/azure/cli/core/application.py @@ -138,7 +138,7 @@ def execute(self, unexpanded_argv): # pylint: disable=too-many-statements self.parser.load_command_table(command_table) self.raise_event(self.COMMAND_PARSER_LOADED, parser=self.parser) - if len(argv) == 0: + if not argv: enable_autocomplete(self.parser) az_subparser = self.parser.subparsers[tuple()] _help.show_welcome(az_subparser) @@ -273,8 +273,9 @@ def _maybe_load_file(arg): return arg elif ix == 0: return Application._load_file(poss_file) - else: # if @ not at the start it can't be a file - return arg + + # if @ not at the start it can't be a file + return arg @staticmethod def _expand_file_prefix(arg): diff --git a/src/azure-cli-core/azure/cli/core/azlogging.py b/src/azure-cli-core/azure/cli/core/azlogging.py index aad28f9f57e..27fb588ebf4 100644 --- a/src/azure-cli-core/azure/cli/core/azlogging.py +++ b/src/azure-cli-core/azure/cli/core/azlogging.py @@ -151,7 +151,7 @@ def configure_logging(argv): az_logger.setLevel(logging.DEBUG) az_logger.propagate = False - if len(root_logger.handlers) and len(az_logger.handlers): + if root_logger.handlers and az_logger.handlers: # loggers already configured return _init_console_handlers(root_logger, az_logger, log_level_config) diff --git a/src/azure-cli-core/azure/cli/core/commands/__init__.py b/src/azure-cli-core/azure/cli/core/commands/__init__.py index eb2a953d22e..b82896ff5e5 100644 --- a/src/azure-cli-core/azure/cli/core/commands/__init__.py +++ b/src/azure-cli-core/azure/cli/core/commands/__init__.py @@ -167,7 +167,7 @@ def __call__(self, poller): try: message = '{} {}'.format( str(message), - json.loads(client_exception.response.text)['error']['details'][0]['message']) + json.loads(client_exception.response.text)['error']['details'][0]['message']) # pylint: disable=no-member except: # pylint: disable=bare-except pass @@ -195,9 +195,9 @@ def __call__(self, result): elif isinstance(result, ClientRawResponse): # --no-wait returns a ClientRawResponse return None - else: - # --validate returns a 'normal' response - return result + + # --validate returns a 'normal' response + return result class CommandTable(dict): @@ -392,8 +392,7 @@ def get_op_handler(operation): op = getattr(op, part) if isinstance(op, types.FunctionType): return op - else: - return six.get_method_function(op) + return six.get_method_function(op) except (ValueError, AttributeError): raise ValueError("The operation '{}' is invalid.".format(operation)) @@ -443,7 +442,6 @@ def create_command(module_name, name, operation, raise ValueError("Operation must be a string. Got '{}'".format(operation)) def _execute_command(kwargs): - from msrestazure.azure_exceptions import CloudError if confirmation \ and not kwargs.get(CONFIRM_PARAM_NAME) \ and not az_config.getboolean('core', 'disable_confirm_prompt', fallback=False) \ diff --git a/src/azure-cli-core/azure/cli/core/commands/_introspection.py b/src/azure-cli-core/azure/cli/core/commands/_introspection.py index 278bf922c21..84e1d636ab4 100644 --- a/src/azure-cli-core/azure/cli/core/commands/_introspection.py +++ b/src/azure-cli-core/azure/cli/core/commands/_introspection.py @@ -27,7 +27,7 @@ def _option_descriptions(operation): option_descs = {} lines = inspect.getdoc(operation) param_breaks = ["'''", '"""', ':param', ':type', ':return', ':rtype'] - if lines: + if lines: # pylint: disable=too-many-nested-blocks lines = lines.splitlines() index = 0 while index < len(lines): diff --git a/src/azure-cli-core/azure/cli/core/commands/arm.py b/src/azure-cli-core/azure/cli/core/commands/arm.py index e9a3d046fe3..753a4b1ba5f 100644 --- a/src/azure-cli-core/azure/cli/core/commands/arm.py +++ b/src/azure-cli-core/azure/cli/core/commands/arm.py @@ -97,10 +97,7 @@ def __new__(cls, val): def resource_exists(resource_group, name, namespace, type, **_): # pylint: disable=redefined-builtin - '''Checks if the given resource exists. - ''' - from azure.mgmt.resource import ResourceManagementClient - + ''' Checks if the given resource exists. ''' odata_filter = "resourceGroup eq '{}' and name eq '{}'" \ " and resourceType eq '{}/{}'".format(resource_group, name, namespace, type) client = get_mgmt_service_client(ResourceType.MGMT_RESOURCE_RESOURCES).resources @@ -109,10 +106,8 @@ def resource_exists(resource_group, name, namespace, type, **_): # pylint: disa def add_id_parameters(command_table): - def split_action(arguments): class SplitAction(argparse.Action): # pylint: disable=too-few-public-methods - def __call__(self, parser, namespace, values, option_string=None): ''' The SplitAction will take the given ID parameter and spread the parsed parts of the id into the individual backing fields. @@ -120,7 +115,7 @@ def __call__(self, parser, namespace, values, option_string=None): Since the id value is expected to be of type `IterateValue`, all the backing (dest) fields will also be of type `IterateValue` ''' - try: + try: # pylint: disable=too-many-nested-blocks for value in [values] if isinstance(values, str) else values: parts = parse_resource_id(value) for arg in [arg for arg in arguments.values() if arg.id_part]: @@ -132,7 +127,7 @@ def __call__(self, parser, namespace, values, option_string=None): if isinstance(existing_values, str): if not getattr(arg.type, 'configured_default_applied', None): logger.warning( - "Property '%s=%s' being overriden by value '%s' from IDs parameter.", # pylint: disable=line-too-long + "Property '%s=%s' being overriden by value '%s' from IDs parameter.", arg.name, existing_values, parts[arg.id_part] ) existing_values = IterateValue() @@ -503,7 +498,7 @@ def _find_split(): value = [] brackets = False chars = list(expression) - while len(chars) > 0: + while chars: c = chars.pop(0) if c == '=' and not brackets: # keys done the rest is value @@ -519,15 +514,12 @@ def _find_split(): # normal character key += c - key = ''.join(key) # pylint: disable=redefined-variable-type - value = ''.join(value) # pylint: disable=redefined-variable-type - return key, value + return ''.join(key), ''.join(value) equals_count = expression.count('=') if equals_count == 1: return expression.split('=', 1) - else: - return _find_split() + return _find_split() def set_properties(instance, expression): diff --git a/src/azure-cli-core/azure/cli/core/commands/parameters.py b/src/azure-cli-core/azure/cli/core/commands/parameters.py index 6ca0e9960bf..27bf2637c41 100644 --- a/src/azure-cli-core/azure/cli/core/commands/parameters.py +++ b/src/azure-cli-core/azure/cli/core/commands/parameters.py @@ -68,8 +68,7 @@ def get_resources_in_resource_group(resource_group_name, resource_type=None): filter_str = "resourceType eq '{}'".format(resource_type) if resource_type else None if supported_api_version(ResourceType.MGMT_RESOURCE_RESOURCES, max_api='2016-09-01'): return list(rcf.resource_groups.list_resources(resource_group_name, filter=filter_str)) - else: - return list(rcf.resources.list_by_resource_group(resource_group_name, filter=filter_str)) + return list(rcf.resources.list_by_resource_group(resource_group_name, filter=filter_str)) def get_resources_in_subscription(resource_type=None): @@ -84,8 +83,7 @@ def completer(prefix, action, parsed_args, **kwargs): # pylint: disable=unused- if getattr(parsed_args, 'resource_group_name', None): rg = parsed_args.resource_group_name return [r.name for r in get_resources_in_resource_group(rg, resource_type=resource_type)] - else: - return [r.name for r in get_resources_in_subscription(resource_type=resource_type)] + return [r.name for r in get_resources_in_subscription(resource_type=resource_type)] return completer diff --git a/src/azure-cli-core/azure/cli/core/commands/validators.py b/src/azure-cli-core/azure/cli/core/commands/validators.py index 756a378ad50..5d09728e25e 100644 --- a/src/azure-cli-core/azure/cli/core/commands/validators.py +++ b/src/azure-cli-core/azure/cli/core/commands/validators.py @@ -56,9 +56,9 @@ def validate_file_or_dict(string): if os.path.exists(string): from azure.cli.core.util import get_file_json return get_file_json(string) - else: - from azure.cli.core.util import shell_safe_json_parse - return shell_safe_json_parse(string) + + from azure.cli.core.util import shell_safe_json_parse + return shell_safe_json_parse(string) SPECIFIED_SENTINEL = '__SET__' diff --git a/src/azure-cli-core/azure/cli/core/extensions/query.py b/src/azure-cli-core/azure/cli/core/extensions/query.py index 41852f8afaf..273cca558f8 100644 --- a/src/azure-cli-core/azure/cli/core/extensions/query.py +++ b/src/azure-cli-core/azure/cli/core/extensions/query.py @@ -38,7 +38,7 @@ def handle_query_parameter(**kwargs): del args._jmespath_query if query_expression: def filter_output(**kwargs): - from jmespath import search, Options + from jmespath import Options kwargs['event_data']['result'] = query_expression.search( kwargs['event_data']['result'], Options(collections.OrderedDict)) application.remove(application.FILTER_RESULT, filter_output) diff --git a/src/azure-cli-core/azure/cli/core/help_files.py b/src/azure-cli-core/azure/cli/core/help_files.py index c0a1931c17f..4b0fadb4a57 100644 --- a/src/azure-cli-core/azure/cli/core/help_files.py +++ b/src/azure-cli-core/azure/cli/core/help_files.py @@ -12,5 +12,4 @@ def _load_help_file(delimiters): import yaml if delimiters in helps: return yaml.load(helps[delimiters]) - else: - return None + return None diff --git a/src/azure-cli-core/azure/cli/core/prompting.py b/src/azure-cli-core/azure/cli/core/prompting.py index 8a7922de862..db77527c89f 100644 --- a/src/azure-cli-core/azure/cli/core/prompting.py +++ b/src/azure-cli-core/azure/cli/core/prompting.py @@ -108,7 +108,7 @@ def prompt_choice_list(msg, a_list, default=1, help_string=None): if val == '?' and help_string is not None: print(help_string) continue - if len(val) == 0: + if not val: val = '{}'.format(default) try: ans = int(val) diff --git a/src/azure-cli-core/azure/cli/core/sdk/util.py b/src/azure-cli-core/azure/cli/core/sdk/util.py index 305bbb64e32..e709f86a40b 100644 --- a/src/azure-cli-core/azure/cli/core/sdk/util.py +++ b/src/azure-cli-core/azure/cli/core/sdk/util.py @@ -12,10 +12,8 @@ def create_service_adapter(service_model, service_class=None): def _service_adapter(method_name): - if service_class is not None: - return '{}#{}.{}'.format(service_model, service_class, method_name) - else: - return '{}#{}'.format(service_model, method_name) + return '{}#{}.{}'.format(service_model, service_class, method_name) if service_class else \ + '{}#{}'.format(service_model, method_name) return _service_adapter diff --git a/src/azure-cli-core/azure/cli/core/telemetry.py b/src/azure-cli-core/azure/cli/core/telemetry.py index f5ae41f25b9..63c1fd3f90c 100644 --- a/src/azure-cli-core/azure/cli/core/telemetry.py +++ b/src/azure-cli-core/azure/cli/core/telemetry.py @@ -29,8 +29,7 @@ def _user_agrees_to_telemetry(func): def _wrapper(*args, **kwargs): if not _get_azure_cli_config().getboolean('core', 'collect_telemetry', fallback=True): return - else: - return func(*args, **kwargs) + return func(*args, **kwargs) return _wrapper @@ -334,8 +333,7 @@ def _get_shell_type(): return 'ksh' elif 'WINDIR' in os.environ: return 'cmd' - else: - return _remove_cmd_chars(_remove_symbols(os.environ.get('SHELL'))) + return _remove_cmd_chars(_remove_symbols(os.environ.get('SHELL'))) @decorators.suppress_all_exceptions(fallback_return='') diff --git a/src/azure-cli-core/azure/cli/core/util.py b/src/azure-cli-core/azure/cli/core/util.py index 6a3b79b97b5..ae36ed8e1f4 100644 --- a/src/azure-cli-core/azure/cli/core/util.py +++ b/src/azure-cli-core/azure/cli/core/util.py @@ -32,14 +32,14 @@ class CLIError(Exception): def handle_exception(ex): # For error code, follow guidelines at https://docs.python.org/2/library/sys.html#sys.exit, from msrestazure.azure_exceptions import CloudError - if isinstance(ex, CLIError) or isinstance(ex, CloudError): + if isinstance(ex, (CLIError, CloudError)): logger.error(ex.args[0]) return ex.args[1] if len(ex.args) >= 2 else 1 elif isinstance(ex, KeyboardInterrupt): return 1 - else: - logger.exception(ex) - return 1 + + logger.exception(ex) + return 1 def empty_on_404(ex): @@ -93,6 +93,7 @@ def show_version_info_exit(out_file): def get_json_object(json_string): """ Loads a JSON string as an object and converts all keys to snake case """ + def _convert_to_snake_case(item): if isinstance(item, dict): new_item = {} @@ -101,8 +102,8 @@ def _convert_to_snake_case(item): return new_item if isinstance(item, list): return [_convert_to_snake_case(x) for x in item] - else: - return item + return item + return _convert_to_snake_case(shell_safe_json_parse(json_string)) @@ -166,8 +167,7 @@ def todict(obj): # pylint: disable=too-many-return-statements return dict([(to_camel_case(k), todict(v)) for k, v in obj.__dict__.items() if not callable(v) and not k.startswith('_')]) - else: - return obj + return obj KEYS_CAMELCASE_PATTERN = re.compile('(?!^)_([a-zA-Z])') @@ -190,10 +190,7 @@ def b64encode(s): :rtype: str """ encoded = base64.b64encode(six.b(s)) - if encoded is str: - return encoded - else: - return encoded.decode('latin-1') + return encoded if encoded is str else encoded.decode('latin-1') def b64_to_hex(s): diff --git a/src/azure-cli-testsdk/azure/cli/testsdk/base.py b/src/azure-cli-testsdk/azure/cli/testsdk/base.py index 54a1bd258b7..69c4757b74a 100644 --- a/src/azure-cli-testsdk/azure/cli/testsdk/base.py +++ b/src/azure-cli-testsdk/azure/cli/testsdk/base.py @@ -160,8 +160,8 @@ def create_random_name(self, prefix, length): name = create_random_name(prefix, length) self.name_replacer.register_name_pair(name, moniker) return name - else: - return moniker + + return moniker def _process_request_recording(self, request): if self.in_recording: diff --git a/src/azure-cli-testsdk/azure/cli/testsdk/preparers.py b/src/azure-cli-testsdk/azure/cli/testsdk/preparers.py index 7255349c6f4..bddac35ca68 100644 --- a/src/azure-cli-testsdk/azure/cli/testsdk/preparers.py +++ b/src/azure-cli-testsdk/azure/cli/testsdk/preparers.py @@ -48,7 +48,7 @@ def _preparer_wrapper(test_class_instance, **kwargs): args, _, kw, _ = inspect.getargspec(fn) # pylint: disable=deprecated-method if kw is None: args = set(args) - for key in [k for k in kwargs.keys() if k not in args]: + for key in [k for k in kwargs if k not in args]: del kwargs[key] fn(test_class_instance, **kwargs) @@ -128,10 +128,10 @@ def create_resource(self, name, **kwargs): if self.dev_setting_name: return {self.parameter_name: self.dev_setting_name, self.parameter_name_for_location: self.dev_setting_location} - else: - template = 'az group create --location {} --name {} --tag use=az-test' - execute(template.format(self.location, name)) - return {self.parameter_name: name, self.parameter_name_for_location: self.location} + + template = 'az group create --location {} --name {} --tag use=az-test' + execute(template.format(self.location, name)) + return {self.parameter_name: name, self.parameter_name_for_location: self.location} def remove_resource(self, name, **kwargs): if not self.dev_setting_name: @@ -203,8 +203,8 @@ def create_resource(self, name, **kwargs): template = 'az keyvault create -n {} -g {} -l {} --sku {}' execute(template.format(name, group, self.location, self.sku)) return {self.parameter_name: name} - else: - return {self.parameter_name: self.dev_setting_name} + + return {self.parameter_name: self.dev_setting_name} def remove_resource(self, name, **kwargs): if not self.skip_delete and not self.dev_setting_name: @@ -241,9 +241,9 @@ def create_resource(self, name, **kwargs): .format(name, ' --skip-assignment' if self.skip_assignment else '') self.result = execute(command).get_output_in_json() return {self.parameter_name: name, self.parameter_password: self.result['password']} - else: - return {self.parameter_name: self.dev_setting_sp_name, - self.parameter_password: self.dev_setting_sp_password} + + return {self.parameter_name: self.dev_setting_sp_name, + self.parameter_password: self.dev_setting_sp_password} def remove_resource(self, name, **kwargs): if not self.dev_setting_sp_name: diff --git a/src/azure-cli-testsdk/azure/cli/testsdk/vcr_test_base.py b/src/azure-cli-testsdk/azure/cli/testsdk/vcr_test_base.py index fd23ae3c895..741c8c13314 100644 --- a/src/azure-cli-testsdk/azure/cli/testsdk/vcr_test_base.py +++ b/src/azure-cli-testsdk/azure/cli/testsdk/vcr_test_base.py @@ -29,7 +29,6 @@ import vcr import jmespath -from six import StringIO # TODO Should not depend on azure.cli.main package here. # Will be ok if this test file is not part of azure.cli.core.utils @@ -414,8 +413,9 @@ def _post_recording_scrub(self): # COMMAND METHODS - def cmd(self, command, checks=None, allowed_exceptions=None, - debug=False): # pylint: disable=no-self-use + def cmd(self, command, checks=None, allowed_exceptions=None, debug=False): # pylint: disable=no-self-use + from six import StringIO + allowed_exceptions = allowed_exceptions or [] if not isinstance(allowed_exceptions, list): allowed_exceptions = [allowed_exceptions] diff --git a/src/azure-cli/azure/cli/main.py b/src/azure-cli/azure/cli/main.py index cdffa1cca44..31482d6a86d 100644 --- a/src/azure-cli/azure/cli/main.py +++ b/src/azure-cli/azure/cli/main.py @@ -20,7 +20,7 @@ def main(args, file=sys.stdout): # pylint: disable=redefined-builtin azlogging.configure_logging(args) logger.debug('Command arguments %s', args) - if len(args) > 0 and (args[0] == '--version' or args[0] == '-v'): + if args and (args[0] == '--version' or args[0] == '-v'): show_version_info_exit(file) azure_folder = get_config_dir() diff --git a/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/__init__.py b/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/__init__.py index 60a71e59b85..ff504cb87f6 100644 --- a/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/__init__.py +++ b/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/__init__.py @@ -7,8 +7,8 @@ def load_params(_): - import azure.cli.command_modules.acr._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.acr._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.acr.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.acr.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/_utils.py b/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/_utils.py index f7d26b5381d..9c145edcd60 100644 --- a/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/_utils.py +++ b/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/_utils.py @@ -27,7 +27,7 @@ def _arm_get_resource_by_name(resource_name, resource_type): result = get_resources_in_subscription(resource_type) elements = [item for item in result if item.name.lower() == resource_name.lower()] - if len(elements) == 0: + if not elements: raise CLIError( 'No resource with type {} can be found with name: {}'.format( resource_type, resource_name)) diff --git a/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/_validators.py b/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/_validators.py index 5abc1a5aeea..4ef707aaf42 100644 --- a/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/_validators.py +++ b/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/_validators.py @@ -4,10 +4,9 @@ # -------------------------------------------------------------------------------------------- from azure.cli.core.util import CLIError - +import azure.cli.core.azlogging as azlogging from ._factory import get_acr_service_client -import azure.cli.core.azlogging as azlogging logger = azlogging.get_az_logger(__name__) diff --git a/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/credential.py b/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/credential.py index 38912b89d43..30555b2c342 100644 --- a/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/credential.py +++ b/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/credential.py @@ -4,11 +4,11 @@ # -------------------------------------------------------------------------------------------- from azure.cli.core.util import CLIError +import azure.cli.core.azlogging as azlogging from ._factory import get_acr_service_client from ._utils import get_registry_by_name -import azure.cli.core.azlogging as azlogging logger = azlogging.get_az_logger(__name__) diff --git a/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/custom.py b/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/custom.py index 95e843665fa..48fcb49d9eb 100644 --- a/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/custom.py +++ b/src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/custom.py @@ -4,6 +4,7 @@ # -------------------------------------------------------------------------------------------- from azure.cli.core.commands import LongRunningOperation +import azure.cli.core.azlogging as azlogging from azure.mgmt.containerregistry.models import ( RegistryUpdateParameters, @@ -20,7 +21,6 @@ get_location_from_resource_group ) -import azure.cli.core.azlogging as azlogging logger = azlogging.get_az_logger(__name__) @@ -42,8 +42,8 @@ def acr_list(resource_group_name=None): if resource_group_name: return client.list_by_resource_group(resource_group_name) - else: - return client.list() + + return client.list() def acr_create(registry_name, diff --git a/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/__init__.py b/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/__init__.py index 2061f6f583d..1273263a3fe 100644 --- a/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/__init__.py +++ b/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/__init__.py @@ -8,8 +8,8 @@ def load_params(_): - import azure.cli.command_modules.acs._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.acs._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.acs.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.acs.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/acs_client.py b/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/acs_client.py index 3738e576088..0bc15f1dad8 100644 --- a/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/acs_client.py +++ b/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/acs_client.py @@ -128,8 +128,8 @@ def run(self, command, background=False): t.daemon = True t.start() return - else: - return self._run_cmd(command) + + return self._run_cmd(command) def _run_cmd(self, command): """ diff --git a/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/commands.py b/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/commands.py index 0421a4eeb79..799af952495 100644 --- a/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/commands.py +++ b/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/commands.py @@ -6,9 +6,9 @@ # pylint: disable=line-too-long from azure.cli.core.commands import cli_command -from ._client_factory import _acs_client_factory from azure.cli.core.util import empty_on_404 from azure.cli.core.commands.arm import cli_generic_wait_command +from ._client_factory import _acs_client_factory cli_command(__name__, 'acs show', 'azure.mgmt.compute.containerservice.operations.container_services_operations#ContainerServicesOperations.get', _acs_client_factory, exception_handler=empty_on_404) diff --git a/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/custom.py b/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/custom.py index e7cb0d1ebb3..5bbc0de0df9 100644 --- a/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/custom.py +++ b/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/custom.py @@ -241,8 +241,8 @@ def acs_install_cli(resource_group, name, install_location=None, client_version= def _ssl_context(): if sys.version_info < (3, 4): return ssl.SSLContext(ssl.PROTOCOL_TLSv1) - else: - return ssl.create_default_context() + + return ssl.create_default_context() def _urlretrieve(url, filename): @@ -541,7 +541,7 @@ def _create_kubernetes(resource_group_name, deployment_name, dns_name_prefix, na windows_profile = None os_type = 'Linux' if windows: - if len(admin_password) == 0: + if not admin_password: raise CLIError('--admin-password is required.') if len(admin_password) < 6: raise CLIError('--admin-password must be at least 6 characters') @@ -911,7 +911,7 @@ def _build_application_creds(password=None, key_value=None, key_type=None, if not end_date: end_date = start_date + relativedelta(years=1) elif isinstance(end_date, str): - end_date = dateutil.parser.parse(end_date) # pylint: disable=redefined-variable-type + end_date = dateutil.parser.parse(end_date) key_type = key_type or 'AsymmetricX509Cert' key_usage = key_usage or 'Verify' @@ -921,8 +921,7 @@ def _build_application_creds(password=None, key_value=None, key_type=None, if password: password_creds = [PasswordCredential(start_date, end_date, str(uuid.uuid4()), password)] elif key_value: - key_creds = [KeyCredential(start_date, end_date, key_value, str(uuid.uuid4()), - key_usage, key_type)] + key_creds = [KeyCredential(start_date, end_date, key_value, str(uuid.uuid4()), key_usage, key_type)] return (password_creds, key_creds) diff --git a/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/proxy.py b/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/proxy.py index 9d75f9c2cae..dd90a8f0c91 100644 --- a/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/proxy.py +++ b/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/proxy.py @@ -68,9 +68,6 @@ def disable_http_proxy(self): class LinuxProxy(Proxy): - def __init__(self): - super(LinuxProxy, self).__init__() - def set_http_proxy(self, host, port): """ Sets the HTTP proxy on Linux @@ -89,9 +86,6 @@ def disable_http_proxy(self): class MacProxy(Proxy): - def __init__(self): - super(MacProxy, self).__init__() - def set_http_proxy(self, host, port): """ Sets the HTTP proxy diff --git a/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/win_proxy.py b/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/win_proxy.py index 2b2bec5a65a..6323b023eec 100644 --- a/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/win_proxy.py +++ b/src/command_modules/azure-cli-acs/azure/cli/command_modules/acs/win_proxy.py @@ -21,9 +21,6 @@ class WinProxy(Proxy): INTERNET_PER_CONN_PROXY_BYPASS = 3 INTERNET_PER_CONN_FLAGS = 1 - def __init__(self): - super(WinProxy, self).__init__() - def set_http_proxy(self, host, port): """ Sets the HTTP proxy on Windows diff --git a/src/command_modules/azure-cli-appservice/azure/cli/command_modules/appservice/__init__.py b/src/command_modules/azure-cli-appservice/azure/cli/command_modules/appservice/__init__.py index 23352b91838..405adc49ed3 100644 --- a/src/command_modules/azure-cli-appservice/azure/cli/command_modules/appservice/__init__.py +++ b/src/command_modules/azure-cli-appservice/azure/cli/command_modules/appservice/__init__.py @@ -8,8 +8,8 @@ def load_params(_): - import azure.cli.command_modules.appservice._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.appservice._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.appservice.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.appservice.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-appservice/azure/cli/command_modules/appservice/_params.py b/src/command_modules/azure-cli-appservice/azure/cli/command_modules/appservice/_params.py index 2f98a5e6713..8bfee5da3ad 100644 --- a/src/command_modules/azure-cli-appservice/azure/cli/command_modules/appservice/_params.py +++ b/src/command_modules/azure-cli-appservice/azure/cli/command_modules/appservice/_params.py @@ -22,9 +22,9 @@ def _generic_site_operation(resource_group_name, name, operation_name, slot=None if slot is None: return (m(resource_group_name, name) if extra_parameter is None else m(resource_group_name, name, extra_parameter)) - else: - return (m(resource_group_name, name, slot) - if extra_parameter is None else m(resource_group_name, name, extra_parameter, slot)) + + return (m(resource_group_name, name, slot) + if extra_parameter is None else m(resource_group_name, name, extra_parameter, slot)) def get_hostname_completion_list(prefix, action, parsed_args, **kwargs): # pylint: disable=unused-argument diff --git a/src/command_modules/azure-cli-appservice/azure/cli/command_modules/appservice/custom.py b/src/command_modules/azure-cli-appservice/azure/cli/command_modules/appservice/custom.py index 48bb960be0f..5563a9a24e3 100644 --- a/src/command_modules/azure-cli-appservice/azure/cli/command_modules/appservice/custom.py +++ b/src/command_modules/azure-cli-appservice/azure/cli/command_modules/appservice/custom.py @@ -119,9 +119,9 @@ def list_runtimes(linux=False): 'check out https://aka.ms/linux-stacks') return ['node|6.4', 'node|4.5', 'node|6.2', 'node|6.6', 'node|6.9', 'php|5.6', 'php|7.0', 'dotnetcore|1.0', 'dotnetcore|1.1', 'ruby|2.3'] - else: - runtime_helper = _StackRuntimeHelper(client) - return [s['displayName'] for s in runtime_helper.stacks] + + runtime_helper = _StackRuntimeHelper(client) + return [s['displayName'] for s in runtime_helper.stacks] def _rename_server_farm_props(webapp): @@ -346,20 +346,18 @@ def add_hostname(resource_group_name, webapp_name, hostname, slot=None): binding = HostNameBinding(webapp.location, host_name_binding_name=hostname, site_name=webapp.name) if slot is None: - return client.web_apps.create_or_update_host_name_binding( - resource_group_name, webapp.name, hostname, binding) - else: - return client.web_apps.create_or_update_host_name_binding_slot( - resource_group_name, webapp.name, hostname, binding, slot) + return client.web_apps.create_or_update_host_name_binding(resource_group_name, webapp.name, hostname, binding) + + return client.web_apps.create_or_update_host_name_binding_slot(resource_group_name, webapp.name, hostname, binding, + slot) def delete_hostname(resource_group_name, webapp_name, hostname, slot=None): client = web_client_factory() if slot is None: return client.web_apps.delete_host_name_binding(resource_group_name, webapp_name, hostname) - else: - return client.web_apps.delete_host_name_binding_slot(resource_group_name, - webapp_name, slot, hostname) + + return client.web_apps.delete_host_name_binding_slot(resource_group_name, webapp_name, slot, hostname) def list_hostnames(resource_group_name, webapp_name, slot=None): @@ -380,9 +378,8 @@ def get_external_ip(resource_group_name, webapp_name): if address.internal_ip_address: ip_address = address.internal_ip_address else: - vip = next((s for s in webapp_name.host_name_ssl_states - if s.ssl_state == SslState.ip_based_enabled), None) - ip_address = (vip and vip.virtual_ip) or address.service_ip_address + vip = next((s for s in webapp_name.host_name_ssl_states if s.ssl_state == SslState.ip_based_enabled), None) + ip_address = vip.virtual_ip if vip else address.service_ip_address else: ip_address = _resolve_hostname_through_dns(webapp_name.default_host_name) @@ -598,8 +595,8 @@ def create_backup(resource_group_name, webapp_name, storage_account_url, storage_account_url=storage_account_url, databases=db_setting) if slot: return client.web_apps.backup_slot(resource_group_name, webapp_name, backup_request, slot) - else: - return client.web_apps.backup(resource_group_name, webapp_name, backup_request) + + return client.web_apps.backup(resource_group_name, webapp_name, backup_request) def update_backup_schedule(resource_group_name, webapp_name, storage_account_url=None, @@ -653,11 +650,9 @@ def update_backup_schedule(resource_group_name, webapp_name, storage_account_url backup_request = BackupRequest(location, backup_schedule=backup_schedule, enabled=True, storage_account_url=storage_account_url, databases=db_setting) if slot: - return client.web_apps.update_backup_configuration_slot(resource_group_name, webapp_name, - backup_request, slot) - else: - return client.web_apps.update_backup_configuration(resource_group_name, webapp_name, - backup_request) + return client.web_apps.update_backup_configuration_slot(resource_group_name, webapp_name, backup_request, slot) + + return client.web_apps.update_backup_configuration(resource_group_name, webapp_name, backup_request) def restore_backup(resource_group_name, webapp_name, storage_account_url, backup_name, @@ -675,8 +670,8 @@ def restore_backup(resource_group_name, webapp_name, storage_account_url, backup ignore_conflicting_host_names=ignore_hostname_conflict) if slot: return client.web_apps.restore(resource_group_name, webapp_name, 0, restore_request, slot) - else: - return client.web_apps.restore(resource_group_name, webapp_name, 0, restore_request) + + return client.web_apps.restore(resource_group_name, webapp_name, 0, restore_request) def _create_db_setting(db_name, db_type, db_connection_string): @@ -691,7 +686,6 @@ def _parse_frequency(frequency): if unit_part == 'd': frequency_unit = FrequencyUnit.day elif unit_part == 'h': - # pylint: disable=redefined-variable-type frequency_unit = FrequencyUnit.hour else: raise CLIError('Frequency must end with d or h for "day" or "hour"') @@ -713,8 +707,7 @@ def _normalize_sku(sku): return 'F1' elif sku == 'SHARED': return 'D1' - else: - return sku + return sku def _get_sku_name(tier): @@ -783,7 +776,6 @@ def set_deployment_user(user_name, password=None): def list_publish_profiles(resource_group_name, name, slot=None): - from azure.mgmt.web.models import PublishingProfileFormat import xmltodict content = _generic_site_operation(resource_group_name, name, @@ -1049,15 +1041,15 @@ def _update_ssl_binding(resource_group_name, name, certificate_thumbprint, ssl_t return _update_host_name_ssl_state(resource_group_name, name, webapp.location, webapp_cert.host_names[0], ssl_type, certificate_thumbprint, slot) - else: - query_result = list_hostnames(resource_group_name, name, slot) - hostnames_in_webapp = [x.name.split('/')[-1] for x in query_result] - to_update = _match_host_names_from_cert(webapp_cert.host_names, hostnames_in_webapp) - for h in to_update: - _update_host_name_ssl_state(resource_group_name, name, webapp.location, - h, ssl_type, certificate_thumbprint, slot) - - return show_webapp(resource_group_name, name, slot) + + query_result = list_hostnames(resource_group_name, name, slot) + hostnames_in_webapp = [x.name.split('/')[-1] for x in query_result] + to_update = _match_host_names_from_cert(webapp_cert.host_names, hostnames_in_webapp) + for h in to_update: + _update_host_name_ssl_state(resource_group_name, name, webapp.location, + h, ssl_type, certificate_thumbprint, slot) + + return show_webapp(resource_group_name, name, slot) raise CLIError("Certificate for thumbprint '{}' not found.".format(certificate_thumbprint)) diff --git a/src/command_modules/azure-cli-batch/azure/cli/command_modules/batch/__init__.py b/src/command_modules/azure-cli-batch/azure/cli/command_modules/batch/__init__.py index ee9280abebb..fa2e79f7ed5 100644 --- a/src/command_modules/azure-cli-batch/azure/cli/command_modules/batch/__init__.py +++ b/src/command_modules/azure-cli-batch/azure/cli/command_modules/batch/__init__.py @@ -7,7 +7,7 @@ def load_params(_): - import azure.cli.command_modules.batch._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.batch._params # pylint: disable=redefined-outer-name, unused-variable try: import azure.cli.command_modules.batch_extensions._params except ImportError: @@ -15,7 +15,7 @@ def load_params(_): def load_commands(): - import azure.cli.command_modules.batch.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.batch.commands # pylint: disable=redefined-outer-name, unused-variable try: import azure.cli.command_modules.batch_extensions.commands except ImportError: diff --git a/src/command_modules/azure-cli-batch/azure/cli/command_modules/batch/_command_type.py b/src/command_modules/azure-cli-batch/azure/cli/command_modules/batch/_command_type.py index 14300150421..963a6269b4b 100644 --- a/src/command_modules/azure-cli-batch/azure/cli/command_modules/batch/_command_type.py +++ b/src/command_modules/azure-cli-batch/azure/cli/command_modules/batch/_command_type.py @@ -212,7 +212,7 @@ def filter_group(group): return group group_path = path.split('.') - group_path = list(map(filter_group, group_path)) # pylint: disable=bad-builtin + group_path = list(map(filter_group, group_path)) title = ': '.join(group_path) for group in group_path: title = title.replace(group, " ".join([n.title() for n in group.split('_')]), 1) @@ -570,8 +570,8 @@ def _execute_command(kwargs): # Otherwise handle based on return type of results elif isinstance(result, Paged): return list(result) - else: - return result + + return result except BatchErrorException as ex: try: message = ex.error.message.value diff --git a/src/command_modules/azure-cli-batch/azure/cli/command_modules/batch/_validators.py b/src/command_modules/azure-cli-batch/azure/cli/command_modules/batch/_validators.py index ca640ee66ad..a8275eb796f 100644 --- a/src/command_modules/azure-cli-batch/azure/cli/command_modules/batch/_validators.py +++ b/src/command_modules/azure-cli-batch/azure/cli/command_modules/batch/_validators.py @@ -129,7 +129,6 @@ def validate_required_parameter(ns, parser): def storage_account_id(namespace): """Validate storage account name""" - from azure.mgmt.storage import StorageManagementClient from azure.cli.core.profiles import ResourceType from azure.cli.core.commands.client_factory import get_mgmt_service_client diff --git a/src/command_modules/azure-cli-batch/azure/cli/command_modules/batch/custom.py b/src/command_modules/azure-cli-batch/azure/cli/command_modules/batch/custom.py index a2e60a740a1..7c6e9f8c710 100644 --- a/src/command_modules/azure-cli-batch/azure/cli/command_modules/batch/custom.py +++ b/src/command_modules/azure-cli-batch/azure/cli/command_modules/batch/custom.py @@ -76,7 +76,6 @@ def update_account(client, resource_group_name, account_name, def login_account(client, resource_group_name, account_name, shared_key_auth=False): from azure.cli.core._config import az_config, set_global_config - from azure.cli.core._profile import Profile account = client.get(resource_group_name=resource_group_name, account_name=account_name) @@ -218,16 +217,16 @@ def action(): if_modified_since=if_modified_since, if_unmodified_since=if_unmodified_since) return client.stop_resize(pool_id, pool_stop_resize_options=stop_resize_option) - else: - param = PoolResizeParameter(target_dedicated_nodes=target_dedicated_nodes, - target_low_priority_nodes=target_low_priority_nodes, - resize_timeout=resize_timeout, - node_deallocation_option=node_deallocation_option) - resize_option = PoolResizeOptions(if_match=if_match, - if_none_match=if_none_match, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since) - return client.resize(pool_id, param, pool_resize_options=resize_option) + + param = PoolResizeParameter(target_dedicated_nodes=target_dedicated_nodes, + target_low_priority_nodes=target_low_priority_nodes, + resize_timeout=resize_timeout, + node_deallocation_option=node_deallocation_option) + resize_option = PoolResizeOptions(if_match=if_match, + if_none_match=if_none_match, + if_modified_since=if_modified_since, + if_unmodified_since=if_unmodified_since) + return client.resize(pool_id, param, pool_resize_options=resize_option) return _handle_batch_exception(action) @@ -288,11 +287,11 @@ def action(): expand=expand) return list(client.list_from_job_schedule(job_schedule_id=job_schedule_id, job_list_from_job_schedule_options=option1)) - else: - option2 = JobListOptions(filter=filter, - select=select, - expand=expand) - return list(client.list(job_list_options=option2)) + + option2 = JobListOptions(filter=filter, + select=select, + expand=expand) + return list(client.list(job_list_options=option2)) return _handle_batch_exception(action) @@ -307,9 +306,9 @@ def action(): if task is not None: client.add(job_id=job_id, task=task) return client.get(job_id=job_id, task_id=task.id) - else: - result = client.add_collection(job_id=job_id, value=tasks) - return result.value + + result = client.add_collection(job_id=job_id, value=tasks) + return result.value task = None if json_file: diff --git a/src/command_modules/azure-cli-cdn/azure/cli/command_modules/cdn/__init__.py b/src/command_modules/azure-cli-cdn/azure/cli/command_modules/cdn/__init__.py index 7a291baa610..9124f21eaeb 100644 --- a/src/command_modules/azure-cli-cdn/azure/cli/command_modules/cdn/__init__.py +++ b/src/command_modules/azure-cli-cdn/azure/cli/command_modules/cdn/__init__.py @@ -7,10 +7,8 @@ def load_params(_): - # pylint: disable=redefined-outer-name - import azure.cli.command_modules.cdn._params + import azure.cli.command_modules.cdn._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - # pylint: disable=redefined-outer-name - import azure.cli.command_modules.cdn.commands + import azure.cli.command_modules.cdn.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-cloud/azure/cli/command_modules/cloud/__init__.py b/src/command_modules/azure-cli-cloud/azure/cli/command_modules/cloud/__init__.py index 33018256ffe..a9c9a5c5671 100644 --- a/src/command_modules/azure-cli-cloud/azure/cli/command_modules/cloud/__init__.py +++ b/src/command_modules/azure-cli-cloud/azure/cli/command_modules/cloud/__init__.py @@ -7,8 +7,8 @@ def load_params(_): - import azure.cli.command_modules.cloud._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.cloud._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.cloud.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.cloud.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-cognitiveservices/azure/cli/command_modules/cognitiveservices/__init__.py b/src/command_modules/azure-cli-cognitiveservices/azure/cli/command_modules/cognitiveservices/__init__.py index 6c8efe8cb7d..634544b4b21 100644 --- a/src/command_modules/azure-cli-cognitiveservices/azure/cli/command_modules/cognitiveservices/__init__.py +++ b/src/command_modules/azure-cli-cognitiveservices/azure/cli/command_modules/cognitiveservices/__init__.py @@ -6,8 +6,8 @@ def load_params(_): - import azure.cli.command_modules.cognitiveservices._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.cognitiveservices._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.cognitiveservices.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.cognitiveservices.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-cognitiveservices/azure/cli/command_modules/cognitiveservices/custom.py b/src/command_modules/azure-cli-cognitiveservices/azure/cli/command_modules/cognitiveservices/custom.py index 6ac59a4743f..62adf0b0cc7 100644 --- a/src/command_modules/azure-cli-cognitiveservices/azure/cli/command_modules/cognitiveservices/custom.py +++ b/src/command_modules/azure-cli-cognitiveservices/azure/cli/command_modules/cognitiveservices/custom.py @@ -13,8 +13,7 @@ def listresources(client, resource_group_name=None): if resource_group_name: return client.list_by_resource_group(resource_group_name) - else: - return client.list() + return client.list() def create( diff --git a/src/command_modules/azure-cli-component/azure/cli/command_modules/component/__init__.py b/src/command_modules/azure-cli-component/azure/cli/command_modules/component/__init__.py index b2a8b0b6630..9017dfb1ebc 100644 --- a/src/command_modules/azure-cli-component/azure/cli/command_modules/component/__init__.py +++ b/src/command_modules/azure-cli-component/azure/cli/command_modules/component/__init__.py @@ -7,8 +7,8 @@ def load_params(_): - import azure.cli.command_modules.component._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.component._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.component.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.component.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-configure/azure/cli/command_modules/configure/__init__.py b/src/command_modules/azure-cli-configure/azure/cli/command_modules/configure/__init__.py index d3a7b30c254..900fe4917d3 100644 --- a/src/command_modules/azure-cli-configure/azure/cli/command_modules/configure/__init__.py +++ b/src/command_modules/azure-cli-configure/azure/cli/command_modules/configure/__init__.py @@ -7,8 +7,8 @@ def load_params(_): - import azure.cli.command_modules.configure._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.configure._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.configure.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.configure.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/__init__.py b/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/__init__.py index 6b1891611d4..49e59596c7c 100644 --- a/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/__init__.py +++ b/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/__init__.py @@ -7,8 +7,8 @@ def load_params(_): - import azure.cli.command_modules.cosmosdb._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.cosmosdb._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.cosmosdb.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.cosmosdb.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/_client_factory.py b/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/_client_factory.py index c1dc7844a1d..c3d2999040e 100644 --- a/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/_client_factory.py +++ b/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/_client_factory.py @@ -35,14 +35,12 @@ def _get_url_connection(url_collection, account_name): return url_collection elif account_name: return 'https://{}.documents.azure.com:443'.format(account_name) - else: - return None + + return None def get_document_client_factory(kwargs): from pydocumentdb import document_client - from azure.cli.core.commands.client_factory import get_data_service_client - from azure.cli.core._profile import CLOUD service_type = document_client.DocumentClient logger.debug('Getting data service client service_type=%s', service_type.__name__) diff --git a/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/_exception_handler.py b/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/_exception_handler.py index 24ccf20505a..3a32c4280ed 100644 --- a/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/_exception_handler.py +++ b/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/_exception_handler.py @@ -77,11 +77,9 @@ def chained_handler(ex): def network_exception_handler(ex): - import requests as requests # wraps a connection exception in CLIError - # pylint:disable=line-too-long - if isinstance(ex, requests.exceptions.ConnectionError) or \ - isinstance(ex, requests.exceptions.HTTPError): + import requests.exceptions + if isinstance(ex, (requests.exceptions.ConnectionError, requests.exceptions.HTTPError)): raise CLIError('Please ensure you have network connection. Error detail: ' + str(ex)) raise ex diff --git a/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/_params.py b/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/_params.py index 60ec13c867f..8eb0407dcbb 100644 --- a/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/_params.py +++ b/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/_params.py @@ -10,19 +10,16 @@ get_resource_name_completion_list, enum_choice_list, name_type, - ignore_type, - file_type) + ignore_type) from azure.cli.core.util import shell_safe_json_parse -from ._client_factory import get_document_client_factory -import azure.cli.core.commands.arm from azure.mgmt.documentdb.models.document_db_enums import KeyKind from azure.mgmt.documentdb.models.document_db_enums import DefaultConsistencyLevel from azure.mgmt.documentdb.models.document_db_enums import DatabaseAccountKind from azure.mgmt.documentdb.models.failover_policy import FailoverPolicy from azure.mgmt.documentdb.models.location import Location -from azure.cli.core.commands import register_cli_argument, register_extra_cli_argument, CliArgumentType +from azure.cli.core.commands import register_cli_argument, CliArgumentType def validate_failover_policies(ns): diff --git a/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/custom.py b/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/custom.py index 34bc8ecf07f..6c7d154bb33 100644 --- a/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/custom.py +++ b/src/command_modules/azure-cli-cosmosdb/azure/cli/command_modules/cosmosdb/custom.py @@ -136,13 +136,11 @@ def cli_cosmosdb_update(client, def cli_cosmosdb_list(client, resource_group_name=None): - """ - Lists all Azure Cosmos DB database accounts within a given resource group or subscription. - """ + """ Lists all Azure Cosmos DB database accounts within a given resource group or subscription. """ if resource_group_name: return client.list_by_resource_group(resource_group_name) - else: - return client.list() + + return client.list() ###################### diff --git a/src/command_modules/azure-cli-dla/azure/cli/command_modules/dla/__init__.py b/src/command_modules/azure-cli-dla/azure/cli/command_modules/dla/__init__.py index 6fc59ac4d6c..659a98a6ff7 100644 --- a/src/command_modules/azure-cli-dla/azure/cli/command_modules/dla/__init__.py +++ b/src/command_modules/azure-cli-dla/azure/cli/command_modules/dla/__init__.py @@ -7,10 +7,8 @@ def load_params(_): - # pylint: disable=redefined-outer-name - import azure.cli.command_modules.dla._params + import azure.cli.command_modules.dla._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - # pylint: disable=redefined-outer-name - import azure.cli.command_modules.dla.commands + import azure.cli.command_modules.dla.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-dla/azure/cli/command_modules/dla/custom.py b/src/command_modules/azure-cli-dla/azure/cli/command_modules/dla/custom.py index 3d64312c890..36a46c9f25f 100644 --- a/src/command_modules/azure-cli-dla/azure/cli/command_modules/dla/custom.py +++ b/src/command_modules/azure-cli-dla/azure/cli/command_modules/dla/custom.py @@ -63,7 +63,7 @@ def list_adla_jobs(client, job_list = client.list(account_name, orderby="submitTime desc", top=top if top <= 300 else None, - filter=filter_string if filter_string and len(filter_string) > 0 else None) + filter=filter_string if filter_string else None) if top <= 300: return job_list diff --git a/src/command_modules/azure-cli-dls/azure/cli/command_modules/dls/__init__.py b/src/command_modules/azure-cli-dls/azure/cli/command_modules/dls/__init__.py index b6ddf1b7b6d..798e448ef8c 100644 --- a/src/command_modules/azure-cli-dls/azure/cli/command_modules/dls/__init__.py +++ b/src/command_modules/azure-cli-dls/azure/cli/command_modules/dls/__init__.py @@ -7,10 +7,8 @@ def load_params(_): - # pylint: disable=redefined-outer-name - import azure.cli.command_modules.dls._params + import azure.cli.command_modules.dls._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - # pylint: disable=redefined-outer-name - import azure.cli.command_modules.dls.commands + import azure.cli.command_modules.dls.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-dls/azure/cli/command_modules/dls/custom.py b/src/command_modules/azure-cli-dls/azure/cli/command_modules/dls/custom.py index ee449cf32ef..99a89d03ef3 100644 --- a/src/command_modules/azure-cli-dls/azure/cli/command_modules/dls/custom.py +++ b/src/command_modules/azure-cli-dls/azure/cli/command_modules/dls/custom.py @@ -193,7 +193,6 @@ def test_adls_item(account_name, return cf_dls_filesystem(account_name).exists(path) -# pylint: disable=redefined-variable-type def preview_adls_item(account_name, path, length=None, diff --git a/src/command_modules/azure-cli-feedback/azure/cli/command_modules/feedback/__init__.py b/src/command_modules/azure-cli-feedback/azure/cli/command_modules/feedback/__init__.py index 93b15ce5dd2..b8232fbdee1 100644 --- a/src/command_modules/azure-cli-feedback/azure/cli/command_modules/feedback/__init__.py +++ b/src/command_modules/azure-cli-feedback/azure/cli/command_modules/feedback/__init__.py @@ -11,4 +11,4 @@ def load_params(_): def load_commands(): - import azure.cli.command_modules.feedback.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.feedback.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-find/azure/cli/command_modules/find/__init__.py b/src/command_modules/azure-cli-find/azure/cli/command_modules/find/__init__.py index 8121b22221f..e707d5232a4 100644 --- a/src/command_modules/azure-cli-find/azure/cli/command_modules/find/__init__.py +++ b/src/command_modules/azure-cli-find/azure/cli/command_modules/find/__init__.py @@ -7,8 +7,8 @@ def load_params(_): - import azure.cli.command_modules.find._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.find._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.find.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.find.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-interactive/azure/cli/command_modules/interactive/__init__.py b/src/command_modules/azure-cli-interactive/azure/cli/command_modules/interactive/__init__.py index 52e6c8fc622..9bbbf657e61 100644 --- a/src/command_modules/azure-cli-interactive/azure/cli/command_modules/interactive/__init__.py +++ b/src/command_modules/azure-cli-interactive/azure/cli/command_modules/interactive/__init__.py @@ -7,8 +7,8 @@ def load_params(_): - import azure.cli.command_modules.interactive._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.interactive._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.interactive.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.interactive.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-iot/azure/cli/command_modules/iot/__init__.py b/src/command_modules/azure-cli-iot/azure/cli/command_modules/iot/__init__.py index 5b1e23395ca..080cb6c1186 100644 --- a/src/command_modules/azure-cli-iot/azure/cli/command_modules/iot/__init__.py +++ b/src/command_modules/azure-cli-iot/azure/cli/command_modules/iot/__init__.py @@ -7,8 +7,8 @@ def load_params(_): - import azure.cli.command_modules.iot._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.iot._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.iot.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.iot.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-iot/azure/cli/command_modules/iot/commands.py b/src/command_modules/azure-cli-iot/azure/cli/command_modules/iot/commands.py index 3e49815706f..f06fb165c94 100644 --- a/src/command_modules/azure-cli-iot/azure/cli/command_modules/iot/commands.py +++ b/src/command_modules/azure-cli-iot/azure/cli/command_modules/iot/commands.py @@ -6,8 +6,8 @@ from azure.cli.core.commands import cli_command from azure.cli.core.commands.arm import cli_generic_update_command -from ._factory import iot_hub_service_factory as factory from azure.cli.core.commands import LongRunningOperation +from ._factory import iot_hub_service_factory as factory custom_path = 'azure.cli.command_modules.iot.custom#{0}' diff --git a/src/command_modules/azure-cli-iot/azure/cli/command_modules/iot/custom.py b/src/command_modules/azure-cli-iot/azure/cli/command_modules/iot/custom.py index d2e8ac51827..e9af0f49ca1 100644 --- a/src/command_modules/azure-cli-iot/azure/cli/command_modules/iot/custom.py +++ b/src/command_modules/azure-cli-iot/azure/cli/command_modules/iot/custom.py @@ -58,15 +58,13 @@ def _check_name_availability(client, hub_name): def iot_hub_get(client, hub_name, resource_group_name=None): if resource_group_name is None: return _get_iot_hub_by_name(client, hub_name) - else: - return client.get(resource_group_name, hub_name) + return client.get(resource_group_name, hub_name) def iot_hub_list(client, resource_group_name=None): if resource_group_name is None: return client.list_by_subscription() - else: - return client.list_by_resource_group(resource_group_name) + return client.list_by_resource_group(resource_group_name) def iot_hub_update(client, hub_name, parameters, resource_group_name=None): @@ -218,11 +216,10 @@ def _validate_x509_parameters(x509, primary_thumbprint, secondary_thumbprint, va def _construct_x509_auth(device_id, primary_thumbprint, secondary_thumbprint, valid_days, output_dir): if any([primary_thumbprint, secondary_thumbprint]): return Authentication(x509_thumbprint=X509Thumbprint(primary_thumbprint, secondary_thumbprint)) - else: - valid_days = valid_days if valid_days is not None else 365 - output_dir = output_dir if output_dir is not None else '.' - cert_info = create_self_signed_certificate(device_id, valid_days, output_dir) - return Authentication(x509_thumbprint=X509Thumbprint(cert_info['thumbprint'])) + valid_days = valid_days if valid_days is not None else 365 + output_dir = output_dir if output_dir is not None else '.' + cert_info = create_self_signed_certificate(device_id, valid_days, output_dir) + return Authentication(x509_thumbprint=X509Thumbprint(cert_info['thumbprint'])) def iot_device_get(client, hub_name, device_id, resource_group_name=None): @@ -352,15 +349,13 @@ def _ensure_location(resource_group_name, location): if location is None: resource_group_client = resource_service_factory().resource_groups return resource_group_client.get(resource_group_name).location - else: - return location + return location def _ensure_resource_group_name(client, resource_group_name, hub_name): if resource_group_name is None: return _get_iot_hub_by_name(client, hub_name).resourcegroup - else: - return resource_group_name + return resource_group_name # Convert permission list to AccessRights from IoT SDK. diff --git a/src/command_modules/azure-cli-keyvault/azure/cli/command_modules/keyvault/__init__.py b/src/command_modules/azure-cli-keyvault/azure/cli/command_modules/keyvault/__init__.py index a1e25259f94..d5126b31918 100644 --- a/src/command_modules/azure-cli-keyvault/azure/cli/command_modules/keyvault/__init__.py +++ b/src/command_modules/azure-cli-keyvault/azure/cli/command_modules/keyvault/__init__.py @@ -7,8 +7,8 @@ def load_params(_): - import azure.cli.command_modules.keyvault._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.keyvault._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.keyvault.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.keyvault.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-keyvault/azure/cli/command_modules/keyvault/_command_type.py b/src/command_modules/azure-cli-keyvault/azure/cli/command_modules/keyvault/_command_type.py index da9b3835e67..7d532f785a2 100644 --- a/src/command_modules/azure-cli-keyvault/azure/cli/command_modules/keyvault/_command_type.py +++ b/src/command_modules/azure-cli-keyvault/azure/cli/command_modules/keyvault/_command_type.py @@ -30,10 +30,9 @@ def _encode_hex(item): except TypeError: item.__dict__[key] = _encode_hex(val) return item - elif isinstance(item, bytes) or isinstance(item, bytearray): + elif isinstance(item, (bytes, bytearray)): return base64.b64encode(item).decode('utf-8') - else: - return item + return item def _create_key_vault_command(module_name, name, operation, transform_result, table_transformer): @@ -66,7 +65,7 @@ def get_token(server, resource, scope): # pylint: disable=unused-argument op = get_op_handler(operation) # since the convenience client can be inconvenient, we have to check and create the # correct client version - client = KeyVaultClient(KeyVaultAuthentication(get_token)) # pylint: disable=redefined-variable-type + client = KeyVaultClient(KeyVaultAuthentication(get_token)) result = op(client, **kwargs) # apply results transform if specified diff --git a/src/command_modules/azure-cli-keyvault/azure/cli/command_modules/keyvault/_params.py b/src/command_modules/azure-cli-keyvault/azure/cli/command_modules/keyvault/_params.py index b27b9a87d96..bc6466194b9 100644 --- a/src/command_modules/azure-cli-keyvault/azure/cli/command_modules/keyvault/_params.py +++ b/src/command_modules/azure-cli-keyvault/azure/cli/command_modules/keyvault/_params.py @@ -41,7 +41,7 @@ def _get_token(server, resource, scope): # pylint: disable=unused-argument def get_keyvault_name_completion_list(resource_name): def completer(prefix, action, parsed_args, **kwargs): # pylint: disable=unused-argument client = KeyVaultClient( - KeyVaultAuthentication(_get_token)) # pylint: disable=redefined-variable-type + KeyVaultAuthentication(_get_token)) func_name = 'get_{}s'.format(resource_name) vault = parsed_args.vault_base_url items = [] @@ -56,7 +56,7 @@ def completer(prefix, action, parsed_args, **kwargs): # pylint: disable=unused- def get_keyvault_version_completion_list(resource_name): def completer(prefix, action, parsed_args, **kwargs): # pylint: disable=unused-argument client = KeyVaultClient( - KeyVaultAuthentication(_get_token)) # pylint: disable=redefined-variable-type + KeyVaultAuthentication(_get_token)) func_name = 'get_{}_versions'.format(resource_name) vault = parsed_args.vault_base_url name = getattr(parsed_args, '{}_name'.format(resource_name)) diff --git a/src/command_modules/azure-cli-keyvault/azure/cli/command_modules/keyvault/custom.py b/src/command_modules/azure-cli-keyvault/azure/cli/command_modules/keyvault/custom.py index b0bc643c472..736f5596e4f 100644 --- a/src/command_modules/azure-cli-keyvault/azure/cli/command_modules/keyvault/custom.py +++ b/src/command_modules/azure-cli-keyvault/azure/cli/command_modules/keyvault/custom.py @@ -206,10 +206,7 @@ def get_default_policy(client, scaffold=False): # pylint: disable=unused-argume :return: policy dict :rtype: dict """ - if scaffold: - return _scaffold_certificate_profile() - else: - return _default_certificate_profile() + return _scaffold_certificate_profile() if scaffold else _default_certificate_profile() def create_keyvault(client, @@ -541,7 +538,7 @@ def create_certificate(client, vault_base_url, certificate_name, certificate_pol message = getattr(client_exception, 'message', client_exception) try: - ex_message = json.loads(client_exception.response.text) + ex_message = json.loads(client_exception.response.text) # pylint: disable=no-member message = str(message) + ' ' + ex_message['error']['details'][0]['message'] except: # pylint: disable=bare-except pass @@ -641,7 +638,7 @@ def download_certificate(client, vault_base_url, certificate_name, file_path, import base64 encoded = base64.encodestring(cert) # pylint:disable=deprecated-method if isinstance(encoded, bytes): - encoded = encoded.decode("utf-8") # pylint:disable=redefined-variable-type + encoded = encoded.decode("utf-8") encoded = '-----BEGIN CERTIFICATE-----\n' + encoded + '-----END CERTIFICATE-----\n' f.write(encoded.encode("utf-8")) except Exception as ex: # pylint: disable=broad-except @@ -676,8 +673,7 @@ def delete_certificate_contact(client, vault_base_url, contact_email): raise CLIError("contact '{}' not found in vault '{}'".format(contact_email, vault_base_url)) if remaining.contact_list: return client.set_certificate_contacts(vault_base_url, remaining.contact_list) - else: - return client.delete_certificate_contacts(vault_base_url) + return client.delete_certificate_contacts(vault_base_url) def create_certificate_issuer(client, vault_base_url, issuer_name, provider_name, account_id=None, 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 5a655f33e6b..e2c8464832c 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 @@ -7,8 +7,8 @@ def load_params(_): - import azure.cli.command_modules.lab.params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.lab.params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.lab.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.lab.commands # pylint: disable=redefined-outer-name, unused-variable 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 94081ae1a90..28f9cfd7986 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 @@ -4,6 +4,7 @@ # -------------------------------------------------------------------------------------------- from collections import OrderedDict +from azure.cli.core.sdk.util import (ServiceGroup, create_service_adapter) from ._client_factory import (get_devtestlabs_virtual_machine_operation, get_devtestlabs_custom_image_operation, get_devtestlabs_gallery_image_operation, @@ -15,7 +16,6 @@ get_devtestlabs_secret_operation, get_devtestlabs_environment_operation, get_devtestlabs_arm_template_operation) -from azure.cli.core.sdk.util import (ServiceGroup, create_service_adapter) custom_path = 'azure.cli.command_modules.lab.custom' 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 1d3bbffb0d0..60c92f7ea96 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 @@ -58,9 +58,9 @@ def claim_vm(client, lab_name=None, name=None, resource_group=None): if name is not None: return client.claim(resource_group, lab_name, name) - else: - from ._client_factory import get_devtestlabs_lab_operation - return get_devtestlabs_lab_operation(None).claim_any_vm(resource_group, lab_name) + + from ._client_factory import get_devtestlabs_lab_operation + return get_devtestlabs_lab_operation(None).claim_any_vm(resource_group, lab_name) # pylint: disable=too-many-locals, unused-argument 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 a96da421c9d..989e8d9b07d 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 @@ -9,7 +9,6 @@ from msrestazure.azure_exceptions import CloudError from azure.cli.core.util import CLIError from azure.cli.core.commands.arm import resource_id, is_valid_resource_id -from ._client_factory import (get_devtestlabs_management_client) 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 \ @@ -17,6 +16,7 @@ from azure.mgmt.devtestlabs.models.inbound_nat_rule import InboundNatRule from azure.graphrbac import GraphRbacManagementClient import azure.cli.core.azlogging as azlogging +from ._client_factory import (get_devtestlabs_management_client) logger = azlogging.get_az_logger(__name__) diff --git a/src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/__init__.py b/src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/__init__.py index 0d9e2466acb..f84ac0b8c90 100644 --- a/src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/__init__.py +++ b/src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/__init__.py @@ -7,8 +7,8 @@ def load_params(_): - import azure.cli.command_modules.monitor.params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.monitor.params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.monitor.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.monitor.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/actions.py b/src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/actions.py index f3f748db16a..56accbccd79 100644 --- a/src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/actions.py +++ b/src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/actions.py @@ -15,8 +15,7 @@ def period_type(value): def _get_substring(indices): if indices == tuple([-1, -1]): return '' - else: - return value[indices[0]: indices[1]] + return value[indices[0]: indices[1]] regex = r'(p)?(\d+y)?(\d+m)?(\d+d)?(t)?(\d+h)?(\d+m)?(\d+s)?' match = re.match(regex, value.lower()) @@ -26,14 +25,14 @@ def _get_substring(indices): # simply return value if a valid ISO8601 string is supplied if match.regs[1] != tuple([-1, -1]) and match.regs[5] != tuple([-1, -1]): return value - else: - # if shorthand is used, only support days, minutes, hours, seconds - # ensure M is interpretted as minutes - days = _get_substring(match.regs[4]) - minutes = _get_substring(match.regs[6]) or _get_substring(match.regs[3]) - hours = _get_substring(match.regs[7]) - seconds = _get_substring(match.regs[8]) - return 'P{}T{}{}{}'.format(days, minutes, hours, seconds).upper() + + # if shorthand is used, only support days, minutes, hours, seconds + # ensure M is interpretted as minutes + days = _get_substring(match.regs[4]) + minutes = _get_substring(match.regs[6]) or _get_substring(match.regs[3]) + hours = _get_substring(match.regs[7]) + seconds = _get_substring(match.regs[8]) + return 'P{}T{}{}{}'.format(days, minutes, hours, seconds).upper() # pylint: disable=too-few-public-methods @@ -67,10 +66,9 @@ def __call__(self, parser, namespace, values, option_string=None): def get_action(self, values, option_string): # pylint: disable=no-self-use _type = values[0].lower() - action = None if _type == 'email': from azure.mgmt.monitor.models import RuleEmailAction - action = RuleEmailAction(custom_emails=values[1:]) + return RuleEmailAction(custom_emails=values[1:]) elif _type == 'webhook': from azure.mgmt.monitor.models import RuleWebhookAction uri = values[1] @@ -78,11 +76,9 @@ def get_action(self, values, option_string): # pylint: disable=no-self-use properties = dict(x.split('=', 1) for x in values[2:]) except ValueError: raise CLIError('usage error: {} webhook URI [KEY=VALUE ...]'.format(option_string)) - action = RuleWebhookAction(uri, properties) # pylint: disable=redefined-variable-type - else: - raise CLIError('usage error: {} TYPE KEY [ARGS]'.format(option_string)) + return RuleWebhookAction(uri, properties) - return action + raise CLIError('usage error: {} TYPE KEY [ARGS]'.format(option_string)) class AlertRemoveAction(argparse._AppendAction): diff --git a/src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/commands.py b/src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/commands.py index 2abc7c7f44f..992c7ff9936 100644 --- a/src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/commands.py +++ b/src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/commands.py @@ -5,12 +5,12 @@ # pylint: disable=line-too-long +from azure.cli.core.commands import cli_command +from azure.cli.core.commands.arm import cli_generic_update_command from ._client_factory import \ (cf_alert_rules, cf_metrics, cf_metric_def, cf_alert_rule_incidents, cf_log_profiles, cf_autoscale, cf_diagnostics, cf_activity_log) from ._exception_handler import monitor_exception_handler -from azure.cli.core.commands import cli_command -from azure.cli.core.commands.arm import cli_generic_update_command def monitor_command(*args, **kwargs): diff --git a/src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/custom.py b/src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/custom.py index 6f4d4a14d2a..8ec40dc34b0 100644 --- a/src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/custom.py +++ b/src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/custom.py @@ -67,7 +67,7 @@ def _parse_action_removals(actions): def create_metric_rule(client, resource_group_name, rule_name, target, condition, description=None, disabled=False, location=None, tags=None, email_service_owners=False, actions=None): - from azure.mgmt.monitor.models import AlertRuleResource, RuleEmailAction, RuleWebhookAction + from azure.mgmt.monitor.models import AlertRuleResource, RuleEmailAction condition.data_source.resource_uri = target custom_emails, webhooks, _ = _parse_actions(actions) actions = [RuleEmailAction(email_service_owners, custom_emails)] + (webhooks or []) diff --git a/src/command_modules/azure-cli-network/azure/cli/command_modules/network/__init__.py b/src/command_modules/azure-cli-network/azure/cli/command_modules/network/__init__.py index 89e409c4e5a..df2ddf6ea86 100644 --- a/src/command_modules/azure-cli-network/azure/cli/command_modules/network/__init__.py +++ b/src/command_modules/azure-cli-network/azure/cli/command_modules/network/__init__.py @@ -3,10 +3,12 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -import azure.cli.command_modules.network._help # pylint: disable=unused-import +import azure.cli.command_modules.network._help # pylint: disable=unused-import + def load_params(_): - import azure.cli.command_modules.network._params #pylint: disable=redefined-outer-name + import azure.cli.command_modules.network._params # pylint: disable=redefined-outer-name, unused-variable + def load_commands(): - import azure.cli.command_modules.network.commands #pylint: disable=redefined-outer-name + import azure.cli.command_modules.network.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-network/azure/cli/command_modules/network/_client_factory.py b/src/command_modules/azure-cli-network/azure/cli/command_modules/network/_client_factory.py index 9091db42c8c..bcd7e9eee2c 100644 --- a/src/command_modules/azure-cli-network/azure/cli/command_modules/network/_client_factory.py +++ b/src/command_modules/azure-cli-network/azure/cli/command_modules/network/_client_factory.py @@ -3,7 +3,6 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -#pylint: disable=line-too-long def _network_client_factory(**_): from azure.cli.core.profiles import ResourceType @@ -12,7 +11,6 @@ def _network_client_factory(**_): def resource_client_factory(**_): - from azure.mgmt.resource import ResourceManagementClient from azure.cli.core.commands.client_factory import get_mgmt_service_client from azure.cli.core.profiles import ResourceType return get_mgmt_service_client(ResourceType.MGMT_RESOURCE_RESOURCES) @@ -131,11 +129,14 @@ def cf_dns_mgmt_record_sets(_): from azure.cli.core.commands.client_factory import get_mgmt_service_client return get_mgmt_service_client(DnsManagementClient).record_sets + def cf_route_filters(_): return _network_client_factory().route_filters + def cf_route_filter_rules(_): return _network_client_factory().route_filter_rules + def cf_service_community(_): return _network_client_factory().bgp_service_communities diff --git a/src/command_modules/azure-cli-network/azure/cli/command_modules/network/_format.py b/src/command_modules/azure-cli-network/azure/cli/command_modules/network/_format.py index e327be61610..658f6d0fb4a 100644 --- a/src/command_modules/azure-cli-network/azure/cli/command_modules/network/_format.py +++ b/src/command_modules/azure-cli-network/azure/cli/command_modules/network/_format.py @@ -94,8 +94,8 @@ def transform_vpn_connection(result): delattr(result, prop) else: null_props = [key for key in prop_val.__dict__ if not prop_val.__dict__[key]] - for prop in null_props: - delattr(prop_val, prop) + for null_prop in null_props: + delattr(prop_val, null_prop) return result @@ -110,9 +110,9 @@ def transform_vpn_connection_create_output(result): elif isinstance(result, ClientRawResponse): # returns a raw response if --no-wait used return - else: - # returns a plain response (not a poller) if --validate used - return result + + # returns a plain response (not a poller) if --validate used + return result def transform_vnet_create_output(result): diff --git a/src/command_modules/azure-cli-network/azure/cli/command_modules/network/_template_builder.py b/src/command_modules/azure-cli-network/azure/cli/command_modules/network/_template_builder.py index 663958af8d9..095ac5494f1 100644 --- a/src/command_modules/azure-cli-network/azure/cli/command_modules/network/_template_builder.py +++ b/src/command_modules/azure-cli-network/azure/cli/command_modules/network/_template_builder.py @@ -9,7 +9,6 @@ class ArmTemplateBuilder(object): - def __init__(self): template = OrderedDict() template['$schema'] = \ @@ -44,8 +43,9 @@ def add_output(self, key, property_name, provider=None, property_type=None, output_type='string', path=None): if provider and property_type: - value = "[reference(resourceId('{provider}/{type}', '{property}'),providers('{provider}', '{type}').apiVersions[0])".format( # pylint: disable=line-too-long - provider=provider, type=property_type, property=property_name) + template = "[reference(resourceId('{provider}/{type}', '{property}')," \ + "providers('{provider}', '{type}').apiVersions[0])" + value = template.format(provider=provider, type=property_type, property=property_name) else: value = "[reference('{}')".format(property_name) value = '{}.{}]'.format(value, path) if path else '{}]'.format(value) @@ -85,14 +85,11 @@ def _build_frontend_ip_config(name, public_ip_id=None, subnet_id=None, private_i # pylint: disable=too-many-locals -def build_application_gateway_resource(name, location, tags, sku_name, sku_tier, capacity, - servers, frontend_port, - private_ip_address, private_ip_allocation, - cert_data, cert_password, - cookie_based_affinity, - http_settings_protocol, http_settings_port, - http_listener_protocol, routing_rule_type, public_ip_id, - subnet_id, connection_draining_timeout): +def build_application_gateway_resource(name, location, tags, sku_name, sku_tier, capacity, servers, frontend_port, + private_ip_address, private_ip_allocation, cert_data, cert_password, + cookie_based_affinity, http_settings_protocol, http_settings_port, + http_listener_protocol, routing_rule_type, public_ip_id, subnet_id, + connection_draining_timeout): from azure.cli.core.profiles import ResourceType, supported_api_version, get_api_version # set the default names @@ -210,12 +207,10 @@ def _ag_subresource_id(_type, name): return ag -def build_load_balancer_resource(name, location, tags, backend_pool_name, - frontend_ip_name, public_ip_id, subnet_id, +def build_load_balancer_resource(name, location, tags, backend_pool_name, frontend_ip_name, public_ip_id, subnet_id, private_ip_address, private_ip_allocation): - - frontend_ip_config = _build_frontend_ip_config(frontend_ip_name, public_ip_id, subnet_id, - private_ip_address, private_ip_allocation) + frontend_ip_config = _build_frontend_ip_config(frontend_ip_name, public_ip_id, subnet_id, private_ip_address, + private_ip_allocation) lb_properties = { 'backendAddressPools': [ @@ -239,7 +234,6 @@ def build_load_balancer_resource(name, location, tags, backend_pool_name, def build_public_ip_resource(name, location, tags, address_allocation, dns_name=None): - public_ip_properties = {'publicIPAllocationMethod': address_allocation} if dns_name: @@ -257,8 +251,7 @@ def build_public_ip_resource(name, location, tags, address_allocation, dns_name= return public_ip -def build_vnet_resource(name, location, tags, vnet_prefix=None, subnet=None, - subnet_prefix=None, dns_servers=None): +def build_vnet_resource(name, location, tags, vnet_prefix=None, subnet=None, subnet_prefix=None, dns_servers=None): vnet = { 'name': name, 'type': 'Microsoft.Network/virtualNetworks', @@ -284,10 +277,9 @@ def build_vnet_resource(name, location, tags, vnet_prefix=None, subnet=None, return vnet -def build_vpn_connection_resource(name, location, tags, gateway1, gateway2, vpn_type, - authorization_key, enable_bgp, routing_weight, shared_key, - use_policy_based_traffic_selectors): - from azure.cli.core.profiles import ResourceType, supported_api_version, get_api_version +def build_vpn_connection_resource(name, location, tags, gateway1, gateway2, vpn_type, authorization_key, enable_bgp, + routing_weight, shared_key, use_policy_based_traffic_selectors): + from azure.cli.core.profiles import ResourceType, supported_api_version vpn_properties = { 'virtualNetworkGateway1': {'id': gateway1}, 'authorizationKey': authorization_key, @@ -324,4 +316,3 @@ def build_vpn_connection_resource(name, location, tags, gateway1, gateway2, vpn_ 'properties': vpn_properties if vpn_type != 'VpnClient' else {} } return vpn_connection - diff --git a/src/command_modules/azure-cli-network/azure/cli/command_modules/network/_validators.py b/src/command_modules/azure-cli-network/azure/cli/command_modules/network/_validators.py index 30254e8bec4..53aae863e6e 100644 --- a/src/command_modules/azure-cli-network/azure/cli/command_modules/network/_validators.py +++ b/src/command_modules/azure-cli-network/azure/cli/command_modules/network/_validators.py @@ -17,12 +17,14 @@ from azure.cli.core.commands.client_factory import get_subscription_id, get_mgmt_service_client from azure.cli.core.profiles import ResourceType, get_sdk, get_api_version + # PARAMETER VALIDATORS def dns_zone_name_type(value): if value: return value[:-1] if value[-1] == '.' else value + def _generate_ag_subproperty_id(namespace, child_type, child_name, subscription=None): return resource_id( subscription=subscription or get_subscription_id(), @@ -33,6 +35,7 @@ def _generate_ag_subproperty_id(namespace, child_type, child_name, subscription= child_type=child_type, child_name=child_name) + def _generate_lb_subproperty_id(namespace, child_type, child_name, subscription=None): return resource_id( subscription=subscription or get_subscription_id(), @@ -43,6 +46,7 @@ def _generate_lb_subproperty_id(namespace, child_type, child_name, subscription= child_type=child_type, child_name=child_name) + def _generate_lb_id_list_from_names_or_ids(namespace, prop, child_type): raw = getattr(namespace, prop) if not raw: @@ -66,6 +70,7 @@ def validate_address_pool_id_list(namespace): _generate_lb_id_list_from_names_or_ids( namespace, 'load_balancer_backend_address_pool_ids', 'backendAddressPools') + def validate_address_pool_name_or_id(namespace): pool_name = namespace.backend_address_pool lb_name = namespace.load_balancer_name @@ -79,8 +84,8 @@ def validate_address_pool_name_or_id(namespace): namespace.backend_address_pool = _generate_lb_subproperty_id( namespace, 'backendAddressPools', pool_name) -def validate_address_prefixes(namespace): +def validate_address_prefixes(namespace): subnet_prefix_set = SPECIFIED_SENTINEL in namespace.subnet_address_prefix vnet_prefix_set = SPECIFIED_SENTINEL in namespace.vnet_address_prefix namespace.subnet_address_prefix = \ @@ -91,6 +96,7 @@ def validate_address_prefixes(namespace): raise CLIError('Existing subnet ({}) found. Cannot specify address prefixes when ' 'reusing an existing subnet.'.format(namespace.subnet)) + def read_base_64_file(filename): with open(filename, 'rb') as f: contents = f.read() @@ -100,11 +106,12 @@ def read_base_64_file(filename): except UnicodeDecodeError: return str(base64_data) + def validate_auth_cert(namespace): namespace.cert_data = read_base_64_file(namespace.cert_data) -def validate_cert(namespace): +def validate_cert(namespace): params = [namespace.cert_data, namespace.cert_password] if all([not x for x in params]): # no cert supplied -- use HTTP @@ -127,6 +134,7 @@ def validate_cert(namespace): # app-gateway ssl-cert create does not have these fields and that is okay pass + def validate_dns_record_type(namespace): tokens = namespace.command.split(' ') types = ['a', 'aaaa', 'cname', 'mx', 'ns', 'ptr', 'soa', 'srv', 'txt'] @@ -138,10 +146,12 @@ def validate_dns_record_type(namespace): namespace.record_set_type = token return + def validate_inbound_nat_rule_id_list(namespace): _generate_lb_id_list_from_names_or_ids( namespace, 'load_balancer_inbound_nat_rule_ids', 'inboundNatRules') + def validate_inbound_nat_rule_name_or_id(namespace): rule_name = namespace.inbound_nat_rule lb_name = namespace.load_balancer_name @@ -155,10 +165,12 @@ def validate_inbound_nat_rule_name_or_id(namespace): namespace.inbound_nat_rule = _generate_lb_subproperty_id( namespace, 'inboundNatRules', rule_name) + def validate_metadata(namespace): if namespace.metadata: namespace.metadata = dict(x.split('=', 1) for x in namespace.metadata) + def validate_peering_type(namespace): if namespace.peering_type and namespace.peering_type == 'MicrosoftPeering': @@ -166,10 +178,12 @@ def validate_peering_type(namespace): raise CLIError( 'missing required MicrosoftPeering parameter --advertised-public-prefixes') + def validate_private_ip_address(namespace): if namespace.private_ip_address and hasattr(namespace, 'private_ip_address_allocation'): namespace.private_ip_address_allocation = 'static' + def validate_route_filter(namespace): if namespace.route_filter: if not is_valid_resource_id(namespace.route_filter): @@ -180,10 +194,12 @@ def validate_route_filter(namespace): type='routeFilters', name=namespace.route_filter) + def get_public_ip_validator(has_type_field=False, allow_none=False, allow_new=False, default_none=False): """ Retrieves a validator for public IP address. Accepting all defaults will perform a check for an existing name or ID with no ARM-required -type parameter. """ + def simple_validator(namespace): if namespace.public_ip_address: is_list = isinstance(namespace.public_ip_address, list) @@ -204,7 +220,6 @@ def _validate_name_or_id(public_ip): else: namespace.public_ip_address = _validate_name_or_id(namespace.public_ip_address) - def complex_validator_with_type(namespace): get_folded_parameter_validator( 'public_ip_address', 'Microsoft.Network/publicIPAddresses', '--public-ip-address', @@ -212,9 +227,9 @@ def complex_validator_with_type(namespace): return complex_validator_with_type if has_type_field else simple_validator + def get_subnet_validator(has_type_field=False, allow_none=False, allow_new=False, default_none=False): - def simple_validator(namespace): if namespace.virtual_network_name is None and namespace.subnet is None: return @@ -253,8 +268,8 @@ def complex_validator_with_type(namespace): return complex_validator_with_type if has_type_field else simple_validator -def get_nsg_validator(has_type_field=False, allow_none=False, allow_new=False, default_none=False): +def get_nsg_validator(has_type_field=False, allow_none=False, allow_new=False, default_none=False): def simple_validator(namespace): if namespace.network_security_group: # determine if network_security_group is name or ID @@ -274,19 +289,20 @@ def complex_validator_with_type(namespace): return complex_validator_with_type if has_type_field else simple_validator + def validate_servers(namespace): servers = [] for item in namespace.servers if namespace.servers else []: try: - socket.inet_aton(item) #pylint:disable=no-member - servers.append({'ipAddress':item}) - except socket.error: #pylint:disable=no-member - servers.append({'fqdn':item}) + socket.inet_aton(item) # pylint:disable=no-member + servers.append({'ipAddress': item}) + except socket.error: # pylint:disable=no-member + servers.append({'fqdn': item}) namespace.servers = servers + def get_virtual_network_validator(has_type_field=False, allow_none=False, allow_new=False, default_none=False): - def simple_validator(namespace): if namespace.virtual_network: # determine if vnet is name or ID @@ -306,9 +322,10 @@ def complex_validator_with_type(namespace): return complex_validator_with_type if has_type_field else simple_validator + # COMMAND NAMESPACE VALIDATORS -def process_ag_listener_create_namespace(namespace): # pylint: disable=unused-argument +def process_ag_listener_create_namespace(namespace): # pylint: disable=unused-argument if namespace.frontend_ip and not is_valid_resource_id(namespace.frontend_ip): namespace.frontend_ip = _generate_ag_subproperty_id( namespace, 'frontendIpConfigurations', namespace.frontend_ip) @@ -321,12 +338,14 @@ def process_ag_listener_create_namespace(namespace): # pylint: disable=unused-ar namespace.ssl_cert = _generate_ag_subproperty_id( namespace, 'sslCertificates', namespace.ssl_cert) -def process_ag_http_settings_create_namespace(namespace): # pylint: disable=unused-argument + +def process_ag_http_settings_create_namespace(namespace): # pylint: disable=unused-argument if namespace.probe and not is_valid_resource_id(namespace.probe): namespace.probe = _generate_ag_subproperty_id( namespace, 'probes', namespace.probe) -def process_ag_rule_create_namespace(namespace): # pylint: disable=unused-argument + +def process_ag_rule_create_namespace(namespace): # pylint: disable=unused-argument if namespace.address_pool and not is_valid_resource_id(namespace.address_pool): namespace.address_pool = _generate_ag_subproperty_id( namespace, 'backendAddressPools', namespace.address_pool) @@ -343,22 +362,26 @@ def process_ag_rule_create_namespace(namespace): # pylint: disable=unused-argume namespace.url_path_map = _generate_ag_subproperty_id( namespace, 'urlPathMaps', namespace.url_path_map) + def process_ag_ssl_policy_set_namespace(namespace): if namespace.disabled_ssl_protocols and namespace.clear: raise ValueError('incorrect usage: --disabled-ssl-protocols PROTOCOL [...] | --clear') -def process_ag_url_path_map_create_namespace(namespace): # pylint: disable=unused-argument + +def process_ag_url_path_map_create_namespace(namespace): # pylint: disable=unused-argument if namespace.default_address_pool and not is_valid_resource_id(namespace.default_address_pool): namespace.default_address_pool = _generate_ag_subproperty_id( namespace, 'backendAddressPools', namespace.default_address_pool) - if namespace.default_http_settings and not is_valid_resource_id(namespace.default_http_settings): # pylint: disable=line-too-long + if namespace.default_http_settings and not is_valid_resource_id( + namespace.default_http_settings): # pylint: disable=line-too-long namespace.default_http_settings = _generate_ag_subproperty_id( namespace, 'backendHttpSettingsCollection', namespace.default_http_settings) process_ag_url_path_map_rule_create_namespace(namespace) -def process_ag_url_path_map_rule_create_namespace(namespace): # pylint: disable=unused-argument + +def process_ag_url_path_map_rule_create_namespace(namespace): # pylint: disable=unused-argument if namespace.address_pool and not is_valid_resource_id(namespace.address_pool): namespace.address_pool = _generate_ag_subproperty_id( namespace, 'backendAddressPools', namespace.address_pool) @@ -367,8 +390,8 @@ def process_ag_url_path_map_rule_create_namespace(namespace): # pylint: disable= namespace.http_settings = _generate_ag_subproperty_id( namespace, 'backendHttpSettingsCollection', namespace.http_settings) -def process_ag_create_namespace(namespace): +def process_ag_create_namespace(namespace): get_default_location_from_resource_group(namespace) # process folded parameters @@ -395,13 +418,14 @@ def process_ag_create_namespace(namespace): validate_cert(namespace) + def process_auth_create_namespace(namespace): ExpressRouteCircuitAuthorization = \ get_sdk(ResourceType.MGMT_NETWORK, 'ExpressRouteCircuitAuthorization', mod='models') namespace.authorization_parameters = ExpressRouteCircuitAuthorization() -def process_lb_create_namespace(namespace): +def process_lb_create_namespace(namespace): get_default_location_from_resource_group(namespace) if namespace.subnet and namespace.public_ip_address: @@ -429,8 +453,8 @@ def process_lb_create_namespace(namespace): namespace.subnet = None namespace.virtual_network_name = None -def process_lb_frontend_ip_namespace(namespace): +def process_lb_frontend_ip_namespace(namespace): if namespace.subnet and namespace.public_ip_address: raise ValueError( 'incorrect usage: --subnet NAME --vnet-name NAME | ' @@ -441,6 +465,7 @@ def process_lb_frontend_ip_namespace(namespace): else: get_public_ip_validator()(namespace) + def process_local_gateway_create_namespace(namespace): ns = namespace get_default_location_from_resource_group(ns) @@ -449,8 +474,8 @@ def process_local_gateway_create_namespace(namespace): raise ValueError( 'incorrect usage: --bgp-peering-address IP --asn ASN [--peer-weight WEIGHT]') -def process_nic_create_namespace(namespace): +def process_nic_create_namespace(namespace): get_default_location_from_resource_group(namespace) # process folded parameters @@ -469,13 +494,14 @@ def process_route_table_create_namespace(namespace): validate_tags(namespace) namespace.parameters = RouteTable(location=namespace.location, tags=namespace.tags) + def process_tm_endpoint_create_namespace(namespace): from azure.mgmt.trafficmanager import TrafficManagerManagementClient client = get_mgmt_service_client(TrafficManagerManagementClient).profiles profile = client.get(namespace.resource_group_name, namespace.profile_name) - routing_type = profile.traffic_routing_method # pylint: disable=no-member + routing_type = profile.traffic_routing_method # pylint: disable=no-member endpoint_type = namespace.endpoint_type all_options = \ ['target_resource_id', 'target', 'min_child_endpoints', 'priority', 'weight', \ @@ -506,7 +532,7 @@ def process_tm_endpoint_create_namespace(namespace): required_options.append('min_child_endpoints') if endpoint_type.lower() in ['nestedendpoints', 'externalendpoints'] and \ - routing_type.lower() == 'performance': + routing_type.lower() == 'performance': required_options.append('endpoint_location') if routing_type.lower() == 'geographic': @@ -514,20 +540,23 @@ def process_tm_endpoint_create_namespace(namespace): # ensure required options are provided missing_options = [props_to_options[x] for x in required_options \ - if getattr(namespace, x, None) is None] + if getattr(namespace, x, None) is None] extra_options = [props_to_options[x] for x in all_options if getattr(namespace, x, None) \ - is not None and x not in required_options] + is not None and x not in required_options] if missing_options or extra_options: - error_message = "Incorrect options for profile routing method '{}' and endpoint type '{}'.".format(routing_type, endpoint_type) # pylint: disable=line-too-long + error_message = "Incorrect options for profile routing method '{}' and endpoint type '{}'.".format(routing_type, + endpoint_type) # pylint: disable=line-too-long if missing_options: - error_message = '{}\nSupply the following: {}'.format(error_message, ', '.join(missing_options)) # pylint: disable=line-too-long + error_message = '{}\nSupply the following: {}'.format(error_message, ', '.join( + missing_options)) # pylint: disable=line-too-long if extra_options: - error_message = '{}\nOmit the following: {}'.format(error_message, ', '.join(extra_options)) # pylint: disable=line-too-long + error_message = '{}\nOmit the following: {}'.format(error_message, ', '.join( + extra_options)) # pylint: disable=line-too-long raise CLIError(error_message) -def process_vnet_create_namespace(namespace): +def process_vnet_create_namespace(namespace): get_default_location_from_resource_group(namespace) if namespace.subnet_prefix and not namespace.subnet_name: @@ -542,6 +571,7 @@ def process_vnet_create_namespace(namespace): subnet_mask = 24 if bit_mask < 24 else bit_mask namespace.subnet_prefix = '{}/{}'.format(address, subnet_mask) + def process_vnet_gateway_create_namespace(namespace): ns = namespace get_default_location_from_resource_group(ns) @@ -558,6 +588,7 @@ def process_vnet_gateway_create_namespace(namespace): raise ValueError( 'incorrect usage: --asn ASN [--peer-weight WEIGHT --bgp-peering-address IP ]') + def process_vnet_gateway_update_namespace(namespace): ns = namespace get_virtual_network_validator()(ns) @@ -567,8 +598,8 @@ def process_vnet_gateway_update_namespace(namespace): raise CLIError('Specify a single public IP to create an active-standby gateway or two ' 'public IPs to create an active-active gateway.') -def process_vpn_connection_create_namespace(namespace): +def process_vpn_connection_create_namespace(namespace): get_default_location_from_resource_group(namespace) args = [a for a in [namespace.express_route_circuit2, @@ -613,11 +644,13 @@ def _validate_name_or_id(namespace, value, resource_type): _validate_name_or_id(namespace, namespace.vnet_gateway2, 'virtualNetworkGateways') namespace.connection_type = 'Vnet2Vnet' + def load_cert_file(param_name): def load_cert_validator(namespace): attr = getattr(namespace, param_name) if attr and os.path.isfile(attr): setattr(namespace, param_name, read_base_64_file(attr)) + return load_cert_validator @@ -632,17 +665,15 @@ def get_network_watcher_from_vm(namespace): def get_network_watcher_from_resource(namespace): - from azure.cli.core.commands.arm import parse_resource_id - resource_client = get_mgmt_service_client(ResourceType.MGMT_RESOURCE_RESOURCES).resources resource = resource_client.get_by_id(namespace.resource, get_api_version(ResourceType.MGMT_NETWORK)) namespace.location = resource.location # pylint: disable=no-member get_network_watcher_from_location(remove=True)(namespace) + def get_network_watcher_from_location(remove=False, watcher_name='watcher_name', rg_name='watcher_rg'): - def _validator(namespace): from azure.cli.core.commands.arm import parse_resource_id @@ -662,13 +693,12 @@ def _validator(namespace): def process_nw_test_connectivity_namespace(namespace): - from azure.cli.core.commands.arm import parse_resource_id compute_client = get_mgmt_service_client(ResourceType.MGMT_COMPUTE).virtual_machines vm_name = parse_resource_id(namespace.source_resource)['name'] rg = namespace.resource_group_name or \ - parse_resource_id(namespace.source_resource).get('resource_group', None) + parse_resource_id(namespace.source_resource).get('resource_group', None) if not rg: raise CLIError('usage error: --source-resource ID | ' '--source-resource NAME --resource-group NAME') @@ -692,8 +722,8 @@ def process_nw_test_connectivity_namespace(namespace): type='virtualMachines', name=namespace.dest_resource) -def process_nw_flow_log_set_namespace(namespace): +def process_nw_flow_log_set_namespace(namespace): if namespace.storage_account and not is_valid_resource_id(namespace.storage_account): namespace.storage_account = resource_id( subscription=get_subscription_id(), @@ -704,8 +734,8 @@ def process_nw_flow_log_set_namespace(namespace): process_nw_flow_log_show_namespace(namespace) -def process_nw_flow_log_show_namespace(namespace): +def process_nw_flow_log_show_namespace(namespace): from azure.cli.core.commands.arm import parse_resource_id if not is_valid_resource_id(namespace.nsg): @@ -726,7 +756,6 @@ def process_nw_flow_log_show_namespace(namespace): def process_nw_topology_namespace(namespace): - location = namespace.location if not location: resource_client = \ @@ -739,7 +768,6 @@ def process_nw_topology_namespace(namespace): def process_nw_packet_capture_create_namespace(namespace): - get_network_watcher_from_vm(namespace) storage_usage = CLIError('usage error: --storage-account NAME_OR_ID [--storage-path ' @@ -773,8 +801,8 @@ def process_nw_packet_capture_create_namespace(namespace): file_path = file_path.replace('/', '\\') namespace.file_path = file_path -def process_nw_troubleshooting_start_namespace(namespace): +def process_nw_troubleshooting_start_namespace(namespace): storage_usage = CLIError('usage error: --storage-account NAME_OR_ID [--storage-path PATH]') if namespace.storage_path and not namespace.storage_account: raise storage_usage @@ -791,7 +819,6 @@ def process_nw_troubleshooting_start_namespace(namespace): def process_nw_troubleshooting_show_namespace(namespace): - resource_usage = CLIError('usage error: --resource ID | --resource NAME --resource-type TYPE ' '--resource-group-name NAME') id_params = [namespace.resource_type, namespace.resource_group_name] @@ -817,8 +844,9 @@ def process_nw_troubleshooting_show_namespace(namespace): # ACTIONS -class markSpecifiedAction(argparse.Action): # pylint: disable=too-few-public-methods +class markSpecifiedAction(argparse.Action): # pylint: disable=too-few-public-methods """ Use this to identify when a parameter is explicitly set by the user (as opposed to a default). You must remove the __SET__ sentinel substring in a follow-up validator.""" + def __call__(self, parser, args, values, option_string=None): setattr(args, self.dest, '__SET__{}'.format(values)) diff --git a/src/command_modules/azure-cli-network/azure/cli/command_modules/network/commands.py b/src/command_modules/azure-cli-network/azure/cli/command_modules/network/commands.py index 2bbc16b24ff..d718b48ea04 100644 --- a/src/command_modules/azure-cli-network/azure/cli/command_modules/network/commands.py +++ b/src/command_modules/azure-cli-network/azure/cli/command_modules/network/commands.py @@ -8,9 +8,19 @@ from azure.cli.core.commands.arm import cli_generic_update_command, cli_generic_wait_command from azure.cli.core.commands import \ (DeploymentOutputLongRunningOperation, cli_command) -from ._client_factory import * # pylint: disable=wildcard-import, unused-wildcard-import from azure.cli.core.util import empty_on_404 +from azure.cli.core.profiles import supported_api_version, ResourceType +from ._client_factory import (cf_application_gateways, cf_express_route_circuit_authorizations, + cf_express_route_circuit_peerings, cf_express_route_circuits, + cf_express_route_service_providers, cf_load_balancers, cf_local_network_gateways, + cf_network_interfaces, cf_network_security_groups, cf_network_watcher, cf_packet_capture, + cf_route_tables, cf_routes, cf_route_filter_rules, cf_route_filters, cf_virtual_networks, + cf_virtual_network_peerings, cf_virtual_network_gateway_connections, + cf_virtual_network_gateways, cf_traffic_manager_mgmt_endpoints, + cf_traffic_manager_mgmt_profiles, cf_dns_mgmt_record_sets, cf_dns_mgmt_zones, + cf_tm_geographic, cf_security_rules, cf_subnets, cf_usages, cf_service_community, + cf_public_ip_addresses) from ._util import (list_network_resource_property, get_network_resource_property_entry, delete_network_resource_property_entry) @@ -24,7 +34,6 @@ transform_vpn_connection_create_output, transform_geographic_hierachy_table_output, transform_service_community_table_output, transform_waf_rule_sets_table_output) -from azure.cli.core.profiles import supported_api_version, ResourceType custom_path = 'azure.cli.command_modules.network.custom#' diff --git a/src/command_modules/azure-cli-network/azure/cli/command_modules/network/custom.py b/src/command_modules/azure-cli-network/azure/cli/command_modules/network/custom.py index ec577da5313..10cb0b12b60 100644 --- a/src/command_modules/azure-cli-network/azure/cli/command_modules/network/custom.py +++ b/src/command_modules/azure-cli-network/azure/cli/command_modules/network/custom.py @@ -27,6 +27,7 @@ logger = azlogging.get_az_logger(__name__) + def _log_pprint_template(template): import json logger.info('==== BEGIN TEMPLATE ====') @@ -92,8 +93,8 @@ def _generic_list(operation_name, resource_group_name): operation_group = getattr(ncf, operation_name) if resource_group_name: return operation_group.list(resource_group_name) - else: - return operation_group.list_all() + + return operation_group.list_all() def list_vnet(resource_group_name=None): return _generic_list('virtual_networks', resource_group_name) @@ -140,7 +141,6 @@ def create_application_gateway(application_gateway_name, resource_group_name, lo virtual_network_name=None, vnet_address_prefix='10.0.0.0/16', public_ip_address_type=None, subnet_type=None, validate=False, connection_draining_timeout=0): - from azure.mgmt.resource import ResourceManagementClient from azure.cli.core.util import random_string from azure.cli.command_modules.network._template_builder import \ (ArmTemplateBuilder, build_application_gateway_resource, build_public_ip_resource, @@ -1436,10 +1436,10 @@ def clear_vpn_conn_ipsec_policies(resource_group_name, connection_name, no_wait= conn.use_policy_based_traffic_selectors = False if no_wait: return ncf.create_or_update(resource_group_name, connection_name, conn, raw=no_wait) - else: - from azure.cli.core.commands import LongRunningOperation - poller = ncf.create_or_update(resource_group_name, connection_name, conn, raw=no_wait) - return LongRunningOperation()(poller).ipsec_policies + + from azure.cli.core.commands import LongRunningOperation + poller = ncf.create_or_update(resource_group_name, connection_name, conn, raw=no_wait) + return LongRunningOperation()(poller).ipsec_policies def _validate_bgp_peering(instance, asn, bgp_peering_address, peer_weight): @@ -1805,23 +1805,25 @@ def update_route(instance, address_prefix=None, next_hop_type=None, next_hop_ip_ #region RouteFilter Commands + def create_route_filter(client, resource_group_name, route_filter_name, location=None, tags=None): RouteFilter = get_sdk(ResourceType.MGMT_NETWORK, 'RouteFilter', mod='models') return client.create_or_update(resource_group_name, route_filter_name, RouteFilter(location=location, tags=tags)) + def list_route_filters(client, resource_group_name=None): if resource_group_name: return client.list_by_resource_group(resource_group_name) - else: - return client.list() -def create_route_filter_rule(client, resource_group_name, route_filter_name, rule_name, access, - communities, location=None, tags=None): + return client.list() + + +def create_route_filter_rule(client, resource_group_name, route_filter_name, rule_name, access, communities, + location=None, tags=None): RouteFilterRule = get_sdk(ResourceType.MGMT_NETWORK, 'RouteFilterRule', mod='models') return client.create_or_update(resource_group_name, route_filter_name, rule_name, - RouteFilterRule(access, communities, - location=location, tags=tags)) + RouteFilterRule(access, communities, location=location, tags=tags)) #endregion @@ -1867,8 +1869,8 @@ def list_traffic_manager_profiles(resource_group_name=None): client = get_mgmt_service_client(TrafficManagerManagementClient).profiles if resource_group_name: return client.list_by_in_resource_group(resource_group_name) - else: - return client.list_all() + + return client.list_all() def create_traffic_manager_profile(traffic_manager_profile_name, resource_group_name, @@ -1977,8 +1979,8 @@ def list_dns_zones(resource_group_name=None): ncf = get_mgmt_service_client(DnsManagementClient).zones if resource_group_name: return ncf.list_by_resource_group(resource_group_name) - else: - return ncf.list() + + return ncf.list() def create_dns_record_set(resource_group_name, zone_name, record_set_name, record_set_type, metadata=None, if_match=None, if_none_match=None, ttl=3600): @@ -1992,8 +1994,8 @@ def create_dns_record_set(resource_group_name, zone_name, record_set_name, recor def list_dns_record_set(client, resource_group_name, zone_name, record_type=None): if record_type: return client.list_by_type(resource_group_name, zone_name, record_type) - else: - return client.list_by_dns_zone(resource_group_name, zone_name) + + return client.list_by_dns_zone(resource_group_name, zone_name) def update_dns_record_set(instance, metadata=None): if metadata is not None: @@ -2352,7 +2354,7 @@ def _add_save_record(record, record_type, record_set_name, resource_group_name, try: record_set = ncf.get(resource_group_name, zone_name, record_set_name, record_type) except CloudError: - record_set = RecordSet(name=record_set_name, type=record_type, ttl=3600) # pylint: disable=redefined-variable-type + record_set = RecordSet(name=record_set_name, type=record_type, ttl=3600) _add_record(record_set, record, record_type, is_list) @@ -2384,9 +2386,8 @@ def _remove_record(record, record_type, record_set_name, resource_group_name, zo if not records_remaining and not keep_empty_record_set: logger.info('Removing empty %s record set: %s', record_type, record_set_name) return ncf.delete(resource_group_name, zone_name, record_set_name, record_type) - else: - return ncf.create_or_update(resource_group_name, zone_name, record_set_name, - record_type, record_set) + + return ncf.create_or_update(resource_group_name, zone_name, record_set_name, record_type, record_set) def dict_matches_filter(d, filter_dict): sentinel = object() diff --git a/src/command_modules/azure-cli-profile/azure/cli/command_modules/profile/__init__.py b/src/command_modules/azure-cli-profile/azure/cli/command_modules/profile/__init__.py index 098cba1734f..6f52b2305a5 100644 --- a/src/command_modules/azure-cli-profile/azure/cli/command_modules/profile/__init__.py +++ b/src/command_modules/azure-cli-profile/azure/cli/command_modules/profile/__init__.py @@ -7,8 +7,8 @@ def load_params(_): - import azure.cli.command_modules.profile._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.profile._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.profile.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.profile.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-profile/azure/cli/command_modules/profile/custom.py b/src/command_modules/azure-cli-profile/azure/cli/command_modules/profile/custom.py index 8b49547e0ad..8720e191732 100644 --- a/src/command_modules/azure-cli-profile/azure/cli/command_modules/profile/custom.py +++ b/src/command_modules/azure-cli-profile/azure/cli/command_modules/profile/custom.py @@ -27,7 +27,8 @@ def list_subscriptions(all=False): # pylint: disable=redefined-builtin if not all: enabled_ones = [s for s in subscriptions if s['state'] == 'Enabled'] if len(enabled_ones) != len(subscriptions): - logger.warning("A few accounts are skipped as they don't have 'Enabled' state. Use '--all' to display them.") # pylint: disable=line-too-long + logger.warning("A few accounts are skipped as they don't have 'Enabled' state. " + "Use '--all' to display them.") subscriptions = enabled_ones return subscriptions @@ -36,10 +37,10 @@ def show_subscription(subscription=None, expanded_view=None): profile = Profile() if not expanded_view: return profile.get_subscription(subscription) - else: - logger.warning("'--expanded-view' is deprecating and will be removed in a future release. " - "You can get the same information using 'az cloud show'") - return profile.get_expanded_subscription_info(subscription) + + logger.warning("'--expanded-view' is deprecating and will be removed in a future release. You can get the same " + "information using 'az cloud show'") + return profile.get_expanded_subscription_info(subscription) def get_access_token(subscription=None, resource=None): diff --git a/src/command_modules/azure-cli-rdbms/azure/cli/command_modules/rdbms/__init__.py b/src/command_modules/azure-cli-rdbms/azure/cli/command_modules/rdbms/__init__.py index 9094ef37caf..753982ea222 100644 --- a/src/command_modules/azure-cli-rdbms/azure/cli/command_modules/rdbms/__init__.py +++ b/src/command_modules/azure-cli-rdbms/azure/cli/command_modules/rdbms/__init__.py @@ -9,8 +9,8 @@ def load_params(_): - import azure.cli.command_modules.rdbms.params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.rdbms.params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.rdbms.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.rdbms.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-rdbms/azure/cli/command_modules/rdbms/_util.py b/src/command_modules/azure-cli-rdbms/azure/cli/command_modules/rdbms/_util.py index 3d816131ec0..f22661bafe1 100644 --- a/src/command_modules/azure-cli-rdbms/azure/cli/command_modules/rdbms/_util.py +++ b/src/command_modules/azure-cli-rdbms/azure/cli/command_modules/rdbms/_util.py @@ -35,7 +35,7 @@ def get_mysql_management_client(_): tenant=getenv(TENANT_ID)) else: from msrest.authentication import Authentication - credentials = Authentication() # pylint: disable=redefined-variable-type + credentials = Authentication() return MySQLManagementClient( subscription_id=getenv(SUB_ID_OVERRIDE), @@ -64,7 +64,7 @@ def get_postgresql_management_client(_): tenant=getenv(TENANT_ID)) else: from msrest.authentication import Authentication - credentials = Authentication() # pylint: disable=redefined-variable-type + credentials = Authentication() return PostgreSQLManagementClient( subscription_id=getenv(SUB_ID_OVERRIDE), diff --git a/src/command_modules/azure-cli-rdbms/azure/cli/command_modules/rdbms/custom.py b/src/command_modules/azure-cli-rdbms/azure/cli/command_modules/rdbms/custom.py index 8aeff4e9294..7f25a8ae3e2 100644 --- a/src/command_modules/azure-cli-rdbms/azure/cli/command_modules/rdbms/custom.py +++ b/src/command_modules/azure-cli-rdbms/azure/cli/command_modules/rdbms/custom.py @@ -25,7 +25,7 @@ def _server_restore( if len(source_server.split('/')) == 1: from azure.cli.core.commands.client_factory import get_subscription_id from azure.mgmt.rdbms.mysql.operations.servers_operations import ServersOperations - provider = 'Microsoft.DBForMySQL' if isinstance(client, ServersOperations) else 'Microsoft.DBforPostgreSQL' # pylint: disable=line-too-long + provider = 'Microsoft.DBForMySQL' if isinstance(client, ServersOperations) else 'Microsoft.DBforPostgreSQL' source_server = resource_id(subscription=get_subscription_id(), resource_group=resource_group_name, namespace=provider, @@ -180,5 +180,4 @@ def _server_list_custom_func( if resource_group_name: return client.list_by_resource_group(resource_group_name) - else: - return client.list() + return client.list() diff --git a/src/command_modules/azure-cli-redis/azure/cli/command_modules/redis/__init__.py b/src/command_modules/azure-cli-redis/azure/cli/command_modules/redis/__init__.py index 0e9d308bcb8..5e58759021c 100644 --- a/src/command_modules/azure-cli-redis/azure/cli/command_modules/redis/__init__.py +++ b/src/command_modules/azure-cli-redis/azure/cli/command_modules/redis/__init__.py @@ -7,8 +7,8 @@ def load_params(_): - import azure.cli.command_modules.redis._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.redis._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.redis.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.redis.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-redis/azure/cli/command_modules/redis/_params.py b/src/command_modules/azure-cli-redis/azure/cli/command_modules/redis/_params.py index f7e51fc1569..05a01bbb382 100644 --- a/src/command_modules/azure-cli-redis/azure/cli/command_modules/redis/_params.py +++ b/src/command_modules/azure-cli-redis/azure/cli/command_modules/redis/_params.py @@ -23,7 +23,6 @@ class JsonString(dict): def __init__(self, value): super(JsonString, self).__init__() - import json if value[0] in ("'", '"') and value[-1] == value[0]: # Remove leading and trailing quotes for dos/cmd.exe users value = value[1:-1] @@ -34,7 +33,6 @@ def __init__(self, value): class ScheduleEntryList(list): def __init__(self, value): super(ScheduleEntryList, self).__init__() - import json if value[0] in ("'", '"') and value[-1] == value[0]: # Remove leading and trailing quotes for dos/cmd.exe users value = value[1:-1] diff --git a/src/command_modules/azure-cli-resource/azure/cli/command_modules/resource/__init__.py b/src/command_modules/azure-cli-resource/azure/cli/command_modules/resource/__init__.py index 8fbe92f9839..d776270eec9 100644 --- a/src/command_modules/azure-cli-resource/azure/cli/command_modules/resource/__init__.py +++ b/src/command_modules/azure-cli-resource/azure/cli/command_modules/resource/__init__.py @@ -7,8 +7,8 @@ def load_params(_): - import azure.cli.command_modules.resource._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.resource._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.resource.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.resource.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-resource/azure/cli/command_modules/resource/_validators.py b/src/command_modules/azure-cli-resource/azure/cli/command_modules/resource/_validators.py index 1a2adf96a9f..f2436813e37 100644 --- a/src/command_modules/azure-cli-resource/azure/cli/command_modules/resource/_validators.py +++ b/src/command_modules/azure-cli-resource/azure/cli/command_modules/resource/_validators.py @@ -51,7 +51,7 @@ def internal_validate_lock_parameters(resource_group_name, resource_provider_nam raise CLIError('--parent is ignored if --resource-name is not given.') return - if resource_type is None or len(resource_type) == 0: + if not resource_type: raise CLIError('--resource-type is required if --resource-name is present') parts = resource_type.split('/') diff --git a/src/command_modules/azure-cli-resource/azure/cli/command_modules/resource/custom.py b/src/command_modules/azure-cli-resource/azure/cli/command_modules/resource/custom.py index 43ffa571bae..764ff37736f 100644 --- a/src/command_modules/azure-cli-resource/azure/cli/command_modules/resource/custom.py +++ b/src/command_modules/azure-cli-resource/azure/cli/command_modules/resource/custom.py @@ -51,7 +51,7 @@ def list_resource_groups(tag=None): # pylint: disable=no-self-use filters.append("tagname eq '{}'".format(key)) filters.append("tagvalue eq '{}'".format(tag[key])) - filter_text = ' and '.join(filters) if len(filters) > 0 else None + filter_text = ' and '.join(filters) if filters else None groups = rcf.resource_groups.list(filter=filter_text) return list(groups) @@ -284,7 +284,7 @@ def _prompt_for_parameters(missing_parameters): else: value = prompt(prompt_str, help_string=description) result[param_name] = value - if len(value) > 0: + if value: break return result @@ -304,7 +304,7 @@ def _merge_parameters(parameter_list): def _get_missing_parameters(parameters, template, prompt_fn): missing = _find_missing_parameters(parameters, template) - if len(missing) > 0: + if missing: prompt_parameters = prompt_fn(missing) for param_name in prompt_parameters: parameters[param_name] = { @@ -342,11 +342,8 @@ def _deploy_arm_template_core(resource_group_name, # pylint: disable=too-many-a smc = get_mgmt_service_client(ResourceType.MGMT_RESOURCE_RESOURCES) if validate_only: - return smc.deployments.validate(resource_group_name, deployment_name, - properties, raw=no_wait) - else: - return smc.deployments.create_or_update(resource_group_name, deployment_name, - properties, raw=no_wait) + return smc.deployments.validate(resource_group_name, deployment_name, properties, raw=no_wait) + return smc.deployments.create_or_update(resource_group_name, deployment_name, properties, raw=no_wait) def export_deployment_as_template(resource_group_name, deployment_name): @@ -572,8 +569,7 @@ def move_resource(ids, destination_group, destination_subscription_id=None): def list_features(client, resource_provider_namespace=None): if resource_provider_namespace: return client.list(resource_provider_namespace=resource_provider_namespace) - else: - return client.list_all() + return client.list_all() def create_policy_assignment(policy, name=None, display_name=None, @@ -1051,27 +1047,25 @@ def get_resource(self): def delete(self): if self.resource_id: return self.rcf.resources.delete_by_id(self.resource_id, self.api_version) - else: - return self.rcf.resources.delete(self.resource_group_name, - self.resource_provider_namespace, - self.parent_resource_path or '', - self.resource_type, - self.resource_name, - self.api_version) + return self.rcf.resources.delete(self.resource_group_name, + self.resource_provider_namespace, + self.parent_resource_path or '', + self.resource_type, + self.resource_name, + self.api_version) def update(self, parameters): if self.resource_id: return self.rcf.resources.create_or_update_by_id(self.resource_id, self.api_version, parameters) - else: - return self.rcf.resources.create_or_update(self.resource_group_name, - self.resource_provider_namespace, - self.parent_resource_path or '', - self.resource_type, - self.resource_name, - self.api_version, - parameters) + return self.rcf.resources.create_or_update(self.resource_group_name, + self.resource_provider_namespace, + self.parent_resource_path or '', + self.resource_type, + self.resource_name, + self.api_version, + parameters) def tag(self, tags): resource = self.get_resource() @@ -1089,15 +1083,13 @@ def tag(self, tags): if self.resource_id: return self.rcf.resources.create_or_update_by_id(self.resource_id, self.api_version, parameters) - else: - return self.rcf.resources.create_or_update( - self.resource_group_name, - self.resource_provider_namespace, - self.parent_resource_path or '', - self.resource_type, - self.resource_name, - self.api_version, - parameters) + return self.rcf.resources.create_or_update(self.resource_group_name, + self.resource_provider_namespace, + self.parent_resource_path or '', + self.resource_type, + self.resource_name, + self.api_version, + parameters) @staticmethod def resolve_api_version(rcf, resource_provider_namespace, parent_resource_path, resource_type): diff --git a/src/command_modules/azure-cli-role/azure/cli/command_modules/role/__init__.py b/src/command_modules/azure-cli-role/azure/cli/command_modules/role/__init__.py index e024cc3156b..b689d29dc8f 100644 --- a/src/command_modules/azure-cli-role/azure/cli/command_modules/role/__init__.py +++ b/src/command_modules/azure-cli-role/azure/cli/command_modules/role/__init__.py @@ -7,8 +7,8 @@ def load_params(_): - import azure.cli.command_modules.role._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.role._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.role.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.role.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-role/azure/cli/command_modules/role/custom.py b/src/command_modules/azure-cli-role/azure/cli/command_modules/role/custom.py index 45b7ed5a1eb..af845e51c1d 100644 --- a/src/command_modules/azure-cli-role/azure/cli/command_modules/role/custom.py +++ b/src/command_modules/azure-cli-role/azure/cli/command_modules/role/custom.py @@ -199,8 +199,7 @@ def _get_displayable_name(graph_object): return graph_object.user_principal_name elif graph_object.service_principal_names: return graph_object.service_principal_names[0] - else: - return '' + return '' def delete_role_assignments(ids=None, assignee=None, role=None, @@ -435,7 +434,7 @@ def _build_application_creds(password=None, key_value=None, key_type=None, if not end_date: end_date = start_date + relativedelta(years=1) elif isinstance(end_date, str): - end_date = dateutil.parser.parse(end_date) # pylint: disable=redefined-variable-type + end_date = dateutil.parser.parse(end_date) key_type = key_type or 'AsymmetricX509Cert' key_usage = key_usage or 'Verify' @@ -565,7 +564,6 @@ def create_service_principal_for_rbac( create_cert=False, cert=None, scopes=None, role='Contributor', expanded_view=None, skip_assignment=False, keyvault=None): - from azure.graphrbac.models import GraphErrorException import time import pytz @@ -689,11 +687,9 @@ def _get_token(server, resource, scope): # pylint: disable=unused-argument def _create_self_signed_cert(start_date, end_date): # pylint: disable=too-many-locals - import base64 from os import path import tempfile - import time - from OpenSSL import crypto, SSL + from OpenSSL import crypto from datetime import timedelta _, cert_file = tempfile.mkstemp() @@ -744,11 +740,7 @@ def _create_self_signed_cert(start_date, end_date): # pylint: disable=too-many- def _create_self_signed_cert_with_keyvault(years, keyvault, keyvault_cert_name): # pylint: disable=too-many-locals from azure.cli.core._profile import CLOUD import base64 - from os import path - import tempfile import time - from OpenSSL import crypto, SSL - from datetime import timedelta kv_client = _get_keyvault_client() cert_policy = { @@ -895,8 +887,7 @@ def reset_service_principal_credential(name, password=None, create_cert=False, ) ] - app_create_param = ApplicationUpdateParameters(password_credentials=app_creds, - key_credentials=cert_creds) + app_create_param = ApplicationUpdateParameters(password_credentials=app_creds, key_credentials=cert_creds) client.applications.patch(app.object_id, app_create_param) @@ -920,7 +911,6 @@ def _resolve_object_id(assignee): result = list(client.service_principals.list( filter="servicePrincipalNames/any(c:c eq '{}')".format(assignee))) if not result: # assume an object id, let us verify it - from azure.graphrbac.models import GetObjectsParameters result = _get_object_stubs(client, [assignee]) # 2+ matches should never happen, so we only check 'no match' here @@ -932,6 +922,5 @@ def _resolve_object_id(assignee): def _get_object_stubs(graph_client, assignees): from azure.graphrbac.models import GetObjectsParameters - params = GetObjectsParameters(include_directory_object_references=True, - object_ids=assignees) + params = GetObjectsParameters(include_directory_object_references=True, object_ids=assignees) return list(graph_client.objects.get_objects_by_object_ids(params)) diff --git a/src/command_modules/azure-cli-sf/azure/cli/command_modules/sf/__init__.py b/src/command_modules/azure-cli-sf/azure/cli/command_modules/sf/__init__.py index 3cfaf7f30a2..52e34766e6e 100644 --- a/src/command_modules/azure-cli-sf/azure/cli/command_modules/sf/__init__.py +++ b/src/command_modules/azure-cli-sf/azure/cli/command_modules/sf/__init__.py @@ -6,10 +6,8 @@ def load_params(_): - # pylint: disable=redefined-outer-name - import azure.cli.command_modules.sf._params + import azure.cli.command_modules.sf._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - # pylint: disable=redefined-outer-name - import azure.cli.command_modules.sf.commands + import azure.cli.command_modules.sf.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-sf/azure/cli/command_modules/sf/custom.py b/src/command_modules/azure-cli-sf/azure/cli/command_modules/sf/custom.py index 3ac8c26bb98..f8250beed47 100644 --- a/src/command_modules/azure-cli-sf/azure/cli/command_modules/sf/custom.py +++ b/src/command_modules/azure-cli-sf/azure/cli/command_modules/sf/custom.py @@ -13,10 +13,8 @@ try: from urllib.parse import urlparse, urlencode, urlunparse except ImportError: - # pylint: disable=import-error - from urlparse import urlparse, urlunparse - # pylint: disable=no-name-in-module - from urllib import urlencode + from urlparse import urlparse, urlunparse # pylint: disable=import-error + from urllib import urlencode # pylint: disable=no-name-in-module, ungrouped-imports import requests import azure.cli.core.azlogging as azlogging @@ -575,20 +573,16 @@ def sup_load_metrics(formatted_metrics): def sup_placement_policies(formatted_placement_policies): - # pylint: disable=line-too-long - from azure.servicefabric.models.service_placement_non_partially_place_service_policy_description import ( # noqa: justification, no way to shorten + from azure.servicefabric.models.service_placement_non_partially_place_service_policy_description import ( ServicePlacementNonPartiallyPlaceServicePolicyDescription ) - # pylint: disable=line-too-long - from azure.servicefabric.models.service_placement_prefer_primary_domain_policy_description import ( # noqa: justification, no way to shorten + from azure.servicefabric.models.service_placement_prefer_primary_domain_policy_description import ( ServicePlacementPreferPrimaryDomainPolicyDescription ) - # pylint: disable=line-too-long - from azure.servicefabric.models.service_placement_required_domain_policy_description import ( # noqa: justification, no way to shorten + from azure.servicefabric.models.service_placement_required_domain_policy_description import ( ServicePlacementRequiredDomainPolicyDescription ) - # pylint: disable=line-too-long - from azure.servicefabric.models.service_placement_require_domain_distribution_policy_description import ( # noqa: justification, no way to shorten + from azure.servicefabric.models.service_placement_require_domain_distribution_policy_description import ( ServicePlacementRequireDomainDistributionPolicyDescription ) @@ -606,32 +600,19 @@ def sup_placement_policies(formatted_placement_policies): "RequireDomainDistribution"]: raise CLIError("Invalid type of placement policy specified") p_domain_name = p.get("domain_name", None) - if ( - p_domain_name is None and - p_type != "NonPartiallyPlaceService" - ): - raise CLIError( - "Placement policy type requires target domain name" - ) + + if p_domain_name is None and p_type != "NonPartiallyPlaceService": + raise CLIError("Placement policy type requires target domain name") if p_type == "NonPartiallyPlaceService": - r.append( - ServicePlacementNonPartiallyPlaceServicePolicyDescription() - ) + r.append(ServicePlacementNonPartiallyPlaceServicePolicyDescription()) elif p_type == "PreferPrimaryDomain": - r.append( - ServicePlacementPreferPrimaryDomainPolicyDescription(p_domain_name) # noqa: justification, no way to shorten - ) + r.append(ServicePlacementPreferPrimaryDomainPolicyDescription(p_domain_name)) elif p_type == "RequireDomain": - r.append( - ServicePlacementRequiredDomainPolicyDescription(p_domain_name) # noqa: justification, no way to shorten - ) + r.append(ServicePlacementRequiredDomainPolicyDescription(p_domain_name)) elif p_type == "RequireDomainDistribution": - r.append( - ServicePlacementRequireDomainDistributionPolicyDescription(p_domain_name) # noqa: justification, no way to shorten - ) + r.append(ServicePlacementRequireDomainDistributionPolicyDescription(p_domain_name)) return r - else: - return None + return None def sup_validate_move_cost(move_cost): @@ -825,14 +806,12 @@ def sf_create_service( # pylint: disable=too-many-arguments, too-many-locals part_schema = NamedPartitionSchemeDescription(len(named_scheme_list), named_scheme_list) elif int_scheme: - # pylint: disable=redefined-variable-type part_schema = UniformInt64RangePartitionSchemeDescription( int_scheme_count, int_scheme_low, int_scheme_high ) else: - # pylint: disable=redefined-variable-type part_schema = SingletonPartitionSchemeDescription() # correlation scheme correlation_desc = sup_correlation_scheme(correlated_service, @@ -873,7 +852,6 @@ def sf_create_service( # pylint: disable=too-many-arguments, too-many-locals if stateful: flags = sup_stateful_flags(replica_restart_wait, quorum_loss_wait, stand_by_replica_keep) - # pylint: disable=redefined-variable-type svc_desc = StatefulServiceDescription(name, service_type, part_schema, target_replica_set_size, @@ -1016,7 +994,6 @@ def sf_update_service(client, service_id, if stand_by_replica_keep is not None: raise CLIError("Cannot specify standby replica keep duration for " "stateless service") - # pylint: disable=redefined-variable-type update_desc = StatelessServiceUpdateDescription(flags, constraints, correlation_desc, load_list, diff --git a/src/command_modules/azure-cli-sql/azure/cli/command_modules/sql/__init__.py b/src/command_modules/azure-cli-sql/azure/cli/command_modules/sql/__init__.py index 7477cac8250..dcce1e7c47e 100644 --- a/src/command_modules/azure-cli-sql/azure/cli/command_modules/sql/__init__.py +++ b/src/command_modules/azure-cli-sql/azure/cli/command_modules/sql/__init__.py @@ -9,8 +9,8 @@ def load_params(_): - import azure.cli.command_modules.sql.params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.sql.params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.sql.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.sql.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-sql/azure/cli/command_modules/sql/_util.py b/src/command_modules/azure-cli-sql/azure/cli/command_modules/sql/_util.py index bb33efe6220..a4d594bd903 100644 --- a/src/command_modules/azure-cli-sql/azure/cli/command_modules/sql/_util.py +++ b/src/command_modules/azure-cli-sql/azure/cli/command_modules/sql/_util.py @@ -19,9 +19,9 @@ def get_sql_management_client(_): subscription_id=getenv('_AZURE_CLI_SQL_SUB_ID'), base_url=sql_rm_override, credentials=Authentication()) # No authentication - else: - # Normal production scenario. - return get_mgmt_service_client(SqlManagementClient) + + # Normal production scenario. + return get_mgmt_service_client(SqlManagementClient) def get_sql_servers_operations(kwargs): diff --git a/src/command_modules/azure-cli-sql/azure/cli/command_modules/sql/commands.py b/src/command_modules/azure-cli-sql/azure/cli/command_modules/sql/commands.py index 6b77d03eb30..4c9a9c862b7 100644 --- a/src/command_modules/azure-cli-sql/azure/cli/command_modules/sql/commands.py +++ b/src/command_modules/azure-cli-sql/azure/cli/command_modules/sql/commands.py @@ -3,14 +3,14 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- +from azure.cli.core.sdk.util import ( + create_service_adapter, + ServiceGroup) from ._util import ( get_sql_servers_operations, get_sql_firewall_rules_operations, get_sql_databases_operations, get_sql_elastic_pools_operations) -from azure.cli.core.sdk.util import ( - create_service_adapter, - ServiceGroup) custom_path = 'azure.cli.command_modules.sql.custom#{}' diff --git a/src/command_modules/azure-cli-sql/azure/cli/command_modules/sql/custom.py b/src/command_modules/azure-cli-sql/azure/cli/command_modules/sql/custom.py index 92f29716e8d..5d7ff101cce 100644 --- a/src/command_modules/azure-cli-sql/azure/cli/command_modules/sql/custom.py +++ b/src/command_modules/azure-cli-sql/azure/cli/command_modules/sql/custom.py @@ -3,11 +3,6 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -from ._util import ( - get_sql_servers_operations, - get_sql_elastic_pools_operations -) - from azure.cli.core.commands.client_factory import ( get_mgmt_service_client, get_subscription_id) @@ -27,6 +22,11 @@ # url parse package has different names in Python 2 and 3. 'six' package works cross-version. from six.moves.urllib.parse import (quote, urlparse) # pylint: disable=import-error +from ._util import ( + get_sql_servers_operations, + get_sql_elastic_pools_operations +) + ############################################### # Common funcs # ############################################### @@ -212,7 +212,7 @@ def db_failover( server_name=server_name, resource_group_name=resource_group_name)) - if len(links) == 0: + if not links: raise CLIError('The specified database has no replication links.') # If a replica is primary, then it has 1 or more links (to its secondaries). @@ -343,11 +343,9 @@ def db_list( resource_group_name=resource_group_name, elastic_pool_name=elastic_pool_name, filter=filter) - else: + # List all databases in the server - return client.list_by_server( - resource_group_name=resource_group_name, - server_name=server_name) + return client.list_by_server(resource_group_name=resource_group_name, server_name=server_name) # Update database. Custom update function to apply parameters to instance. @@ -420,7 +418,7 @@ def _find_storage_account_resource_group(name): client = get_mgmt_service_client(ResourceManagementClient) resources = list(client.resources.list(filter=query)) - if len(resources) == 0: + if not resources: raise CLIError("No storage account with name '{}' was found.".format(name)) if len(resources) > 1: diff --git a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/__init__.py b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/__init__.py index c209f13fa14..375e9630bfb 100644 --- a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/__init__.py +++ b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/__init__.py @@ -7,8 +7,8 @@ def load_params(_): - import azure.cli.command_modules.storage._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.storage._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.storage.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.storage.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/_validators.py b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/_validators.py index 0c062510791..f829e3f7a4d 100644 --- a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/_validators.py +++ b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/_validators.py @@ -326,13 +326,13 @@ def validator(namespace): container = ns.get('container_name') blob = ns.get('blob_name') lease_id = ns.get('lease_id') - props = client.get_blob_properties(container, blob, lease_id=lease_id).properties.content_settings # pylint: disable=line-too-long + props = client.get_blob_properties(container, blob, lease_id=lease_id).properties.content_settings elif _class_name(settings_class) == _class_name(FileContentSettings): - client = get_storage_data_service_client(FileService, account, key, cs, sas) # pylint: disable=redefined-variable-type + client = get_storage_data_service_client(FileService, account, key, cs, sas) share = ns.get('share_name') directory = ns.get('directory_name') filename = ns.get('file_name') - props = client.get_file_properties(share, directory, filename).properties.content_settings # pylint: disable=line-too-long + props = client.get_file_properties(share, directory, filename).properties.content_settings # create new properties new_props = settings_class( @@ -772,8 +772,8 @@ def datetime_type(string): try: if to_string: return datetime.strptime(string, form).strftime(form) - else: - return datetime.strptime(string, form) + + return datetime.strptime(string, form) except ValueError: continue raise ValueError("Input '{}' not valid. Valid example: 2000-12-31T12:59:59Z".format(string)) diff --git a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/blob.py b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/blob.py index c7faa7dc528..5f09afc7103 100644 --- a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/blob.py +++ b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/blob.py @@ -121,9 +121,8 @@ def storage_blob_download_batch(client, source, destination, source_container_na for b in source_blobs or []: logger.warning(' - %s', b) return [] - else: - return list(_download_blob(client, source_container_name, destination, blob) for blob in - source_blobs) + + return list(_download_blob(client, source_container_name, destination, blob) for blob in source_blobs) def storage_blob_upload_batch(client, source, destination, pattern=None, source_files=None, diff --git a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/custom.py b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/custom.py index 4c14462afc9..e02d52bb9c5 100644 --- a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/custom.py +++ b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/custom.py @@ -118,8 +118,8 @@ def list_share_files(client, share_name, directory_name=None, timeout=None, timeout=timeout) if exclude_dir: return list(f for f in generator if isinstance(f.properties, FileProperties)) - else: - return generator + + return generator @transfer_doc(FileService.list_directories_and_files) diff --git a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/storage_url_helpers.py b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/storage_url_helpers.py index c861168fce8..bd38ff9624a 100644 --- a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/storage_url_helpers.py +++ b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/storage_url_helpers.py @@ -71,14 +71,14 @@ def _separate_path(cls, path, find_method): return None, None path = path.lstrip('/') - if len(path) == 0: + if not path: return None, None idx = find_method(path) if idx == -1: return path, None - else: - return path[:idx], path[idx + 1:] + + return path[:idx], path[idx + 1:] def is_url(self): return self._is_url diff --git a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/util.py b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/util.py index 9eb34b24a7e..13329a97a03 100644 --- a/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/util.py +++ b/src/command_modules/azure-cli-storage/azure/cli/command_modules/storage/util.py @@ -26,9 +26,8 @@ def collect_blobs(blob_service, container, pattern=None): if not _pattern_has_wildcards(pattern): return [pattern] - else: - return (blob.name for blob in blob_service.list_blobs(container) - if _match_path(pattern, blob.name)) + + return (blob.name for blob in blob_service.list_blobs(container) if _match_path(pattern, blob.name)) def collect_files(file_service, share, pattern=None): @@ -89,7 +88,7 @@ def glob_files_remotely(client, share_name, pattern): 'file.models#File') queue = deque([""]) - while len(queue) > 0: + while queue: current_dir = queue.pop() for f in client.list_directories_and_files(share_name, current_dir): if isinstance(f, File): @@ -142,7 +141,4 @@ def _pattern_has_wildcards(p): def _match_path(pattern, *args): - if not pattern: - return True - else: - return fnmatch(os.path.join(*args), pattern) + return fnmatch(os.path.join(*args), pattern) if pattern else True diff --git a/src/command_modules/azure-cli-taskhelp/azure/cli/command_modules/taskhelp/__init__.py b/src/command_modules/azure-cli-taskhelp/azure/cli/command_modules/taskhelp/__init__.py index 031045c9cc7..6c1cba4aa0d 100644 --- a/src/command_modules/azure-cli-taskhelp/azure/cli/command_modules/taskhelp/__init__.py +++ b/src/command_modules/azure-cli-taskhelp/azure/cli/command_modules/taskhelp/__init__.py @@ -12,4 +12,4 @@ def load_params(_): def load_commands(): - import azure.cli.command_modules.taskhelp.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.taskhelp.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-taskhelp/azure/cli/command_modules/taskhelp/commands.py b/src/command_modules/azure-cli-taskhelp/azure/cli/command_modules/taskhelp/commands.py index ec27bc7a190..5033cff3a14 100644 --- a/src/command_modules/azure-cli-taskhelp/azure/cli/command_modules/taskhelp/commands.py +++ b/src/command_modules/azure-cli-taskhelp/azure/cli/command_modules/taskhelp/commands.py @@ -5,5 +5,4 @@ from azure.cli.core.commands import cli_command -cli_command(__name__, 'taskhelp deploy-arm-template', - 'azure.cli.command_modules.taskhelp.custom#deploy_arm_template') +cli_command(__name__, 'taskhelp deploy-arm-template', 'azure.cli.command_modules.taskhelp.custom#deploy_arm_template') diff --git a/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/__init__.py b/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/__init__.py index d38a22c4d35..d332840d0ba 100644 --- a/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/__init__.py +++ b/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/__init__.py @@ -7,8 +7,8 @@ def load_params(_): - import azure.cli.command_modules.vm._params # pylint: disable=redefined-outer-name + import azure.cli.command_modules.vm._params # pylint: disable=redefined-outer-name, unused-variable def load_commands(): - import azure.cli.command_modules.vm.commands # pylint: disable=redefined-outer-name + import azure.cli.command_modules.vm.commands # pylint: disable=redefined-outer-name, unused-variable diff --git a/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/_template_builder.py b/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/_template_builder.py index bacb86e133d..8a061bdf1b1 100644 --- a/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/_template_builder.py +++ b/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/_template_builder.py @@ -77,7 +77,6 @@ class StorageProfile(Enum): def build_deployment_resource(name, template, dependencies=None): - from azure.cli.core.util import random_string dependencies = dependencies or [] deployment = { 'name': name, diff --git a/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/_validators.py b/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/_validators.py index 0a0861a0e73..5563fa83462 100644 --- a/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/_validators.py +++ b/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/_validators.py @@ -13,10 +13,10 @@ from azure.cli.core.commands.validators import \ (get_default_location_from_resource_group, validate_file_or_dict) from azure.cli.core.util import CLIError, random_string -from ._client_factory import _compute_client_factory from azure.cli.command_modules.vm._vm_utils import check_existence from azure.cli.command_modules.vm._template_builder import StorageProfile import azure.cli.core.azlogging as azlogging +from ._client_factory import _compute_client_factory logger = azlogging.get_az_logger(__name__) @@ -46,13 +46,9 @@ def _get_resource_id(val, resource_group, resource_type, resource_namespace): from azure.cli.core.commands.client_factory import get_subscription_id if is_valid_resource_id(val): return val - else: - return resource_id( - name=val, - resource_group=resource_group, - namespace=resource_namespace, - type=resource_type, - subscription=get_subscription_id()) + + return resource_id(name=val, resource_group=resource_group, namespace=resource_namespace, type=resource_type, + subscription=get_subscription_id()) def _get_nic_id(val, resource_group): @@ -162,7 +158,7 @@ def _parse_image_argument(namespace): namespace.os_sku, top=1, orderby='name desc') - if len(top_one) == 0: + if not top_one: raise CLIError("Can't resolve the vesion of '{}'".format(namespace.image)) image_version = top_one[0].name @@ -274,7 +270,7 @@ def _validate_managed_disk_sku(sku): raise CLIError("invalid storage SKU '{}': allowed values: '{}'".format(sku, allowed_skus)) -# pylint: disable=too-many-branches, too-many-statements, redefined-variable-type +# pylint: disable=too-many-branches, too-many-statements def _validate_vm_create_storage_profile(namespace, for_scale_set=False): # use minimal parameters to resolve the expected storage profile diff --git a/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/custom.py b/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/custom.py index 76bcd1c3450..dd159055901 100644 --- a/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/custom.py +++ b/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/custom.py @@ -36,16 +36,11 @@ logger = azlogging.get_az_logger(__name__) -VirtualHardDisk, VirtualMachineScaleSet, \ - VirtualMachineCaptureParameters, VirtualMachineScaleSetExtension, \ - VirtualMachineScaleSetExtensionProfile = get_sdk( - ResourceType.MGMT_COMPUTE, - 'VirtualHardDisk', - 'VirtualMachineScaleSet', - 'VirtualMachineCaptureParameters', - 'VirtualMachineScaleSetExtension', - 'VirtualMachineScaleSetExtensionProfile', - mod='models') +VirtualHardDisk, VirtualMachineScaleSet, VirtualMachineCaptureParameters, VirtualMachineScaleSetExtension, \ + VirtualMachineScaleSetExtensionProfile = get_sdk(ResourceType.MGMT_COMPUTE, 'VirtualHardDisk', + 'VirtualMachineScaleSet', 'VirtualMachineCaptureParameters', + 'VirtualMachineScaleSetExtension', + 'VirtualMachineScaleSetExtensionProfile', mod='models') def get_resource_group_location(resource_group_name): @@ -73,8 +68,8 @@ def set_vm(instance, lro_operation=None, no_wait=False): parameters=instance, raw=no_wait) if lro_operation: return lro_operation(poller) - else: - return LongRunningOperation()(poller) + + return LongRunningOperation()(poller) def _parse_rg_name(strid): @@ -159,15 +154,12 @@ def list_vm(resource_group_name=None, show_details=False): if resource_group_name else ccf.virtual_machines.list_all() if show_details: return [get_vm_details(_parse_rg_name(v.id)[0], v.name) for v in vm_list] - else: - return list(vm_list) + + return list(vm_list) def show_vm(resource_group_name, vm_name, show_details=False): - if show_details: - return get_vm_details(resource_group_name, vm_name) - else: - return get_vm(resource_group_name, vm_name) + return get_vm_details(resource_group_name, vm_name) if show_details else get_vm(resource_group_name, vm_name) def get_vm_details(resource_group_name, vm_name): @@ -194,7 +186,8 @@ def get_vm_details(resource_group_name, vm_name): if public_ip_info.dns_settings: fqdns.append(public_ip_info.dns_settings.fqdn) - setattr(result, 'power_state', ','.join([s.display_status for s in result.instance_view.statuses if s.code.startswith('PowerState/')])) + setattr(result, 'power_state', + ','.join([s.display_status for s in result.instance_view.statuses if s.code.startswith('PowerState/')])) setattr(result, 'public_ips', ','.join(public_ips)) setattr(result, 'fqdns', ','.join(fqdns)) setattr(result, 'private_ips', ','.join(private_ips)) @@ -262,10 +255,10 @@ def list_ip_addresses(resource_group_name=None, vm_name=None): # If provided, make sure that resource group name and vm name match the NIC we are # looking at before adding it to the result... - same_resource_group_name = resource_group_name is None or \ - resource_group_name.lower() == nic_resource_group.lower() - same_vm_name = vm_name is None or \ - vm_name.lower() == nic_vm_name.lower() + same_resource_group_name = (resource_group_name is None or + resource_group_name.lower() == nic_resource_group.lower()) + same_vm_name = (vm_name is None or + vm_name.lower() == nic_vm_name.lower()) if same_resource_group_name and same_vm_name: network_info = { 'privateIpAddresses': [], @@ -299,12 +292,12 @@ def create_managed_disk(resource_group_name, disk_name, location=None, # below are generated internally from 'source' source_blob_uri=None, source_disk=None, source_snapshot=None, source_storage_account_id=None, no_wait=False): - from azure.mgmt.compute.models import Disk, CreationData, DiskCreateOption, ImageDiskReference + from azure.mgmt.compute.models import Disk, CreationData, DiskCreateOption location = location or get_resource_group_location(resource_group_name) if source_blob_uri: option = DiskCreateOption.import_enum elif source_disk or source_snapshot: - option = DiskCreateOption.copy # pylint: disable=redefined-variable-type + option = DiskCreateOption.copy else: option = DiskCreateOption.empty @@ -334,8 +327,8 @@ def attach_managed_data_disk(resource_group_name, vm_name, disk, new=False, sku=None, size_gb=None, lun=None, caching=None): '''attach a managed disk''' vm = get_vm(resource_group_name, vm_name) - from azure.mgmt.compute.models import (CreationData, DiskCreateOptionTypes, - ManagedDiskParameters, DataDisk) + from azure.mgmt.compute.models import DiskCreateOptionTypes, ManagedDiskParameters, DataDisk + # pylint: disable=no-member if lun is None: luns = ([d.lun for d in vm.storage_profile.data_disks] @@ -404,19 +397,17 @@ def grant_disk_access(resource_group_name, disk_name, duration_in_seconds): return _grant_access(resource_group_name, disk_name, duration_in_seconds, True) -def create_snapshot(resource_group_name, snapshot_name, location=None, - size_gb=None, sku='Standard_LRS', +def create_snapshot(resource_group_name, snapshot_name, location=None, size_gb=None, sku='Standard_LRS', source=None, # pylint: disable=unused-argument # below are generated internally from 'source' - source_blob_uri=None, source_disk=None, source_snapshot=None, - source_storage_account_id=None): - from azure.mgmt.compute.models import (Snapshot, CreationData, DiskCreateOption, - ImageDiskReference) + source_blob_uri=None, source_disk=None, source_snapshot=None, source_storage_account_id=None): + from azure.mgmt.compute.models import Snapshot, CreationData, DiskCreateOption + location = location or get_resource_group_location(resource_group_name) if source_blob_uri: option = DiskCreateOption.import_enum elif source_disk or source_snapshot: - option = DiskCreateOption.copy # pylint: disable=redefined-variable-type + option = DiskCreateOption.copy else: option = DiskCreateOption.empty @@ -444,16 +435,16 @@ def list_managed_disks(resource_group_name=None): client = _compute_client_factory() if resource_group_name: return client.disks.list_by_resource_group(resource_group_name) - else: - return client.disks.list() + + return client.disks.list() def list_snapshots(resource_group_name=None): client = _compute_client_factory() if resource_group_name: return client.snapshots.list_by_resource_group(resource_group_name) - else: - return client.snapshots.list() + + return client.snapshots.list() def grant_snapshot_access(resource_group_name, snapshot_name, duration_in_seconds): @@ -471,19 +462,18 @@ def list_images(resource_group_name=None): client = _compute_client_factory() if resource_group_name: return client.images.list_by_resource_group(resource_group_name) - else: - return client.images.list() + + return client.images.list() -def create_image(resource_group_name, name, os_type=None, location=None, # pylint: disable=too-many-locals,line-too-long +def create_image(resource_group_name, name, os_type=None, location=None, # pylint: disable=too-many-locals source=None, data_disk_sources=None, # pylint: disable=unused-argument # below are generated internally from 'source' and 'data_disk_sources' source_virtual_machine=None, os_blob_uri=None, data_blob_uris=None, os_snapshot=None, data_snapshots=None, os_disk=None, data_disks=None): - from azure.mgmt.compute.models import (ImageOSDisk, ImageDataDisk, ImageStorageProfile, Image, - OperatingSystemTypes, SubResource, + from azure.mgmt.compute.models import (ImageOSDisk, ImageDataDisk, ImageStorageProfile, Image, SubResource, OperatingSystemStateTypes) # pylint: disable=line-too-long if source_virtual_machine: @@ -558,8 +548,8 @@ def _get_disk_lun(data_disks): if existing_luns[i] != i: return i return len(existing_luns) - else: - return 0 + + return 0 def resize_vm(resource_group_name, vm_name, size, no_wait=False): @@ -746,9 +736,7 @@ def _get_extension_instance_name(instance_view, publisher, extension_type_name, def disable_boot_diagnostics(resource_group_name, vm_name): vm = get_vm(resource_group_name, vm_name) diag_profile = vm.diagnostics_profile - if not (diag_profile and - diag_profile.boot_diagnostics and - diag_profile.boot_diagnostics.enabled): + if not (diag_profile and diag_profile.boot_diagnostics and diag_profile.boot_diagnostics.enabled): return # Issue: https://github.com/Azure/autorest/issues/934 @@ -927,7 +915,8 @@ def set_vmss_extension( if extension_profile: extensions = extension_profile.extensions if extensions: - extension_profile.extensions = [x for x in extensions if x.type.lower() != extension_name.lower() or x.publisher.lower() != publisher.lower()] # pylint: disable=line-too-long + extension_profile.extensions = [x for x in extensions if + x.type.lower() != extension_name.lower() or x.publisher.lower() != publisher.lower()] # pylint: disable=line-too-long ext = VirtualMachineScaleSetExtension(name=extension_name, publisher=publisher, @@ -948,11 +937,9 @@ def set_vmss_extension( def _normalize_extension_version(publisher, vm_extension_name, version, location): if not version: - result = load_extension_images_thru_services(publisher, vm_extension_name, - None, location, show_latest=True) + result = load_extension_images_thru_services(publisher, vm_extension_name, None, location, show_latest=True) if not result: - raise CLIError('Failed to find the latest version for the extension "{}"' - .format(vm_extension_name)) + raise CLIError('Failed to find the latest version for the extension "{}"'.format(vm_extension_name)) # with 'show_latest' enabled, we will only get one result. version = result[0]['version'] @@ -1095,7 +1082,8 @@ def vm_show_nic(resource_group_name, vm_name, nic): ''' Show details of a network interface configuration attached to a virtual machine ''' vm = get_vm(resource_group_name, vm_name) found = next( - (n for n in vm.network_profile.network_interfaces if nic.lower() == n.id.lower()), None # pylint: disable=no-member + (n for n in vm.network_profile.network_interfaces if nic.lower() == n.id.lower()), None + # pylint: disable=no-member ) if found: network_client = get_mgmt_service_client(ResourceType.MGMT_NETWORK) @@ -1317,17 +1305,13 @@ def get_vmss_instance_view(resource_group_name, vm_scale_set_name, instance_id=N client = _compute_client_factory() if instance_id: if instance_id == '*': - return client.virtual_machine_scale_set_vms.list(resource_group_name, - vm_scale_set_name, - select='instanceView', - expand='instanceView') - else: - return client.virtual_machine_scale_set_vms.get_instance_view(resource_group_name, - vm_scale_set_name, - instance_id) - else: - return client.virtual_machine_scale_sets.get_instance_view(resource_group_name, - vm_scale_set_name) + return client.virtual_machine_scale_set_vms.list(resource_group_name, vm_scale_set_name, + select='instanceView', expand='instanceView') + + return client.virtual_machine_scale_set_vms.get_instance_view(resource_group_name, vm_scale_set_name, + instance_id) + + return client.virtual_machine_scale_sets.get_instance_view(resource_group_name, vm_scale_set_name) def show_vmss(resource_group_name, vm_scale_set_name, instance_id=None): @@ -1337,12 +1321,9 @@ def show_vmss(resource_group_name, vm_scale_set_name, instance_id=None): ''' client = _compute_client_factory() if instance_id: - return client.virtual_machine_scale_set_vms.get(resource_group_name, - vm_scale_set_name, - instance_id) - else: - return client.virtual_machine_scale_sets.get(resource_group_name, - vm_scale_set_name) + return client.virtual_machine_scale_set_vms.get(resource_group_name, vm_scale_set_name, instance_id) + + return client.virtual_machine_scale_sets.get(resource_group_name, vm_scale_set_name) def list_vmss(resource_group_name=None): @@ -1350,53 +1331,41 @@ def list_vmss(resource_group_name=None): client = _compute_client_factory() if resource_group_name: return client.virtual_machine_scale_sets.list(resource_group_name) - else: - return client.virtual_machine_scale_sets.list_all() + + return client.virtual_machine_scale_sets.list_all() def deallocate_vmss(resource_group_name, vm_scale_set_name, instance_ids=None, no_wait=False): '''deallocate virtual machines in a scale set. ''' client = _compute_client_factory() if instance_ids and len(instance_ids) == 1: - return client.virtual_machine_scale_set_vms.deallocate(resource_group_name, - vm_scale_set_name, - instance_ids[0], + return client.virtual_machine_scale_set_vms.deallocate(resource_group_name, vm_scale_set_name, instance_ids[0], raw=no_wait) - else: - return client.virtual_machine_scale_sets.deallocate(resource_group_name, - vm_scale_set_name, - instance_ids=instance_ids, - raw=no_wait) + + return client.virtual_machine_scale_sets.deallocate(resource_group_name, vm_scale_set_name, + instance_ids=instance_ids, raw=no_wait) def delete_vmss_instances(resource_group_name, vm_scale_set_name, instance_ids, no_wait=False): '''delete virtual machines in a scale set.''' client = _compute_client_factory() if len(instance_ids) == 1: - return client.virtual_machine_scale_set_vms.delete(resource_group_name, - vm_scale_set_name, - instance_ids[0], + return client.virtual_machine_scale_set_vms.delete(resource_group_name, vm_scale_set_name, instance_ids[0], raw=no_wait) - else: - return client.virtual_machine_scale_sets.delete_instances(resource_group_name, - vm_scale_set_name, - instance_ids, - raw=no_wait) + + return client.virtual_machine_scale_sets.delete_instances(resource_group_name, vm_scale_set_name, instance_ids, + raw=no_wait) def stop_vmss(resource_group_name, vm_scale_set_name, instance_ids=None, no_wait=False): '''power off (stop) virtual machines in a virtual machine scale set.''' client = _compute_client_factory() if instance_ids and len(instance_ids) == 1: - return client.virtual_machine_scale_set_vms.power_off(resource_group_name, - vm_scale_set_name, - instance_ids[0], - raw=no_wait) - else: - return client.virtual_machine_scale_sets.power_off(resource_group_name, - vm_scale_set_name, - instance_ids=instance_ids, - raw=no_wait) + return client.virtual_machine_scale_set_vms.power_off(resource_group_name, vm_scale_set_name, + instance_ids[0], raw=no_wait) + + return client.virtual_machine_scale_sets.power_off(resource_group_name, vm_scale_set_name, + instance_ids=instance_ids, raw=no_wait) def reimage_vmss(resource_group_name, vm_scale_set_name, instance_id=None, no_wait=False): @@ -1406,44 +1375,31 @@ def reimage_vmss(resource_group_name, vm_scale_set_name, instance_id=None, no_wa ''' client = _compute_client_factory() if instance_id: - return client.virtual_machine_scale_set_vms.reimage(resource_group_name, - vm_scale_set_name, - instance_id, + return client.virtual_machine_scale_set_vms.reimage(resource_group_name, vm_scale_set_name, instance_id, raw=no_wait) - else: - return client.virtual_machine_scale_sets.reimage(resource_group_name, - vm_scale_set_name, - raw=no_wait) + + return client.virtual_machine_scale_sets.reimage(resource_group_name, vm_scale_set_name, raw=no_wait) def restart_vmss(resource_group_name, vm_scale_set_name, instance_ids=None, no_wait=False): '''restart virtual machines in a scale set.''' client = _compute_client_factory() if instance_ids and len(instance_ids) == 1: - return client.virtual_machine_scale_set_vms.restart(resource_group_name, - vm_scale_set_name, - instance_ids[0], + return client.virtual_machine_scale_set_vms.restart(resource_group_name, vm_scale_set_name, instance_ids[0], raw=no_wait) - else: - return client.virtual_machine_scale_sets.restart(resource_group_name, - vm_scale_set_name, - instance_ids=instance_ids, - raw=no_wait) + return client.virtual_machine_scale_sets.restart(resource_group_name, vm_scale_set_name, instance_ids=instance_ids, + raw=no_wait) def start_vmss(resource_group_name, vm_scale_set_name, instance_ids=None, no_wait=False): '''start virtual machines in a virtual machine scale set.''' client = _compute_client_factory() if instance_ids and len(instance_ids) == 1: - return client.virtual_machine_scale_set_vms.start(resource_group_name, - vm_scale_set_name, - instance_ids[0], + return client.virtual_machine_scale_set_vms.start(resource_group_name, vm_scale_set_name, instance_ids[0], raw=no_wait) - else: - return client.virtual_machine_scale_sets.start(resource_group_name, - vm_scale_set_name, - instance_ids=instance_ids, - raw=no_wait) + + return client.virtual_machine_scale_sets.start(resource_group_name, vm_scale_set_name, instance_ids=instance_ids, + raw=no_wait) def list_vmss_instance_connection_info(resource_group_name, vm_scale_set_name): @@ -1511,32 +1467,23 @@ def convert_av_set_to_managed_disk(resource_group_name, availability_set_name): # pylint: disable=too-many-locals, unused-argument, too-many-statements -def create_vm(vm_name, resource_group_name, image=None, - size='Standard_DS1_v2', location=None, tags=None, no_wait=False, - authentication_type=None, admin_password=None, admin_username=getpass.getuser(), - ssh_dest_key_path=None, ssh_key_value=None, generate_ssh_keys=False, - availability_set=None, - nics=None, nsg=None, nsg_rule=None, - private_ip_address=None, - public_ip_address=None, public_ip_address_allocation='dynamic', - public_ip_address_dns_name=None, - os_disk_name=None, os_type=None, storage_account=None, - os_caching=None, data_caching=None, storage_container_name=None, - storage_sku=None, use_unmanaged_disk=False, - attach_os_disk=None, data_disk_sizes_gb=None, image_data_disks=None, - vnet_name=None, vnet_address_prefix='10.0.0.0/16', - subnet=None, subnet_address_prefix='10.0.0.0/24', storage_profile=None, - os_publisher=None, os_offer=None, os_sku=None, os_version=None, - storage_account_type=None, vnet_type=None, nsg_type=None, public_ip_type=None, - nic_type=None, validate=False, custom_data=None, secrets=None, - plan_name=None, plan_product=None, plan_publisher=None, - license_type=None): +def create_vm(vm_name, resource_group_name, image=None, size='Standard_DS1_v2', location=None, tags=None, no_wait=False, + authentication_type=None, admin_password=None, admin_username=getpass.getuser(), ssh_dest_key_path=None, + ssh_key_value=None, generate_ssh_keys=False, availability_set=None, nics=None, nsg=None, nsg_rule=None, + private_ip_address=None, public_ip_address=None, public_ip_address_allocation='dynamic', + public_ip_address_dns_name=None, os_disk_name=None, os_type=None, storage_account=None, os_caching=None, + data_caching=None, storage_container_name=None, storage_sku=None, use_unmanaged_disk=False, + attach_os_disk=None, data_disk_sizes_gb=None, image_data_disks=None, vnet_name=None, + vnet_address_prefix='10.0.0.0/16', subnet=None, subnet_address_prefix='10.0.0.0/24', storage_profile=None, + os_publisher=None, os_offer=None, os_sku=None, os_version=None, storage_account_type=None, vnet_type=None, + nsg_type=None, public_ip_type=None, nic_type=None, validate=False, custom_data=None, secrets=None, + plan_name=None, plan_product=None, plan_publisher=None, license_type=None): from azure.cli.core.commands.client_factory import get_subscription_id from azure.cli.core.util import random_string - from azure.cli.command_modules.vm._template_builder import ( - ArmTemplateBuilder, build_vm_resource, build_storage_account_resource, build_nic_resource, - build_vnet_resource, build_nsg_resource, build_public_ip_resource, - build_output_deployment_resource, build_deployment_resource, StorageProfile) + from azure.cli.command_modules.vm._template_builder import (ArmTemplateBuilder, build_vm_resource, + build_storage_account_resource, build_nic_resource, + build_vnet_resource, build_nsg_resource, + build_public_ip_resource, StorageProfile) from azure.cli.core._profile import CLOUD @@ -1700,11 +1647,11 @@ def create_vmss(vmss_name, resource_group_name, image, plan_name=None, plan_product=None, plan_publisher=None): from azure.cli.core.commands.client_factory import get_subscription_id from azure.cli.core.util import random_string - from azure.cli.command_modules.vm._template_builder import ( - ArmTemplateBuilder, StorageProfile, build_vmss_resource, build_storage_account_resource, - build_vnet_resource, build_public_ip_resource, build_load_balancer_resource, - build_output_deployment_resource, build_deployment_resource, - build_vmss_storage_account_pool_resource, build_application_gateway_resource) + from azure.cli.command_modules.vm._template_builder import (ArmTemplateBuilder, StorageProfile, build_vmss_resource, + build_vnet_resource, build_public_ip_resource, + build_load_balancer_resource, + build_vmss_storage_account_pool_resource, + build_application_gateway_resource) from azure.cli.core._profile import CLOUD from azure.mgmt.compute.models import CachingTypes @@ -1746,14 +1693,14 @@ def create_vmss(vmss_name, resource_group_name, image, subnet_id = subnet if is_valid_resource_id(subnet) else \ '{}/virtualNetworks/{}/subnets/{}'.format(network_id_template, vnet_name, subnet) - gateway_subnet_id = \ - '{}/virtualNetworks/{}/subnets/appGwSubnet'.format(network_id_template, vnet_name) \ - if app_gateway_type == 'new' else None + gateway_subnet_id = ('{}/virtualNetworks/{}/subnets/appGwSubnet'.format(network_id_template, vnet_name) + if app_gateway_type == 'new' else None) # public IP is used by either load balancer/application gateway if public_ip_address: public_ip_address_id = (public_ip_address if is_valid_resource_id(public_ip_address) - else '{}/publicIPAddresses/{}'.format(network_id_template, public_ip_address)) # pylint: disable=line-too-long + else '{}/publicIPAddresses/{}'.format(network_id_template, + public_ip_address)) # Handle load balancer creation if load_balancer_type == 'new': @@ -1763,7 +1710,8 @@ def create_vmss(vmss_name, resource_group_name, image, lb_dependencies = [] if public_ip_type == 'new': public_ip_address = public_ip_address or '{}PublicIP'.format(load_balancer) - lb_dependencies.append('Microsoft.Network/publicIpAddresses/{}'.format(public_ip_address)) # pylint: disable=line-too-long + lb_dependencies.append( + 'Microsoft.Network/publicIpAddresses/{}'.format(public_ip_address)) master_template.add_resource(build_public_ip_resource(public_ip_address, location, tags, public_ip_address_allocation, @@ -1793,7 +1741,8 @@ def create_vmss(vmss_name, resource_group_name, image, ag_dependencies = [] if public_ip_type == 'new': public_ip_address = public_ip_address or '{}PublicIP'.format(app_gateway) - ag_dependencies.append('Microsoft.Network/publicIpAddresses/{}'.format(public_ip_address)) # pylint: disable=line-too-long + ag_dependencies.append( + 'Microsoft.Network/publicIpAddresses/{}'.format(public_ip_address)) master_template.add_resource(build_public_ip_resource(public_ip_address, location, tags, public_ip_address_allocation, diff --git a/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/disk_encryption.py b/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/disk_encryption.py index 4687f292650..f26fffe5413 100644 --- a/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/disk_encryption.py +++ b/src/command_modules/azure-cli-vm/azure/cli/command_modules/vm/disk_encryption.py @@ -193,9 +193,7 @@ def disable(resource_group_name, vm_name, volume_type=None, force=False): 'SequenceVersion': sequence_version, } - from azure.mgmt.compute.models import (VirtualMachineExtension, DiskEncryptionSettings, - KeyVaultSecretReference, KeyVaultKeyReference, - SubResource) + from azure.mgmt.compute.models import VirtualMachineExtension, DiskEncryptionSettings ext = VirtualMachineExtension(vm.location, # pylint: disable=no-member publisher=extension['publisher'],