def main(args, file=sys.stdout): #pylint: disable=redefined-builtin _logging.configure_logging(args) if len(args) > 0 and args[0] == '--version': show_version_info_exit(file) azure_folder = os.path.expanduser('~/.azure') if not os.path.exists(azure_folder): os.makedirs(azure_folder) ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json')) CONFIG.load(os.path.join(azure_folder, 'az.json')) SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600) config = Configuration(args) APPLICATION.initialize(config) try: cmd_result = APPLICATION.execute(args) # Commands can return a dictionary/list of results # If they do, we print the results. if cmd_result and cmd_result.result: formatter = OutputProducer.get_formatter( APPLICATION.configuration.output_format) OutputProducer(formatter=formatter, file=file).out(cmd_result) except Exception as ex: # pylint: disable=broad-except error_code = _handle_exception(ex) return error_code
def main(args, file=sys.stdout): #pylint: disable=redefined-builtin _logging.configure_logging(args) if len(args) > 0 and args[0] == '--version': show_version_info_exit(file) azure_folder = os.path.expanduser('~/.azure') if not os.path.exists(azure_folder): os.makedirs(azure_folder) ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json')) CONFIG.load(os.path.join(azure_folder, 'az.json')) SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600) config = Configuration(args) APPLICATION.initialize(config) try: cmd_result = APPLICATION.execute(args) # Commands can return a dictionary/list of results # If they do, we print the results. if cmd_result and cmd_result.result: formatter = OutputProducer.get_formatter(APPLICATION.configuration.output_format) OutputProducer(formatter=formatter, file=file).out(cmd_result) except Exception as ex: # pylint: disable=broad-except error_code = _handle_exception(ex) return error_code
def mock_echo_args(command_name, parameters): try: argv = ' '.join((command_name, parameters)).split() APPLICATION.initialize(Configuration(argv)) command_table = APPLICATION.configuration.get_command_table() prefunc = command_table[command_name].handler command_table[command_name].handler = lambda args: args parsed_namespace = APPLICATION.execute(argv) return parsed_namespace finally: command_table[command_name].handler = prefunc
def test_generic_update_ids(self): my_objs = [ { 'prop': 'val', 'list': [ 'a', 'b', ['c', {'d': 'e'}] ] }, { 'prop': 'val', 'list': [ 'a', 'b', ['c', {'d': 'e'}] ] }] def my_get(name, resource_group): #pylint:disable=unused-argument # name is None when tests are run in a batch on Python <=2.7.9 if sys.version_info < (2, 7, 10): return my_objs[0] return my_objs[int(name)] def my_set(**kwargs): #pylint:disable=unused-argument return my_objs register_cli_argument('gencommand', 'name', CliArgumentType(options_list=('--name', '-n'), metavar='NAME', id_part='name')) register_generic_update('gencommand', my_get, my_set) config = Configuration([]) APPLICATION.initialize(config) id_str = ('/subscriptions/00000000-0000-0000-0000-0000000000000/resourceGroups/rg/' 'providers/Microsoft.Compute/virtualMachines/') APPLICATION.execute('gencommand --ids {0}0 {0}1 --resource-group bar --set prop=newval' .format(id_str).split()) self.assertEqual(my_objs[0]['prop'], 'newval', 'first object updated') # name is None when tests are run in a batch on Python <=2.7.9 if not sys.version_info < (2, 7, 10): self.assertEqual(my_objs[1]['prop'], 'newval', 'second object updated')
def test_command_consistency(self): argv = ['vm'] APPLICATION.initialize(Configuration(argv)) command_table = APPLICATION.configuration.get_command_table() vm_commands = ((vm_command, metadata) for vm_command, metadata in command_table.items() if vm_command.startswith('vm')) for command_name, command_metadata in vm_commands: for argument_name, expected_options_list in self.consistent_arguments.items( ): try: actual_options_list = command_metadata.arguments[ argument_name].options_list self.assertEqual( actual_options_list, expected_options_list, 'Argument {} of command {} has inconsistent flags'. format(argument_name, command_name)) except KeyError: pass
ssh_key_file = os.path.join(os.path.expanduser('~'), '.ssh/id_rsa.pub') if not args.ssh_key_value: if os.path.isfile(ssh_key_file): with open(ssh_key_file) as f: args.ssh_key_value = f.read() else: raise CLIError('An RSA key file or key value must be supplied to SSH Key Value') if hasattr(args, 'network_security_group_type'): args.network_security_group_rule = 'RDP' if is_windows else 'SSH' if hasattr(args, 'nat_backend_port') and not args.nat_backend_port: args.nat_backend_port = '3389' if is_windows else '22' APPLICATION.register(APPLICATION.COMMAND_PARSER_PARSED, _handle_auth_types) def load_images_from_aliases_doc(publisher=None, offer=None, sku=None): target_url = ('https://raw.githubusercontent.com/Azure/azure-rest-api-specs/' 'master/arm-compute/quickstart-templates/aliases.json') txt = urlopen(target_url).read() dic = json.loads(txt.decode()) try: all_images = [] result = (dic['outputs']['aliases']['value']) for v in result.values(): #loop around os for alias, vv in v.items(): #loop around distros all_images.append({ 'urn alias': alias, 'publisher': vv['publisher'], 'offer': vv['offer'],
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. Since the id value is expected to be of type `IterateValue`, all the backing (dest) fields will also be of type `IterateValue` ''' try: 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 ]: existing_values = getattr(namespace, arg.name, None) if existing_values is None: existing_values = IterateValue() existing_values.append(parts[arg.id_part]) setattr(namespace, arg.name, existing_values) except Exception as ex: raise ValueError(ex) return SplitAction def command_loaded_handler(command): if not 'name' in [ arg.id_part for arg in command.arguments.values() if arg.id_part ]: # Only commands with a resource name are candidates for an id parameter return if command.name.split()[-1] == 'create': # Somewhat blunt hammer, but any create commands will not have an automatic id # parameter return required_arguments = [] optional_arguments = [] for arg in [ argument for argument in command.arguments.values() if argument.id_part ]: if arg.options.get('required', False): required_arguments.append(arg) else: optional_arguments.append(arg) arg.required = False def required_values_validator(namespace): errors = [ arg for arg in required_arguments if getattr(namespace, arg.name, None) is None ] if errors: missing_required = ' '.join( (arg.options_list[0] for arg in errors)) raise CLIError('({} | {}) are required'.format( missing_required, '--ids')) command.add_argument(argparse.SUPPRESS, '--ids', metavar='RESOURCE_ID', help='ID of resource', action=split_action(command.arguments), nargs='+', type=ResourceId, validator=required_values_validator) for command in command_table.values(): command_loaded_handler(command) APPLICATION.remove(APPLICATION.COMMAND_TABLE_LOADED, add_id_parameters)
command.add_argument(argparse.SUPPRESS, '--ids', metavar='RESOURCE_ID', help='ID of resource', action=split_action(command.arguments), nargs='+', type=ResourceId, validator=required_values_validator) for command in command_table.values(): command_loaded_handler(command) APPLICATION.remove(APPLICATION.COMMAND_TABLE_LOADED, add_id_parameters) APPLICATION.register(APPLICATION.COMMAND_TABLE_LOADED, add_id_parameters) def register_generic_update(name, getter, setter, factory=None, setter_arg_name='parameters'): get_arguments = dict(extract_args_from_signature(getter)) set_arguments = dict(extract_args_from_signature(setter)) def handler(args): ordered_arguments = args.pop('ordered_arguments') try:
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. Since the id value is expected to be of type `IterateValue`, all the backing (dest) fields will also be of type `IterateValue` ''' try: 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]: existing_values = getattr(namespace, arg.name, None) if existing_values is None: existing_values = IterateValue() existing_values.append(parts[arg.id_part]) setattr(namespace, arg.name, existing_values) except Exception as ex: raise ValueError(ex) return SplitAction def command_loaded_handler(command): if not 'name' in [arg.id_part for arg in command.arguments.values() if arg.id_part]: # Only commands with a resource name are candidates for an id parameter return if command.name.split()[-1] == 'create': # Somewhat blunt hammer, but any create commands will not have an automatic id # parameter return required_arguments = [] optional_arguments = [] for arg in [argument for argument in command.arguments.values() if argument.id_part]: if arg.options.get('required', False): required_arguments.append(arg) else: optional_arguments.append(arg) arg.required = False def required_values_validator(namespace): errors = [arg for arg in required_arguments if getattr(namespace, arg.name, None) is None] if errors: missing_required = ' '.join((arg.options_list[0] for arg in errors)) raise CLIError('({} | {}) are required'.format(missing_required, '--ids')) command.add_argument(argparse.SUPPRESS, '--ids', metavar='RESOURCE_ID', help='ID of resource', action=split_action(command.arguments), nargs='+', type=ResourceId, validator=required_values_validator) for command in command_table.values(): command_loaded_handler(command) APPLICATION.remove(APPLICATION.COMMAND_TABLE_LOADED, add_id_parameters)
for arg in [argument for argument in command.arguments.values() if argument.id_part]: if arg.options.get('required', False): required_arguments.append(arg) else: optional_arguments.append(arg) arg.required = False def required_values_validator(namespace): errors = [arg for arg in required_arguments if getattr(namespace, arg.name, None) is None] if errors: missing_required = ' '.join((arg.options_list[0] for arg in errors)) raise CLIError('({} | {}) are required'.format(missing_required, '--ids')) command.add_argument(argparse.SUPPRESS, '--ids', metavar='RESOURCE_ID', help='ID of resource', action=split_action(command.arguments), nargs='+', type=ResourceId, validator=required_values_validator) for command in command_table.values(): command_loaded_handler(command) APPLICATION.remove(APPLICATION.COMMAND_TABLE_LOADED, add_id_parameters) APPLICATION.register(APPLICATION.COMMAND_TABLE_LOADED, add_id_parameters)
if os.path.isfile(ssh_key_file): with open(ssh_key_file) as f: args.ssh_key_value = f.read() else: raise CLIError( 'An RSA key file or key value must be supplied to SSH Key Value' ) if hasattr(args, 'network_security_group_type'): args.network_security_group_rule = 'RDP' if is_windows else 'SSH' if hasattr(args, 'nat_backend_port') and not args.nat_backend_port: args.nat_backend_port = '3389' if is_windows else '22' APPLICATION.register(APPLICATION.COMMAND_PARSER_PARSED, _handle_auth_types) def load_images_from_aliases_doc(publisher=None, offer=None, sku=None): target_url = ( 'https://raw.githubusercontent.com/Azure/azure-rest-api-specs/' 'master/arm-compute/quickstart-templates/aliases.json') txt = urlopen(target_url).read() dic = json.loads(txt.decode()) try: all_images = [] result = (dic['outputs']['aliases']['value']) for v in result.values(): #loop around os for alias, vv in v.items(): #loop around distros all_images.append({ 'urn alias': alias,