示例#1
0
def register_common_storage_account_options(context):
    context.reg_arg('https_only', help='Allows https traffic only to storage service.', **three_state_flag())
    context.reg_arg('sku', help='The storage account SKU.', **model_choice_list(ResourceType.MGMT_STORAGE, 'SkuName'))
    context.reg_arg('access_tier', help='The access tier used for billing StandardBlob accounts. Cannot be set for '
                                        'StandardLRS, StandardGRS, StandardRAGRS, or PremiumLRS account types. It is '
                                        'required for StandardBlob accounts during creation',
                    **model_choice_list(ResourceType.MGMT_STORAGE, 'AccessTier'))

    # after API 2016-12-01
    if supported_api_version(resource_type=ResourceType.MGMT_STORAGE, min_api='2016-12-01'):
        encryption_services_model = get_sdk(ResourceType.MGMT_STORAGE, 'models#EncryptionServices')
        if encryption_services_model:

            encryption_choices = []
            for attribute in encryption_services_model._attribute_map.keys():  # pylint: disable=protected-access
                if not encryption_services_model._validation.get(attribute, {}).get('readonly'):  # pylint: disable=protected-access
                    # skip readonly attributes, which are not for input
                    encryption_choices.append(attribute)

            context.reg_arg('encryption_services', nargs='+', help='Specifies which service(s) to encrypt.',
                            validator=validate_encryption_services, **enum_choice_list(encryption_choices))

    # after API 2017-06-01
    if supported_api_version(resource_type=ResourceType.MGMT_STORAGE, min_api='2017-06-01'):
        context.reg_arg('assign_identity', action='store_true',
                        help='Generate and assign a new Storage Account Identity for this storage account for use with '
                             'key management services like Azure KeyVault.')

        # the options of encryption key sources are hardcoded since there isn't a enum represents them in the SDK.
        context.reg_arg('encryption_key_source', help='The encryption keySource (provider). Default: Microsoft.Storage',
                        validator=validate_encryption_source,
                        **enum_choice_list(['Microsoft.Storage', 'Microsoft.Keyvault']))
示例#2
0
 def test_supported_api_version_invalid_rt_for_profile(self):
     cli = DummyCli()
     cli.cloud = Cloud('TestCloud', profile='2017-01-01-profile')
     test_profile = {'2017-01-01-profile': {ResourceType.MGMT_STORAGE: '2020-10-10'}}
     with mock.patch('azure.cli.core.profiles._shared.AZURE_API_PROFILES', test_profile):
         with self.assertRaises(APIVersionException):
             supported_api_version(cli, ResourceType.MGMT_COMPUTE, min_api='2020-01-01')
示例#3
0
    def upload_block_blob():
        import os

        # increase the block size to 100MB when the file is larger than 200GB
        if os.path.isfile(file_path) and os.stat(file_path).st_size > 200 * 1024 * 1024 * 1024:
            client.MAX_BLOCK_SIZE = 100 * 1024 * 1024
            client.MAX_SINGLE_PUT_SIZE = 256 * 1024 * 1024

        create_blob_args = {
            'container_name': container_name,
            'blob_name': blob_name,
            'file_path': file_path,
            'progress_callback': _update_progress,
            'content_settings': content_settings,
            'metadata': metadata,
            'max_connections': max_connections,
            'lease_id': lease_id,
            'if_modified_since': if_modified_since,
            'if_unmodified_since': if_unmodified_since,
            'if_match': if_match,
            'if_none_match': if_none_match,
            'timeout': timeout
        }

        if supported_api_version(ResourceType.DATA_STORAGE, min_api='2017-04-17') and tier:
            create_blob_args['premium_page_blob_tier'] = tier

        if supported_api_version(ResourceType.DATA_STORAGE, min_api='2016-05-31'):
            create_blob_args['validate_content'] = validate_content

        return client.create_blob_from_path(**create_blob_args)
    def test_services_type(self):
        input = "ttfqbqtf"
        actual = str(services_type(self.loader)(input))
        if supported_api_version(self.cli, ResourceType.DATA_STORAGE, max_api='2016-05-31') or \
           supported_api_version(self.cli, ResourceType.DATA_STORAGE, min_api='2017-07-29'):
            expected = "bqtf"
        else:
            expected = "bqf"
        self.assertEqual(actual, expected)

        input = "everything"
        with self.assertRaises(ValueError):
            services_type(self.loader)(input)
示例#5
0
 def test_supported_api_version_min_max_constraint_semver(self):
     cli = DummyCli()
     cli.cloud = Cloud('TestCloud', profile='2017-01-01-profile')
     test_profile = {'2017-01-01-profile': {ResourceType.MGMT_KEYVAULT: '7.0'}}
     with mock.patch('azure.cli.core.profiles._shared.AZURE_API_PROFILES', test_profile):
         self.assertTrue(
             supported_api_version(cli, ResourceType.MGMT_KEYVAULT, min_api='6.0', max_api='8.0'))
示例#6
0
def cli_storage_data_plane_command(name, operation, client_factory, transform=None, table_transformer=None,
                                   exception_handler=None, resource_type=None, max_api=None, min_api=None):
    """ Registers an Azure CLI Storage Data Plane command. These commands always include the
    four parameters which can be used to obtain a storage client: account-name, account-key,
    connection-string, and sas-token. """

    if resource_type and (max_api or min_api):
        if not supported_api_version(resource_type, min_api=min_api, max_api=max_api):
            return

    command = create_command(__name__, name, operation, transform, table_transformer,
                             client_factory, exception_handler=exception_handler)
    # add parameters required to create a storage client
    group_name = 'Storage Account'
    command.add_argument('account_name', '--account-name', required=False, default=None,
                         arg_group=group_name,
                         help='Storage account name. Must be used in conjunction with either '
                         'storage account key or a SAS token. Environment variable: '
                         'AZURE_STORAGE_ACCOUNT')
    command.add_argument('account_key', '--account-key', required=False, default=None,
                         arg_group=group_name,
                         help='Storage account key. Must be used in conjunction with storage '
                         'account name. Environment variable: '
                         'AZURE_STORAGE_KEY')
    command.add_argument('connection_string', '--connection-string', required=False, default=None,
                         validator=validate_client_parameters, arg_group=group_name,
                         help='Storage account connection string. Environment variable: '
                         'AZURE_STORAGE_CONNECTION_STRING')
    command.add_argument('sas_token', '--sas-token', required=False, default=None,
                         arg_group=group_name,
                         help='A Shared Access Signature (SAS). Must be used in conjunction with '
                         'storage account name. Environment variable: '
                         'AZURE_STORAGE_SAS_TOKEN')
    command_table[command.name] = command
示例#7
0
    def upload_append_blob():
        if not client.exists(container_name, blob_name):
            client.create_blob(
                container_name=container_name,
                blob_name=blob_name,
                content_settings=content_settings,
                metadata=metadata,
                lease_id=lease_id,
                if_modified_since=if_modified_since,
                if_match=if_match,
                if_none_match=if_none_match,
                timeout=timeout)

        append_blob_args = {
            'container_name': container_name,
            'blob_name': blob_name,
            'file_path': file_path,
            'progress_callback': _update_progress,
            'maxsize_condition': maxsize_condition,
            'lease_id': lease_id,
            'timeout': timeout
        }

        if supported_api_version(ResourceType.DATA_STORAGE, min_api='2016-05-31'):
            append_blob_args['validate_content'] = validate_content

        return client.append_blob_from_path(**append_blob_args)
示例#8
0
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, sku, frontend_ip_zone):
    frontend_ip_config = _build_frontend_ip_config(frontend_ip_name, public_ip_id, subnet_id, private_ip_address,
                                                   private_ip_allocation, frontend_ip_zone)

    lb_properties = {
        'backendAddressPools': [
            {
                'name': backend_pool_name
            }
        ],
        'frontendIPConfigurations': [frontend_ip_config]
    }
    lb = {
        'type': 'Microsoft.Network/loadBalancers',
        'name': name,
        'location': location,
        'tags': tags,
        'apiVersion': get_api_version(ResourceType.MGMT_NETWORK),
        'dependsOn': [],
        'properties': lb_properties
    }
    if sku and supported_api_version(ResourceType.MGMT_NETWORK, min_api='2017-08-01'):
        lb['sku'] = {'name': sku}
    return lb
示例#9
0
 def register_cli_argument(self, *args, **kwargs):
     if supported_api_version(self._type, min_api=self._min_api, max_api=self._max_api):
         register_cli_argument(*args, **kwargs)
     else:
         from azure.cli.core.commands.parameters import ignore_type
         kwargs = {'arg_type': ignore_type}
         register_cli_argument(*args, **kwargs)
示例#10
0
def _build_frontend_ip_config(name, public_ip_id=None, subnet_id=None, private_ip_address=None,
                              private_ip_allocation=None, zone=None):
    frontend_ip_config = {
        'name': name
    }

    if public_ip_id:
        frontend_ip_config.update({
            'properties': {
                'publicIPAddress': {'id': public_ip_id}
            }
        })
    else:
        frontend_ip_config.update({
            'properties': {
                'privateIPAllocationMethod': private_ip_allocation,
                'privateIPAddress': private_ip_address,
                'subnet': {'id': subnet_id}
            }
        })

    if zone and supported_api_version(ResourceType.MGMT_NETWORK, min_api='2017-06-01'):
        frontend_ip_config['zones'] = zone

    return frontend_ip_config
示例#11
0
 def test_supported_api_version_min_max_constraint(self):
     cli = DummyCli()
     cli.cloud = Cloud('TestCloud', profile='2017-01-01-profile')
     test_profile = {'2017-01-01-profile': {ResourceType.MGMT_STORAGE: '2020-10-10'}}
     with mock.patch('azure.cli.core.profiles._shared.AZURE_API_PROFILES', test_profile):
         self.assertTrue(
             supported_api_version(cli, ResourceType.MGMT_STORAGE, min_api='2020-01-01', max_api='2021-01-01'))
示例#12
0
 def _in_api_range(kwargs):
     resource_type = kwargs.pop('resource_type', None)
     max_api = kwargs.pop('max_api', None)
     min_api = kwargs.pop('min_api', None)
     if resource_type and (max_api or min_api):
         return supported_api_version(resource_type, min_api=min_api, max_api=max_api)
     return True
示例#13
0
def get_resources_in_resource_group(resource_group_name, resource_type=None):
    from azure.cli.core.commands.client_factory import get_mgmt_service_client
    rcf = get_mgmt_service_client(ResourceType.MGMT_RESOURCE_RESOURCES)
    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))
    return list(rcf.resources.list_by_resource_group(resource_group_name, filter=filter_str))
示例#14
0
 def register_cli_argument(self, *args, **kwargs):
     if supported_api_version(self._type, min_api=self._min_api, max_api=self._max_api):
         register_cli_argument(*args, **kwargs)
     else:
         from azure.cli.core.commands.parameters import ignore_type
         kwargs = {}
         args = tuple([args[0], args[1], ignore_type])
         register_cli_argument(*args, **kwargs)
示例#15
0
def list_share_files(client, share_name, directory_name=None, timeout=None, exclude_dir=False, snapshot=None):
    if supported_api_version(ResourceType.DATA_STORAGE, min_api='2017-04-17'):
        generator = client.list_directories_and_files(share_name, directory_name, timeout=timeout, snapshot=snapshot)
    else:
        generator = client.list_directories_and_files(share_name, directory_name, timeout=timeout)
    if exclude_dir:
        return list(f for f in generator if isinstance(f.properties, FileProperties))

    return generator
示例#16
0
def build_public_ip_resource(name, location, tags, address_allocation, dns_name, sku, zone):
    public_ip_properties = {'publicIPAllocationMethod': address_allocation}

    if dns_name:
        public_ip_properties['dnsSettings'] = {'domainNameLabel': dns_name}

    public_ip = {
        'apiVersion': get_api_version(ResourceType.MGMT_NETWORK),
        'type': 'Microsoft.Network/publicIPAddresses',
        'name': name,
        'location': location,
        'tags': tags,
        'dependsOn': [],
        'properties': public_ip_properties
    }
    if sku and supported_api_version(ResourceType.MGMT_NETWORK, min_api='2017-08-01'):
        public_ip['sku'] = {'name': sku}
    if zone and supported_api_version(ResourceType.MGMT_NETWORK, min_api='2017-06-01'):
        public_ip['zones'] = zone
    return public_ip
示例#17
0
 def _should_include_example(self, ex):
     min_profile = ex.get('min_profile')
     max_profile = ex.get('max_profile')
     if min_profile or max_profile:
         from azure.cli.core.profiles import supported_api_version, PROFILE_TYPE
         # yaml will load this as a datetime if it's a date, we need a string.
         min_profile = str(min_profile) if min_profile else None
         max_profile = str(max_profile) if max_profile else None
         return supported_api_version(self.cli_ctx, resource_type=PROFILE_TYPE,
                                      min_api=min_profile, max_api=max_profile)
     return True
示例#18
0
def create_short_lived_share_sas(account_name, account_key, share):
    from datetime import datetime, timedelta
    if supported_api_version(ResourceType.DATA_STORAGE, min_api='2017-04-17'):
        SharedAccessSignature = get_sdk(ResourceType.DATA_STORAGE, 'FileSharedAccessSignature',
                                        mod='file.sharedaccesssignature')
    else:
        SharedAccessSignature = get_sdk(ResourceType.DATA_STORAGE, 'SharedAccessSignature',
                                        mod='sharedaccesssignature')
    FilePermission = get_sdk(ResourceType.DATA_STORAGE, 'file.models#FilePermissions')

    expiry = (datetime.utcnow() + timedelta(days=1)).strftime('%Y-%m-%dT%H:%M:%SZ')
    sas = SharedAccessSignature(account_name, account_key)
    return sas.generate_share(share, permission=FilePermission(read=True), expiry=expiry, protocol='https')
示例#19
0
def _create_short_lived_blob_sas(account_name, account_key, container, blob):
    if supported_api_version(ResourceType.DATA_STORAGE, min_api='2017-04-17'):
        SharedAccessSignature = get_sdk(ResourceType.DATA_STORAGE, 'BlobSharedAccessSignature',
                                        mod='blob.sharedaccesssignature')
    else:
        SharedAccessSignature = get_sdk(ResourceType.DATA_STORAGE, 'SharedAccessSignature',
                                        mod='sharedaccesssignature')

    BlobPermissions = get_sdk(ResourceType.DATA_STORAGE, 'blob.models#BlobPermissions')
    expiry = (datetime.utcnow() + timedelta(days=1)).strftime('%Y-%m-%dT%H:%M:%SZ')
    sas = SharedAccessSignature(account_name, account_key)
    return sas.generate_blob(container, blob, permission=BlobPermissions(read=True), expiry=expiry,
                             protocol='https')
示例#20
0
def _create_short_lived_file_sas(account_name, account_key, share, directory_name, file_name):
    if supported_api_version(ResourceType.DATA_STORAGE, min_api='2017-04-17'):
        SharedAccessSignature = get_sdk(ResourceType.DATA_STORAGE, 'FileSharedAccessSignature',
                                        mod='file.sharedaccesssignature')
    else:
        SharedAccessSignature = get_sdk(ResourceType.DATA_STORAGE, 'SharedAccessSignature',
                                        mod='sharedaccesssignature')
    BlobPermissions = get_sdk(ResourceType.DATA_STORAGE, 'blob.models#BlobPermissions')
    # if dir is empty string change it to None
    directory_name = directory_name if directory_name else None
    expiry = (datetime.utcnow() + timedelta(days=1)).strftime('%Y-%m-%dT%H:%M:%SZ')
    sas = SharedAccessSignature(account_name, account_key)
    return sas.generate_file(share, directory_name=directory_name, file_name=file_name,
                             permission=BlobPermissions(read=True), expiry=expiry, protocol='https')
示例#21
0
def cli_command(module_name, name, operation,
                client_factory=None, transform=None, table_transformer=None,
                no_wait_param=None, confirmation=None, exception_handler=None,
                formatter_class=None, deprecate_info=None,
                resource_type=None, max_api=None, min_api=None):
    """ Registers a default Azure CLI command. These commands require no special parameters. """
    if resource_type and (max_api or min_api):
        if not supported_api_version(resource_type, min_api=min_api, max_api=max_api):
            return

    command_table[name] = create_command(module_name, name, operation, transform, table_transformer,
                                         client_factory, no_wait_param, confirmation=confirmation,
                                         exception_handler=exception_handler,
                                         formatter_class=formatter_class,
                                         deprecate_info=deprecate_info)
示例#22
0
 def supported_api_version(self, resource_type=None, min_api=None, max_api=None, operation_group=None):
     from azure.cli.core.profiles import supported_api_version
     if not min_api and not max_api:
         # optimistically assume that fully supported if no api restriction listed
         return True
     api_support = supported_api_version(
         cli_ctx=self.cli_ctx,
         resource_type=resource_type or self._get_resource_type(),
         min_api=min_api or self.min_profile,
         max_api=max_api or self.max_profile,
         operation_group=operation_group)
     if isinstance(api_support, bool):
         return api_support
     elif operation_group:
         return getattr(api_support, operation_group)
     return api_support
示例#23
0
    def _download_action(pair):
        destination_dir = os.path.join(destination, pair[0])
        mkdir_p(destination_dir)

        get_file_args = {
            'share_name': source,
            'directory_name': pair[0],
            'file_name': pair[1],
            'file_path': os.path.join(destination, *pair),
            'max_connections': max_connections
        }

        if supported_api_version(ResourceType.DATA_STORAGE, min_api='2016-05-31'):
            get_file_args['validate_content'] = validate_content

        client.get_file_to_path(**get_file_args)
        return client.make_file_url(source, *pair)
示例#24
0
def build_load_balancer_resource(name, location, tags, backend_pool_name, nat_pool_name,
                                 backend_port, frontend_ip_name, public_ip_id, subnet_id,
                                 private_ip_address, private_ip_allocation, sku):
    lb_id = "resourceId('Microsoft.Network/loadBalancers', '{}')".format(name)

    frontend_ip_config = _build_frontend_ip_config(frontend_ip_name, public_ip_id,
                                                   private_ip_address, private_ip_allocation,
                                                   subnet_id)

    lb_properties = {
        'backendAddressPools': [
            {
                'name': backend_pool_name
            }
        ],
        'inboundNatPools': [
            {
                'name': nat_pool_name,
                'properties': {
                    'frontendIPConfiguration': {
                        'id': "[concat({}, '/frontendIPConfigurations/', '{}')]".format(
                            lb_id, frontend_ip_name)
                    },
                    'protocol': 'tcp',
                    'frontendPortRangeStart': '50000',
                    'frontendPortRangeEnd': '50119',
                    'backendPort': backend_port
                }
            }
        ],
        'frontendIPConfigurations': [frontend_ip_config]
    }
    lb = {
        'type': 'Microsoft.Network/loadBalancers',
        'name': name,
        'location': location,
        'tags': tags,
        'apiVersion': get_api_version(ResourceType.MGMT_NETWORK),
        'dependsOn': [],
        'properties': lb_properties
    }
    if sku and supported_api_version(ResourceType.MGMT_NETWORK, min_api='2017-08-01'):
        lb['sku'] = {'name': sku}
    return lb
示例#25
0
    def _upload_blob(file_path, blob_name, blob_content_settings):
        create_blob_args = {
            'container_name': destination_container_name,
            'blob_name': blob_name,
            'file_path': file_path,
            'progress_callback': lambda c, t: None,
            'content_settings': blob_content_settings,
            'metadata': metadata,
            'max_connections': max_connections,
            'lease_id': lease_id,
            'if_modified_since': if_modified_since,
            'if_unmodified_since': if_unmodified_since,
            'if_match': if_match,
            'if_none_match': if_none_match,
            'timeout': timeout
        }

        if supported_api_version(ResourceType.DATA_STORAGE, min_api='2016-05-31'):
            create_blob_args['validate_content'] = validate_content

        return client.create_blob_from_path(**create_blob_args)
示例#26
0
    def _upload_action(source_pair):
        dir_name = os.path.dirname(source_pair[1])
        file_name = os.path.basename(source_pair[1])

        _make_directory_in_files_share(client, destination, dir_name)
        create_file_args = {
            'share_name': destination,
            'directory_name': dir_name,
            'file_name': file_name,
            'local_file_path': source_pair[0],
            'content_settings': content_settings,
            'metadata': metadata,
            'max_connections': max_connections,
        }

        if supported_api_version(ResourceType.DATA_STORAGE, min_api='2016-05-31'):
            create_file_args['validate_content'] = validate_content

        client.create_file_from_path(**create_file_args)

        return client.make_file_url(destination, dir_name, file_name)
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,
        'enableBgp': enable_bgp,
        'connectionType': vpn_type,
        'routingWeight': routing_weight
    }
    if supported_api_version(ResourceType.MGMT_NETWORK, min_api='2017-03-01'):
        vpn_properties['usePolicyBasedTrafficSelectors'] = use_policy_based_traffic_selectors

    # add scenario specific properties
    if vpn_type == 'IPSec':
        vpn_properties.update({
            'localNetworkGateway2': {'id': gateway2},
            'sharedKey': shared_key
        })
    elif vpn_type == 'Vnet2Vnet':
        vpn_properties.update({
            'virtualNetworkGateway2': {'id': gateway2},
            'sharedKey': shared_key
        })
    elif vpn_type == 'ExpressRoute':
        vpn_properties.update({
            'peer': {'id': gateway2}
        })

    vpn_connection = {
        'type': 'Microsoft.Network/connections',
        'name': name,
        'location': location,
        'tags': tags,
        'apiVersion': '2015-06-15',
        'dependsOn': [],
        'properties': vpn_properties if vpn_type != 'VpnClient' else {}
    }
    return vpn_connection
示例#28
0
    def _upload_action(src, dst):
        dir_name = os.path.dirname(dst)
        file_name = os.path.basename(dst)

        _make_directory_in_files_share(client, destination, dir_name)
        create_file_args = {
            'share_name': destination,
            'directory_name': dir_name,
            'file_name': file_name,
            'local_file_path': src,
            'content_settings': guess_content_type(src, content_settings, settings_class),
            'metadata': metadata,
            'max_connections': max_connections,
        }

        if supported_api_version(ResourceType.DATA_STORAGE, min_api='2016-05-31'):
            create_file_args['validate_content'] = validate_content

        logger.warning('uploading %s', src)
        client.create_file_from_path(**create_file_args)

        return client.make_file_url(destination, dir_name, file_name)
示例#29
0
def cli_command(module_name, name, operation,
                client_factory=None, transform=None, table_transformer=None,
                no_wait_param=None, confirmation=None, exception_handler=None,
                formatter_class=None, deprecate_info=None,
                resource_type=None, max_api=None, min_api=None):
    """ Registers a default Azure CLI command. These commands require no special parameters. """
    if resource_type and (max_api or min_api):
        if not supported_api_version(resource_type, min_api=min_api, max_api=max_api):
            return

    cmd = create_command(module_name, name, operation, transform, table_transformer,
                         client_factory, no_wait_param, confirmation=confirmation,
                         exception_handler=exception_handler,
                         formatter_class=formatter_class,
                         deprecate_info=deprecate_info)

    # Set the command source as we have the current command table and are about to add the command
    if module_name and module_name.startswith(EXTENSIONS_MOD_PREFIX):
        ext_mod = module_name.split('.')[0]
        cmd.command_source = ExtensionCommandSource(extension_name=mod_to_ext_map.get(ext_mod, None))
        if name in command_table:
            cmd.command_source.overrides_command = True

    command_table[name] = cmd
示例#30
0
def build_av_set_resource(name, location, tags,
                          platform_update_domain_count, platform_fault_domain_count, unmanaged):
    av_set_api_version = get_api_version(ResourceType.MGMT_COMPUTE)
    av_set = {
        'type': 'Microsoft.Compute/availabilitySets',
        'name': name,
        'location': location,
        'tags': tags,
        'apiVersion': av_set_api_version,
        "properties": {
            'platformFaultDomainCount': platform_fault_domain_count,
        }
    }

    if supported_api_version(ResourceType.MGMT_COMPUTE, '2016-04-30-preview'):
        av_set['sku'] = {
            'name': 'Classic' if unmanaged else 'Aligned'
        }

    # server defaults the UD to 5 unless set otherwise
    if platform_update_domain_count is not None:
        av_set['properties']['platformUpdateDomainCount'] = platform_update_domain_count

    return av_set
示例#31
0
 def test_supported_api_profile_max_constraint_not_supported(self):
     self.assertFalse(
         supported_api_version(PROFILE_TYPE, max_api='1999-12-30'))
示例#32
0
            transform=lambda x: getattr(x, 'keys', x))
cli_command(__name__,
            'storage account keys list',
            mgmt_path + 'list_keys',
            factory,
            transform=lambda x: getattr(x, 'keys', x))

with VersionConstraint(ResourceType.MGMT_STORAGE, min_api='2017-06-01') as c:
    c.cli_command(__name__, 'storage account network-rule add',
                  custom_path + 'add_network_rule', factory)
    c.cli_command(__name__, 'storage account network-rule remove',
                  custom_path + 'remove_network_rule', factory)
    c.cli_command(__name__, 'storage account network-rule list',
                  custom_path + 'list_network_rules', factory)

if supported_api_version(ResourceType.MGMT_STORAGE, max_api='2015-06-15'):
    cli_command(__name__, 'storage account create',
                custom_path + 'create_storage_account_with_account_type')
else:
    cli_command(__name__, 'storage account create',
                custom_path + 'create_storage_account')

if supported_api_version(ResourceType.MGMT_STORAGE, min_api='2016-12-01'):
    cli_generic_update_command(__name__,
                               'storage account update',
                               mgmt_path + 'get_properties',
                               mgmt_path + 'update',
                               factory,
                               custom_function_op=custom_path +
                               'update_storage_account')
示例#33
0
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

# pylint: disable=line-too-long

from azure.cli.core.commands import cli_command
from azure.cli.core.profiles import supported_api_version, PROFILE_TYPE
from ._client_factory import (topics_factory, event_subscriptions_factory,
                              topic_types_factory)

if not supported_api_version(PROFILE_TYPE, max_api='2017-03-09-profile'):
    topics_mgmt_path = 'azure.mgmt.eventgrid.operations.topics_operations#'
    topic_types_mgmt_path = 'azure.mgmt.eventgrid.operations.topic_types_operations#'
    custom_path = 'azure.cli.command_modules.eventgrid.custom#'

    cli_command(__name__, 'eventgrid topic create',
                topics_mgmt_path + 'TopicsOperations.create_or_update',
                topics_factory)
    cli_command(__name__, 'eventgrid topic show',
                topics_mgmt_path + 'TopicsOperations.get', topics_factory)
    cli_command(__name__, 'eventgrid topic key list',
                topics_mgmt_path + 'TopicsOperations.list_shared_access_keys',
                topics_factory)
    cli_command(__name__, 'eventgrid topic key regenerate',
                topics_mgmt_path + 'TopicsOperations.regenerate_key',
                topics_factory)
    cli_command(__name__, 'eventgrid topic delete',
                topics_mgmt_path + 'TopicsOperations.delete', topics_factory)
    cli_command(__name__, 'eventgrid topic list',
示例#34
0
cli_command(__name__, 'vm list-ip-addresses', custom_path.format('list_ip_addresses'), table_transformer=transform_ip_addresses)
cli_command(__name__, 'vm get-instance-view', custom_path.format('get_instance_view'),
            table_transformer='{Name:name, ResourceGroup:resourceGroup, Location:location, ProvisioningState:provisioningState, PowerState:instanceView.statuses[1].displayStatus}')
cli_command(__name__, 'vm list', custom_path.format('list_vm'), table_transformer=transform_vm_list)
cli_command(__name__, 'vm resize', custom_path.format('resize_vm'), no_wait_param='no_wait')
cli_command(__name__, 'vm capture', custom_path.format('capture_vm'))
cli_command(__name__, 'vm open-port', custom_path.format('vm_open_port'))
cli_command(__name__, 'vm format-secret', custom_path.format('get_vm_format_secret'))
cli_generic_update_command(__name__, 'vm update',
                           mgmt_path.format(op_var, op_class, 'get'),
                           mgmt_path.format(op_var, op_class, 'create_or_update'),
                           cf_vm,
                           no_wait_param='raw')
cli_generic_wait_command(__name__, 'vm wait', 'azure.cli.command_modules.vm.custom#get_instance_view')

if supported_api_version(ResourceType.MGMT_COMPUTE, min_api='2016-04-30-preview'):
    cli_command(__name__, 'vm convert', mgmt_path.format(op_var, op_class, 'convert_to_managed_disks'), cf_vm)

    # VM encryption
    cli_command(__name__, 'vm encryption enable', 'azure.cli.command_modules.vm.disk_encryption#enable')
    cli_command(__name__, 'vm encryption disable', 'azure.cli.command_modules.vm.disk_encryption#disable')
    cli_command(__name__, 'vm encryption show', 'azure.cli.command_modules.vm.disk_encryption#show', exception_handler=empty_on_404)

# VM NIC
cli_command(__name__, 'vm nic add', custom_path.format('vm_add_nics'))
cli_command(__name__, 'vm nic remove', custom_path.format('vm_remove_nics'))
cli_command(__name__, 'vm nic set', custom_path.format('vm_set_nics'))
cli_command(__name__, 'vm nic show', custom_path.format('vm_show_nic'), exception_handler=empty_on_404)
cli_command(__name__, 'vm nic list', custom_path.format('vm_list_nics'))

# VMSS NIC
示例#35
0
                     ('Timestamp', r['properties']['timestamp']),
                     ('State', r['properties']['provisioningState'])])
        for r in sort_list
    ]


cli_command(__name__,
            'group deployment create',
            'azure.cli.command_modules.resource.custom#deploy_arm_template',
            no_wait_param='no_wait',
            exception_handler=handle_long_running_operation_exception)
cli_generic_wait_command(
    __name__, 'group deployment wait',
    'azure.mgmt.resource.resources.operations.deployments_operations#DeploymentsOperations.get',
    cf_deployments)
if supported_api_version(resource_type=ResourceType.MGMT_RESOURCE_RESOURCES,
                         min_api='2017-05-10'):
    cli_command(
        __name__,
        'group deployment list',
        'azure.mgmt.resource.resources.operations.deployments_operations#DeploymentsOperations.list_by_resource_group',
        cf_deployments,
        table_transformer=transform_deployments_list)
else:
    cli_command(
        __name__,
        'group deployment list',
        'azure.mgmt.resource.resources.operations.deployments_operations#DeploymentsOperations.list',
        cf_deployments,
        table_transformer=transform_deployments_list)
cli_command(
    __name__,
示例#36
0
 def test_supported_api_profile_no_constraints(self):
     # At least a min or max version must be specified
     cli = TestCli()
     with self.assertRaises(ValueError):
         supported_api_version(cli, PROFILE_TYPE)
示例#37
0
            ag_path + 'delete',
            cf_application_gateways,
            no_wait_param='raw')
cli_command(__name__,
            'network application-gateway show',
            ag_path + 'get',
            cf_application_gateways,
            exception_handler=empty_on_404)
cli_command(__name__, 'network application-gateway list',
            custom_path + 'list_application_gateways')
cli_command(__name__, 'network application-gateway start', ag_path + 'start',
            cf_application_gateways)
cli_command(__name__, 'network application-gateway stop', ag_path + 'stop',
            cf_application_gateways)

if supported_api_version(ResourceType.MGMT_NETWORK, min_api='2016-09-01'):
    cli_command(__name__, 'network application-gateway show-backend-health',
                ag_path + 'backend_health', cf_application_gateways)

cli_generic_update_command(__name__,
                           'network application-gateway update',
                           ag_path + 'get',
                           ag_path + 'create_or_update',
                           cf_application_gateways,
                           no_wait_param='raw',
                           custom_function_op=custom_path +
                           'update_application_gateway')
cli_generic_wait_command(__name__, 'network application-gateway wait',
                         ag_path + 'get', cf_application_gateways)

property_map = {
示例#38
0
            custom_path.format('get_vm_format_secret'))
cli_command(__name__, 'vm secret add', custom_path.format('add_vm_secret'))
cli_command(__name__, 'vm secret list', custom_path.format('list_vm_secrets'))
cli_command(__name__, 'vm secret remove',
            custom_path.format('remove_vm_secret'))
cli_generic_update_command(__name__,
                           'vm update',
                           mgmt_path.format(op_var, op_class, 'get'),
                           mgmt_path.format(op_var, op_class,
                                            'create_or_update'),
                           cf_vm,
                           no_wait_param='raw')
cli_generic_wait_command(
    __name__, 'vm wait',
    'azure.cli.command_modules.vm.custom#get_instance_view')
if supported_api_version(ResourceType.MGMT_COMPUTE, min_api='2017-03-30'):
    cli_command(__name__, 'vm perform-maintenance',
                mgmt_path.format(op_var, op_class, 'perform_maintenance'),
                cf_vm)

if supported_api_version(ResourceType.MGMT_COMPUTE,
                         min_api='2016-04-30-preview'):
    cli_command(__name__, 'vm convert',
                mgmt_path.format(op_var, op_class, 'convert_to_managed_disks'),
                cf_vm)

# VM encryption
cli_command(__name__, 'vm encryption enable',
            'azure.cli.command_modules.vm.disk_encryption#encrypt_vm')
cli_command(__name__, 'vm encryption disable',
            'azure.cli.command_modules.vm.disk_encryption#decrypt_vm')
示例#39
0
def cli_storage_data_plane_command(name,
                                   operation,
                                   client_factory,
                                   transform=None,
                                   table_transformer=None,
                                   exception_handler=None,
                                   resource_type=None,
                                   max_api=None,
                                   min_api=None):
    """ Registers an Azure CLI Storage Data Plane command. These commands always include the
    four parameters which can be used to obtain a storage client: account-name, account-key,
    connection-string, and sas-token. """

    if resource_type and (max_api or min_api):
        if not supported_api_version(
                resource_type, min_api=min_api, max_api=max_api):
            return

    command = create_command(__name__,
                             name,
                             operation,
                             transform,
                             table_transformer,
                             client_factory,
                             exception_handler=exception_handler)
    # add parameters required to create a storage client
    group_name = 'Storage Account'
    command.add_argument(
        'account_name',
        '--account-name',
        required=False,
        default=None,
        arg_group=group_name,
        help=
        'Storage account name. Related environment variable: AZURE_STORAGE_ACCOUNT. Must be used '
        'in conjunction with either storage account key or a SAS token. If neither are present, '
        'the command will try to query the storage account key using the authenticated Azure '
        'account. If a large number of storage commands are executed the API quota may be hit'
    )
    command.add_argument(
        'account_key',
        '--account-key',
        required=False,
        default=None,
        arg_group=group_name,
        help='Storage account key. Must be used in conjunction with storage '
        'account name. Environment variable: '
        'AZURE_STORAGE_KEY')
    command.add_argument(
        'connection_string',
        '--connection-string',
        required=False,
        default=None,
        validator=validate_client_parameters,
        arg_group=group_name,
        help='Storage account connection string. Environment variable: '
        'AZURE_STORAGE_CONNECTION_STRING')
    command.add_argument(
        'sas_token',
        '--sas-token',
        required=False,
        default=None,
        arg_group=group_name,
        help='A Shared Access Signature (SAS). Must be used in conjunction with '
        'storage account name. Environment variable: '
        'AZURE_STORAGE_SAS_TOKEN')
    command_table[command.name] = command
示例#40
0
def cosmosdb_table_exists(cli_ctx):
    try:
        return supported_api_version(cli_ctx, ResourceType.DATA_COSMOS_TABLE, min_api='2017-04-17')
    except APIVersionException:
        return False
示例#41
0
 def test_supported_api_version_no_constraints(self):
     # At least a min or max version must be specified
     cli = TestCli()
     with self.assertRaises(ValueError):
         supported_api_version(cli, ResourceType.MGMT_STORAGE)
示例#42
0
def build_vmss_resource(name, naming_prefix, location, tags, overprovision, upgrade_policy_mode,
                        vm_sku, instance_count, ip_config_name, nic_name, subnet_id,
                        admin_username, authentication_type,
                        storage_profile, os_disk_name,
                        os_caching, data_caching, storage_sku, data_disk_sizes_gb,
                        image_data_disks, os_type,
                        image=None, admin_password=None, ssh_key_value=None, ssh_key_path=None,
                        os_publisher=None, os_offer=None, os_sku=None, os_version=None,
                        backend_address_pool_id=None, inbound_nat_pool_id=None,
                        single_placement_group=None, custom_data=None, secrets=None):

    # Build IP configuration
    ip_configuration = {
        'name': ip_config_name,
        'properties': {
            'subnet': {'id': subnet_id}
        }
    }

    if backend_address_pool_id:
        key = 'loadBalancerBackendAddressPools' if 'loadBalancers' in backend_address_pool_id \
            else 'ApplicationGatewayBackendAddressPools'
        ip_configuration['properties'][key] = [
            {'id': backend_address_pool_id}
        ]

    if inbound_nat_pool_id:
        ip_configuration['properties']['loadBalancerInboundNatPools'] = [
            {'id': inbound_nat_pool_id}
        ]

    # Build storage profile
    storage_properties = {}
    if storage_profile in [StorageProfile.SACustomImage, StorageProfile.SAPirImage]:
        storage_properties['osDisk'] = {
            'name': os_disk_name,
            'caching': os_caching,
            'createOption': 'FromImage',
        }

        if storage_profile == StorageProfile.SACustomImage:
            storage_properties['osDisk'].update({
                'osType': os_type,
                'image': {
                    'uri': image
                }
            })
        else:
            storage_properties['osDisk']['vhdContainers'] = "[variables('vhdContainers')]"
    elif storage_profile in [StorageProfile.ManagedPirImage, StorageProfile.ManagedCustomImage]:
        storage_properties['osDisk'] = {
            'createOption': 'FromImage',
            'caching': os_caching,
            'managedDisk': {'storageAccountType': storage_sku}
        }

    if storage_profile in [StorageProfile.SAPirImage, StorageProfile.ManagedPirImage]:
        storage_properties['imageReference'] = {
            'publisher': os_publisher,
            'offer': os_offer,
            'sku': os_sku,
            'version': os_version
        }
    if storage_profile == StorageProfile.ManagedCustomImage:
        storage_properties['imageReference'] = {
            'id': image
        }

    storage_profile = _build_data_disks(storage_properties, data_disk_sizes_gb,
                                        image_data_disks, data_caching,
                                        storage_sku)

    # Build OS Profile
    os_profile = {
        'computerNamePrefix': naming_prefix,
        'adminUsername': admin_username
    }
    if authentication_type == 'password':
        os_profile['adminPassword'] = admin_password
    else:
        os_profile['linuxConfiguration'] = {
            'disablePasswordAuthentication': True,
            'ssh': {
                'publicKeys': [
                    {
                        'path': ssh_key_path,
                        'keyData': ssh_key_value
                    }
                ]
            }
        }

    if custom_data:
        os_profile['customData'] = b64encode(custom_data)

    if secrets:
        os_profile['secrets'] = secrets

    if single_placement_group is None:  # this should never happen, but just in case
        raise ValueError('single_placement_group was not set by validators')
    # Build VMSS
    vmss_properties = {
        'overprovision': overprovision,
        'upgradePolicy': {
            'mode': upgrade_policy_mode
        },
        'virtualMachineProfile': {
            'storageProfile': storage_properties,
            'osProfile': os_profile,
            'networkProfile': {
                'networkInterfaceConfigurations': [{
                    'name': nic_name,
                    'properties': {
                        'primary': 'true',
                        'ipConfigurations': [ip_configuration]
                    }
                }]
            }
        }
    }

    if supported_api_version(ResourceType.MGMT_COMPUTE, min_api='2016-04-30-preview'):
        vmss_properties['singlePlacementGroup'] = single_placement_group

    vmss_api_version = get_api_version(ResourceType.MGMT_COMPUTE)
    vmss = {
        'type': 'Microsoft.Compute/virtualMachineScaleSets',
        'name': name,
        'location': location,
        'tags': tags,
        'apiVersion': vmss_api_version,
        'dependsOn': [],
        'sku': {
            'name': vm_sku,
            'tier': 'Standard',
            'capacity': instance_count
        },
        'properties': vmss_properties
    }
    return vmss
示例#43
0
 def test_supported_api_profile_min_constraint_not_supported(self):
     cli = TestCli()
     cli.cloud = Cloud('TestCloud', profile='2000-01-01-profile-preview')
     self.assertFalse(
         supported_api_version(cli, PROFILE_TYPE, min_api='2000-01-02'))
示例#44
0
 def test_supported_api_profile_min_constraint(self):
     cli = TestCli()
     cli.cloud = Cloud('TestCloud', profile='2000-01-01-profile')
     self.assertTrue(
         supported_api_version(cli, PROFILE_TYPE, min_api='2000-01-01'))
示例#45
0
 def test_supported_api_profile_preview_constraint_in_profile(self):
     self.assertFalse(
         supported_api_version(PROFILE_TYPE, min_api='2000-01-01'))
示例#46
0
cli_command(__name__, 'resource lock create', 'azure.cli.command_modules.resource.custom#create_lock')
cli_command(__name__, 'resource lock delete', 'azure.cli.command_modules.resource.custom#delete_lock')
cli_command(__name__, 'resource lock list', 'azure.cli.command_modules.resource.custom#list_locks')
cli_command(__name__, 'resource lock show', 'azure.cli.command_modules.resource.custom#get_lock',
            exception_handler=empty_on_404)
cli_command(__name__, 'resource lock update', 'azure.cli.command_modules.resource.custom#update_lock')

# Resource provider commands
cli_command(__name__, 'provider list', 'azure.mgmt.resource.resources.operations.providers_operations#ProvidersOperations.list', cf_providers)
cli_command(__name__, 'provider show', 'azure.mgmt.resource.resources.operations.providers_operations#ProvidersOperations.get', cf_providers, exception_handler=empty_on_404)
cli_command(__name__, 'provider register', 'azure.cli.command_modules.resource.custom#register_provider')
cli_command(__name__, 'provider unregister', 'azure.cli.command_modules.resource.custom#unregister_provider')
cli_command(__name__, 'provider operation list', 'azure.cli.command_modules.resource.custom#list_provider_operations')
cli_command(__name__, 'provider operation show', 'azure.cli.command_modules.resource.custom#show_provider_operations')

if supported_api_version(ResourceType.MGMT_RESOURCE_RESOURCES, min_api='2017-05-10'):
    # Resource feature commands
    feature_table_transform = '{Name:name, RegistrationState:properties.state}'
    cli_command(__name__, 'feature list', 'azure.cli.command_modules.resource.custom#list_features', cf_features, table_transformer='[].' + feature_table_transform)
    cli_command(__name__, 'feature show', 'azure.mgmt.resource.features.operations.features_operations#FeaturesOperations.get', cf_features, exception_handler=empty_on_404, table_transformer=feature_table_transform)
    cli_command(__name__, 'feature register', 'azure.cli.command_modules.resource.custom#register_feature', cf_features)

# Tag commands
cli_command(__name__, 'tag list', 'azure.mgmt.resource.resources.operations.tags_operations#TagsOperations.list', cf_tags)
cli_command(__name__, 'tag create', 'azure.mgmt.resource.resources.operations.tags_operations#TagsOperations.create_or_update', cf_tags)
cli_command(__name__, 'tag delete', 'azure.mgmt.resource.resources.operations.tags_operations#TagsOperations.delete', cf_tags)
cli_command(__name__, 'tag add-value', 'azure.mgmt.resource.resources.operations.tags_operations#TagsOperations.create_or_update_value', cf_tags)
cli_command(__name__, 'tag remove-value', 'azure.mgmt.resource.resources.operations.tags_operations#TagsOperations.delete_value', cf_tags)


# Resource group deployment commands
示例#47
0
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):

    # set the default names
    frontend_ip_name = 'appGatewayFrontendIP'
    backend_pool_name = 'appGatewayBackendPool'
    frontend_port_name = 'appGatewayFrontendPort'
    http_listener_name = 'appGatewayHttpListener'
    http_settings_name = 'appGatewayBackendHttpSettings'
    routing_rule_name = 'rule1'
    ssl_cert_name = '{}SslCert'.format(name)

    ssl_cert = None

    frontend_ip_config = _build_frontend_ip_config(frontend_ip_name, public_ip_id, subnet_id,
                                                   private_ip_address, private_ip_allocation)
    backend_address_pool = {'name': backend_pool_name}
    if servers:
        backend_address_pool['properties'] = {'BackendAddresses': servers}

    def _ag_subresource_id(_type, name):
        return "[concat(variables('appGwID'), '/{}/{}')]".format(_type, name)

    frontend_ip_config_id = _ag_subresource_id('frontendIPConfigurations', frontend_ip_name)
    frontend_port_id = _ag_subresource_id('frontendPorts', frontend_port_name)
    http_listener_id = _ag_subresource_id('httpListeners', http_listener_name)
    backend_address_pool_id = _ag_subresource_id('backendAddressPools', backend_pool_name)
    backend_http_settings_id = _ag_subresource_id('backendHttpSettingsCollection',
                                                  http_settings_name)
    ssl_cert_id = _ag_subresource_id('sslCertificates', ssl_cert_name)

    http_listener = {
        'name': http_listener_name,
        'properties': {
            'FrontendIpConfiguration': {'Id': frontend_ip_config_id},
            'FrontendPort': {'Id': frontend_port_id},
            'Protocol': http_listener_protocol,
            'SslCertificate': None
        }
    }
    if cert_data:
        http_listener['properties'].update({'SslCertificate': {'id': ssl_cert_id}})
        ssl_cert = {
            'name': ssl_cert_name,
            'properties': {
                'data': cert_data,
                'password': cert_password
            }
        }

    backend_http_settings = {
        'name': http_settings_name,
        'properties': {
            'Port': http_settings_port,
            'Protocol': http_settings_protocol,
            'CookieBasedAffinity': cookie_based_affinity
        }
    }
    if supported_api_version(ResourceType.MGMT_NETWORK, min_api='2016-12-01'):
        backend_http_settings['properties']['connectionDraining'] = {
            'enabled': bool(connection_draining_timeout),
            'drainTimeoutInSec': connection_draining_timeout if connection_draining_timeout else 1
        }

    ag_properties = {
        'backendAddressPools': [backend_address_pool],
        'backendHttpSettingsCollection': [backend_http_settings],
        'frontendIPConfigurations': [frontend_ip_config],
        'frontendPorts': [
            {
                'name': frontend_port_name,
                'properties': {
                    'Port': frontend_port
                }
            }
        ],
        'gatewayIPConfigurations': [
            {
                'name': frontend_ip_name,
                'properties': {
                    'subnet': {'id': subnet_id}
                }
            }
        ],
        'httpListeners': [http_listener],
        'sku': {
            'name': sku_name,
            'tier': sku_tier,
            'capacity': capacity
        },
        'requestRoutingRules': [
            {
                'Name': routing_rule_name,
                'properties': {
                    'RuleType': routing_rule_type,
                    'httpListener': {'id': http_listener_id},
                    'backendAddressPool': {'id': backend_address_pool_id},
                    'backendHttpSettings': {'id': backend_http_settings_id}
                }
            }
        ]
    }
    if ssl_cert:
        ag_properties.update({'sslCertificates': [ssl_cert]})

    ag = {
        'type': 'Microsoft.Network/applicationGateways',
        'name': name,
        'location': location,
        'tags': tags,
        'apiVersion': get_api_version(ResourceType.MGMT_NETWORK),
        'dependsOn': [],
        'properties': ag_properties
    }
    return ag
示例#48
0
 def test_supported_api_version_invalid_profile_name(self):
     # Invalid name for the profile name
     cli = TestCli()
     cli.cloud = Cloud('TestCloud', profile='not-a-real-profile')
     with self.assertRaises(ValueError):
         supported_api_version(cli, PROFILE_TYPE, min_api='2000-01-01')
示例#49
0
cli_command(__name__, 'vm list', custom_path.format('list_vm'), table_transformer=transform_vm_list)
cli_command(__name__, 'vm resize', custom_path.format('resize_vm'), no_wait_param='no_wait')
cli_command(__name__, 'vm capture', custom_path.format('capture_vm'))
cli_command(__name__, 'vm open-port', custom_path.format('vm_open_port'))
cli_command(__name__, 'vm format-secret', custom_path.format('get_vm_format_secret'), deprecate_info='az vm secret format')
cli_command(__name__, 'vm secret format', custom_path.format('get_vm_format_secret'))
cli_command(__name__, 'vm secret add', custom_path.format('add_vm_secret'))
cli_command(__name__, 'vm secret list', custom_path.format('list_vm_secrets'))
cli_command(__name__, 'vm secret remove', custom_path.format('remove_vm_secret'))
cli_generic_update_command(__name__, 'vm update',
                           mgmt_path.format(op_var, op_class, 'get'),
                           mgmt_path.format(op_var, op_class, 'create_or_update'),
                           cf_vm,
                           no_wait_param='raw')
cli_generic_wait_command(__name__, 'vm wait', 'azure.cli.command_modules.vm.custom#get_instance_view')
if supported_api_version(ResourceType.MGMT_COMPUTE, min_api='2017-03-30'):
    cli_command(__name__, 'vm perform-maintenance', mgmt_path.format(op_var, op_class, 'perform_maintenance'), cf_vm)


if supported_api_version(ResourceType.MGMT_COMPUTE, min_api='2016-04-30-preview'):
    cli_command(__name__, 'vm convert', mgmt_path.format(op_var, op_class, 'convert_to_managed_disks'), cf_vm)

# VM encryption
cli_command(__name__, 'vm encryption enable', 'azure.cli.command_modules.vm.disk_encryption#encrypt_vm')
cli_command(__name__, 'vm encryption disable', 'azure.cli.command_modules.vm.disk_encryption#decrypt_vm')
cli_command(__name__, 'vm encryption show', 'azure.cli.command_modules.vm.disk_encryption#show_vm_encryption_status', exception_handler=empty_on_404)

# VMSS encryption
if supported_api_version(ResourceType.MGMT_COMPUTE, min_api='2017-03-30'):
    cli_command(__name__, 'vmss encryption enable', 'azure.cli.command_modules.vm.disk_encryption#encrypt_vmss')
    cli_command(__name__, 'vmss encryption disable', 'azure.cli.command_modules.vm.disk_encryption#decrypt_vmss')
示例#50
0
 def register_extra_cli_argument(self, *args, **kwargs):
     if supported_api_version(self._type,
                              min_api=self._min_api,
                              max_api=self._max_api):
         register_extra_cli_argument(*args, **kwargs)
示例#51
0
def api_version_constraint(resource_type, **kwargs):
    return unittest.skipUnless(supported_api_version(resource_type, **kwargs),
                               "Test not supported by current profile.")
示例#52
0
 def cli_command(self, *args, **kwargs):
     if supported_api_version(self._type,
                              min_api=self._min_api,
                              max_api=self._max_api):
         cli_command(*args, **kwargs)
示例#53
0
 def __init__(self, cli_ctx):
     self.old_api = supported_api_version(
         cli_ctx,
         resource_type=ResourceType.MGMT_AUTHORIZATION,
         max_api='2015-07-01')
     self.cli_ctx = cli_ctx
示例#54
0

# storage account commands
factory = lambda kwargs: storage_client_factory().storage_accounts  # noqa: E731 lambda vs def
cli_command(__name__, 'storage account check-name', mgmt_path + 'check_name_availability', factory)
cli_command(__name__, 'storage account delete', mgmt_path + 'delete', factory, confirmation=True)
cli_command(__name__, 'storage account show', mgmt_path + 'get_properties', factory, exception_handler=empty_on_404)
cli_command(__name__, 'storage account list', custom_path + 'list_storage_accounts')
cli_command(__name__, 'storage account show-usage', custom_path + 'show_storage_account_usage')
cli_command(__name__, 'storage account show-connection-string', custom_path + 'show_storage_account_connection_string')
cli_command(__name__, 'storage account keys renew', mgmt_path + 'regenerate_key', factory, transform=lambda x: getattr(x, 'keys', x))
cli_command(__name__, 'storage account keys list', mgmt_path + 'list_keys', factory, transform=lambda x: getattr(x, 'keys', x))
cli_command(__name__, 'storage account create', custom_path + 'create_storage_account_with_account_type', max_api='2015-06-15')
cli_command(__name__, 'storage account create', custom_path + 'create_storage_account', min_api='2016-12-01')

if supported_api_version(ResourceType.MGMT_STORAGE, min_api='2016-12-01'):
    cli_generic_update_command(__name__, 'storage account update',
                               mgmt_path + 'get_properties',
                               mgmt_path + 'update', factory,
                               custom_function_op=custom_path + 'update_storage_account')

cli_storage_data_plane_command('storage account generate-sas', 'azure.multiapi.storage.cloudstorageaccount#CloudStorageAccount.generate_shared_access_signature', cloud_storage_account_service_factory)

# container commands
factory = blob_data_service_factory
cli_storage_data_plane_command('storage container list', block_blob_path + 'list_containers', factory, transform=transform_storage_list_output, table_transformer=transform_container_list)
cli_storage_data_plane_command('storage container delete', block_blob_path + 'delete_container', factory, transform=create_boolean_result_output_transformer('deleted'), table_transformer=transform_boolean_for_table)
cli_storage_data_plane_command('storage container show', block_blob_path + 'get_container_properties', factory, table_transformer=transform_container_show, exception_handler=_dont_fail_not_exist)
cli_storage_data_plane_command('storage container create', block_blob_path + 'create_container', factory, transform=create_boolean_result_output_transformer('created'), table_transformer=transform_boolean_for_table)
cli_storage_data_plane_command('storage container generate-sas', block_blob_path + 'generate_container_shared_access_signature', factory)
cli_storage_data_plane_command('storage container metadata update', block_blob_path + 'set_container_metadata', factory)
示例#55
0
 def test_supported_api_profile_max_constraint_not_supported(self):
     cli = TestCli()
     cli.cloud = Cloud('TestCloud', profile='2000-01-01-profile')
     self.assertFalse(
         supported_api_version(cli, PROFILE_TYPE, max_api='1999-12-30'))
示例#56
0
 def test_supported_api_profile_latest(self):
     cli = DummyCli()
     cli.cloud = Cloud('TestCloud', profile='latest')
     self.assertTrue(
         supported_api_version(cli, PROFILE_TYPE, min_api='2000-01-01'))