def test_get_api_version_invalid_rt_2(self):
     # None is not a valid resource type
     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):
             get_api_version(cli, None)
 def test_get_api_version_invalid_active_profile(self):
     # The active profile is not in our profile dict
     cli = DummyCli()
     cli.cloud = Cloud('TestCloud', profile='not-a-real-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):
             get_api_version(cli, ResourceType.MGMT_STORAGE)
Beispiel #3
0
 def test_get_api_version_invalid_rt_2(self):
     ''' None is not a valid resource type '''
     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):
             get_api_version(None)
Beispiel #4
0
 def test_get_api_version_invalid_rt(self):
     # Resource Type not in 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):
             get_api_version(ResourceType.MGMT_COMPUTE)
Beispiel #5
0
 def test_get_api_version_invalid_active_profile(self):
     ''' The active profile is not in our profile dict '''
     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):
             get_api_version(ResourceType.MGMT_STORAGE)
 def test_get_api_version_invalid_rt_2(self):
     # None is not a valid resource type
     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):
             get_api_version(cli, None)
Beispiel #7
0
 def test_get_api_version_invalid_active_profile(self):
     # The active profile is not in our profile dict
     cli = TestCli()
     cli.cloud = Cloud('TestCloud', profile='not-a-real-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):
             get_api_version(cli, ResourceType.MGMT_STORAGE)
Beispiel #8
0
def get_mgmt_service_client(cli_ctx, client_or_resource_type, subscription_id=None, api_version=None,
                            aux_subscriptions=None, **kwargs):
    """
     :params subscription_id: the current account's subscription
     :param aux_subscriptions: mainly for cross tenant scenarios, say vnet peering.
    """
    if not subscription_id and 'subscription_id' in cli_ctx.data:
        subscription_id = cli_ctx.data['subscription_id']

    sdk_profile = None
    if isinstance(client_or_resource_type, (ResourceType, CustomResourceType)):
        # Get the versioned client
        client_type = get_client_class(client_or_resource_type)
        api_version = api_version or get_api_version(cli_ctx, client_or_resource_type, as_sdk_profile=True)
        if isinstance(api_version, SDKProfile):
            sdk_profile = api_version.profile
            api_version = None
    else:
        # Get the non-versioned client
        client_type = client_or_resource_type
    client, _ = _get_mgmt_service_client(cli_ctx, client_type, subscription_id=subscription_id,
                                         api_version=api_version, sdk_profile=sdk_profile,
                                         aux_subscriptions=aux_subscriptions,
                                         **kwargs)
    return client
Beispiel #9
0
def build_vm_msi_extension(vm_name, location, role_assignment_guid, port,
                           is_linux, extension_version):
    ext_type_name = 'ManagedIdentityExtensionFor' + ('Linux' if is_linux else
                                                     'Windows')
    return {
        'type':
        'Microsoft.Compute/virtualMachines/extensions',
        'name':
        vm_name + '/' + ext_type_name,
        'apiVersion':
        get_api_version(ResourceType.MGMT_COMPUTE).virtual_machine_extensions,
        'location':
        location,
        'dependsOn': [
            role_assignment_guid
            or 'Microsoft.Compute/virtualMachines/' + vm_name
        ],
        'properties': {
            'publisher': "Microsoft.ManagedIdentity",
            'type': ext_type_name,
            'typeHandlerVersion': extension_version,
            'autoUpgradeMinorVersion': True,
            'settings': {
                'port': port
            }
        }
    }
Beispiel #10
0
def get_mgmt_service_client(cli_ctx,
                            client_or_resource_type,
                            subscription_id=None,
                            api_version=None,
                            aux_subscriptions=None,
                            aux_tenants=None,
                            **kwargs):
    """
     :params subscription_id: the current account's subscription
     :param aux_subscriptions: mainly for cross tenant scenarios, say vnet peering.
    """
    if not subscription_id and 'subscription_id' in cli_ctx.data:
        subscription_id = cli_ctx.data['subscription_id']

    sdk_profile = None
    if isinstance(client_or_resource_type, (ResourceType, CustomResourceType)):
        # Get the versioned client
        client_type = get_client_class(client_or_resource_type)
        api_version = api_version or get_api_version(
            cli_ctx, client_or_resource_type, as_sdk_profile=True)
        if isinstance(api_version, SDKProfile):
            sdk_profile = api_version.profile
            api_version = None
    else:
        # Get the non-versioned client
        client_type = client_or_resource_type
    client, _ = _get_mgmt_service_client(cli_ctx,
                                         client_type,
                                         subscription_id=subscription_id,
                                         api_version=api_version,
                                         sdk_profile=sdk_profile,
                                         aux_subscriptions=aux_subscriptions,
                                         aux_tenants=aux_tenants,
                                         **kwargs)
    return client
Beispiel #11
0
def get_subscription_service_client(cli_ctx):
    return _get_mgmt_service_client(
        cli_ctx,
        get_client_class(ResourceType.MGMT_RESOURCE_SUBSCRIPTIONS),
        subscription_bound=False,
        api_version=get_api_version(cli_ctx,
                                    ResourceType.MGMT_RESOURCE_SUBSCRIPTIONS))
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
Beispiel #13
0
def keyvault_private_data_plane_factory_v7_2_preview(cli_ctx, _):
    from azure.cli.command_modules.keyvault.vendored_sdks.azure_keyvault_t1 import (
        KeyVaultAuthentication, KeyVaultClient)
    from azure.cli.core.util import should_disable_connection_verify

    version = str(get_api_version(cli_ctx, ResourceType.DATA_PRIVATE_KEYVAULT))

    def get_token(server, resource, scope):  # pylint: disable=unused-argument
        return Profile(cli_ctx=cli_ctx).get_raw_token(
            resource=resource,
            subscription=cli_ctx.data.get('subscription_id'))[0]

    client = KeyVaultClient(KeyVaultAuthentication(get_token),
                            api_version=version)

    # HACK, work around the fact that KeyVault library does't take confiuration object on constructor
    # which could be used to turn off the verifiaction. Remove this once we migrate to new data plane library
    # pylint: disable=protected-access
    if hasattr(client, '_client') and hasattr(client._client, 'config'):
        verify = not should_disable_connection_verify()
        client._client.config.connection.verify = verify
    else:
        logger.info(
            'Could not find the configuration object to turn off the verification if needed'
        )

    return client
Beispiel #14
0
def get_docs_tmpl(cli_ctx,
                  resource_type,
                  client_name,
                  module_name='operations'):
    if resource_type in [
            ResourceType.DATA_KEYVAULT_ADMINISTRATION_BACKUP,
            ResourceType.DATA_KEYVAULT_ADMINISTRATION_ACCESS_CONTROL,
            ResourceType.DATA_KEYVAULT_KEYS
    ]:
        return KEYVAULT_TEMPLATE_STRINGS[resource_type].format(obj_name='.{}')

    api_version = get_api_version(cli_ctx, resource_type, as_sdk_profile=True)
    from azure.cli.core.profiles import SDKProfile
    if isinstance(api_version, SDKProfile):
        api_version = api_version.profile[client_name] if api_version.profile.get(client_name, None) else \
            api_version.profile[None]
    api_version = '.v' + api_version.replace('.', '_').replace('-', '_')
    if is_mgmt_plane(resource_type):
        class_name = OPERATIONS_NAME.get(
            client_name, '') + '.' if module_name == 'operations' else ''
    else:
        class_name = 'KeyVaultClient.'
    return KEYVAULT_TEMPLATE_STRINGS[resource_type].format(
        api_version=api_version,
        module_name=module_name,
        class_name=class_name,
        obj_name='{}')
Beispiel #15
0
 def test_get_api_version_semver(self):
     # Can get correct resource type API version if semver used
     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.assertEqual(get_api_version(cli, ResourceType.MGMT_KEYVAULT), '7.0')
Beispiel #16
0
def _get_network_client(cli_ctx, subscription_id=None):
    from azure.cli.core.profiles import ResourceType, get_api_version
    from azure.cli.core.commands.client_factory import get_mgmt_service_client
    return get_mgmt_service_client(cli_ctx,
                                   ResourceType.MGMT_NETWORK,
                                   subscription_id=subscription_id,
                                   api_version=get_api_version(cli_ctx, ResourceType.MGMT_NETWORK))
Beispiel #17
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).availability_sets  # pylint: disable=no-member
    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').availability_sets:  # pylint: disable=no-member
        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
Beispiel #18
0
def get_network_watcher_from_resource(namespace):
    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)
Beispiel #19
0
 def test_get_api_version(self):
     # Can get correct resource type API version
     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.assertEqual(get_api_version(cli, ResourceType.MGMT_STORAGE), '2020-10-10')
Beispiel #20
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_config = _build_frontend_ip_config(frontend_ip_name, public_ip_id, subnet_id, private_ip_address,
                                                   private_ip_allocation)

    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
Beispiel #21
0
def create_keyvault_data_plane_client(cli_ctx):
    from azure.cli.core._profile import Profile
    from azure.cli.core.profiles import get_api_version, ResourceType
    version = str(get_api_version(cli_ctx, ResourceType.DATA_KEYVAULT))

    def get_token(server, resource, scope):  # pylint: disable=unused-argument
        return Profile(cli_ctx=cli_ctx).get_login_credentials(resource)[0]._token_retriever()  # pylint: disable=protected-access

    from azure.keyvault import KeyVaultAuthentication, KeyVaultClient
    return KeyVaultClient(KeyVaultAuthentication(get_token), api_version=version)
Beispiel #22
0
 def create_arm_client_factory(credentials):
     if arm_client_factory:
         return arm_client_factory(credentials)
     from azure.cli.core.profiles._shared import get_client_class
     from azure.cli.core.profiles import ResourceType, get_api_version
     from azure.cli.core._debug import change_ssl_cert_verification
     client_type = get_client_class(ResourceType.MGMT_RESOURCE_SUBSCRIPTIONS)
     api_version = get_api_version(cli_ctx, ResourceType.MGMT_RESOURCE_SUBSCRIPTIONS)
     return change_ssl_cert_verification(client_type(credentials, api_version=api_version,
                                                     base_url=self.cli_ctx.cloud.endpoints.resource_manager))
Beispiel #23
0
def get_target_network_api(cli_ctx):
    """ Since most compute calls don't need advanced network functionality, we can target a supported, but not
        necessarily latest, network API version is order to avoid having to re-record every test that uses VM create
        (which there are a lot) whenever NRP bumps their API version (which is often)!
    """
    from azure.cli.core.profiles import get_api_version, ResourceType
    version = get_api_version(cli_ctx, ResourceType.MGMT_NETWORK)
    if cli_ctx.cloud.profile == 'latest':
        version = '2018-01-01'
    return version
Beispiel #24
0
 def create_arm_client_factory(credentials):
     if arm_client_factory:
         return arm_client_factory(credentials)
     from azure.cli.core.profiles._shared import get_client_class
     from azure.cli.core.profiles import get_api_version, ResourceType
     from azure.cli.core._debug import change_ssl_cert_verification
     client_type = get_client_class(ResourceType.MGMT_RESOURCE_SUBSCRIPTIONS)
     api_version = get_api_version(ResourceType.MGMT_RESOURCE_SUBSCRIPTIONS)
     return change_ssl_cert_verification(client_type(credentials, api_version=api_version,
                                                     base_url=CLOUD.endpoints.resource_manager))
Beispiel #25
0
def get_target_network_api(cli_ctx):
    """ Since most compute calls don't need advanced network functionality, we can target a supported, but not
        necessarily latest, network API version is order to avoid having to re-record every test that uses VM create
        (which there are a lot) whenever NRP bumps their API version (which is often)!
    """
    from azure.cli.core.profiles import get_api_version, ResourceType
    version = get_api_version(cli_ctx, ResourceType.MGMT_NETWORK)
    if cli_ctx.cloud.profile == 'latest':
        version = '2018-01-01'
    return version
Beispiel #26
0
 def get_api_version(self, resource_type=None, operation_group=None):
     from azure.cli.core.profiles import get_api_version
     resource_type = resource_type or self._get_resource_type()
     version = get_api_version(self.cli_ctx, resource_type)
     if isinstance(version, str):
         return version
     version = getattr(version, operation_group, None)
     if version:
         return version
     from azure.cli.core.profiles._shared import APIVersionException
     raise APIVersionException(operation_group, self.cli_ctx.cloud.profile)
Beispiel #27
0
 def get_api_version(self, resource_type=None, operation_group=None):
     from azure.cli.core.profiles import get_api_version
     resource_type = resource_type or self._get_resource_type()
     version = get_api_version(self.cli_ctx, resource_type)
     if isinstance(version, str):
         return version
     version = getattr(version, operation_group, None)
     if version:
         return version
     from azure.cli.core.profiles._shared import APIVersionException
     raise APIVersionException(operation_group, self.cli_ctx.cloud.profile)
Beispiel #28
0
 def test_get_api_version(self):
     ''' Can get correct resource type API version '''
     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.assertEqual(get_api_version(ResourceType.MGMT_STORAGE),
                          '2020-10-10')
Beispiel #29
0
 def completer(cmd, prefix, namespace, **kwargs):  # pylint: disable=unused-argument
     from azure.keyvault import KeyVaultAuthentication, KeyVaultClient
     from azure.cli.core.profiles import ResourceType, get_api_version
     version = str(get_api_version(cmd.cli_ctx, ResourceType.DATA_KEYVAULT))
     client = KeyVaultClient(KeyVaultAuthentication(_get_token), api_version=version)
     func_name = 'get_{}s'.format(resource_name)
     vault = namespace.vault_base_url
     items = []
     for y in list(getattr(client, func_name)(vault)):
         id_val = getattr(y, 'id', None) or getattr(y, 'kid', None)
         items.append(id_val.rsplit('/', 1)[1])
     return items
Beispiel #30
0
def get_mgmt_service_client(client_or_resource_type, subscription_id=None, api_version=None,
                            **kwargs):
    if isinstance(client_or_resource_type, ResourceType):
        # Get the versioned client
        client_type = get_client_class(client_or_resource_type)
        api_version = api_version or get_api_version(client_or_resource_type)
    else:
        # Get the non-versioned client
        client_type = client_or_resource_type
    client, _ = _get_mgmt_service_client(client_type, subscription_id=subscription_id,
                                         api_version=api_version, **kwargs)
    return client
Beispiel #31
0
 def completer(cmd, prefix, namespace, **kwargs):  # pylint: disable=unused-argument
     from azure.keyvault import KeyVaultAuthentication, KeyVaultClient
     from azure.cli.core.profiles import ResourceType, get_api_version
     version = str(get_api_version(cmd.cli_ctx, ResourceType.DATA_KEYVAULT))
     client = KeyVaultClient(KeyVaultAuthentication(_get_token), api_version=version)
     func_name = 'get_{}s'.format(resource_name)
     vault = namespace.vault_base_url
     items = []
     for y in list(getattr(client, func_name)(vault)):
         id_val = getattr(y, 'id', None) or getattr(y, 'kid', None)
         items.append(id_val.rsplit('/', 1)[1])
     return items
Beispiel #32
0
def _prepare_data_plane_azure_keyvault_client(cli_ctx, command_args,
                                              resource_type):
    version = str(get_api_version(cli_ctx, resource_type))
    profile = Profile(cli_ctx=cli_ctx)
    credential, _, _ = profile.get_login_credentials()
    vault_url = \
        command_args.get('hsm_name', None) or \
        command_args.get('vault_base_url', None) or \
        command_args.get('identifier', None)
    if not vault_url:
        raise RequiredArgumentMissingError('Please specify --hsm-name or --id')
    return vault_url, credential, version
 def test_get_api_version_semver(self):
     # Can get correct resource type API version if semver used
     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.assertEqual(get_api_version(cli, ResourceType.MGMT_KEYVAULT),
                          '7.0')
Beispiel #34
0
 def test_get_api_version(self):
     # Can get correct resource type API version
     cli = TestCli()
     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.assertEqual(get_api_version(cli, ResourceType.MGMT_STORAGE),
                          '2020-10-10')
Beispiel #35
0
def build_vm_msi_extension(vm_name, location, role_assignment_guid, port, is_linux, extension_version):
    return {
        'type': 'Microsoft.Compute/virtualMachines/extensions',
        'name': vm_name + '/MSIExtension',
        'apiVersion': get_api_version(ResourceType.MGMT_COMPUTE),
        'location': location,
        'dependsOn': [role_assignment_guid or 'Microsoft.Compute/virtualMachines/' + vm_name],
        'properties': {
            'publisher': "Microsoft.ManagedIdentity",
            'type': 'ManagedIdentityExtensionFor' + ('Linux' if is_linux else 'Windows'),
            'typeHandlerVersion': extension_version,
            'autoUpgradeMinorVersion': True,
            'settings': {'port': port}
        }
    }
Beispiel #36
0
def get_mgmt_service_client(cli_ctx, client_or_resource_type, subscription_id=None, api_version=None,
                            **kwargs):
    sdk_profile = None
    if isinstance(client_or_resource_type, (ResourceType, CustomResourceType)):
        # Get the versioned client
        client_type = get_client_class(client_or_resource_type)
        api_version = api_version or get_api_version(cli_ctx, client_or_resource_type, as_sdk_profile=True)
        if isinstance(api_version, SDKProfile):
            sdk_profile = api_version.profile
            api_version = None
    else:
        # Get the non-versioned client
        client_type = client_or_resource_type
    client, _ = _get_mgmt_service_client(cli_ctx, client_type, subscription_id=subscription_id,
                                         api_version=api_version, sdk_profile=sdk_profile, **kwargs)
    return client
Beispiel #37
0
def get_mgmt_service_client(client_or_resource_type,
                            subscription_id=None,
                            api_version=None,
                            **kwargs):
    if isinstance(client_or_resource_type, ResourceType):
        # Get the versioned client
        client_type = get_client_class(client_or_resource_type)
        api_version = api_version or get_api_version(client_or_resource_type)
    else:
        # Get the non-versioned client
        client_type = client_or_resource_type
    client, _ = _get_mgmt_service_client(client_type,
                                         subscription_id=subscription_id,
                                         api_version=api_version,
                                         **kwargs)
    return client
Beispiel #38
0
def data_plane_azure_keyvault_administration_access_control_client(
        cli_ctx, command_args):
    from azure.keyvault.administration import KeyVaultAccessControlClient

    version = str(
        get_api_version(
            cli_ctx, ResourceType.DATA_KEYVAULT_ADMINISTRATION_ACCESS_CONTROL))
    profile = Profile(cli_ctx=cli_ctx)
    credential, _, _ = profile.get_login_credentials(
        resource='https://managedhsm.azure.net')
    vault_url = command_args['hsm_name']
    if not vault_url:
        vault_url = command_args['vault_base_url']
    return KeyVaultAccessControlClient(vault_url=vault_url,
                                       credential=credential,
                                       api_version=version)
Beispiel #39
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
Beispiel #40
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,
        'sku': {
            'name': 'Classic' if unmanaged else 'Aligned'
        },
        "properties": {
            'platformUpdateDomainCount': platform_update_domain_count,
            'platformFaultDomainCount': platform_fault_domain_count,
        }
    }
    return av_set
Beispiel #41
0
def build_public_ip_resource(name, location, tags, address_allocation, dns_name, sku):
    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}
    return public_ip
Beispiel #42
0
def build_public_ip_resource(name, location, tags, address_allocation, dns_name, sku):
    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}
    return public_ip
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,
        'sku': {
            'name': 'Classic' if unmanaged else 'Aligned'
        },
        "properties": {
            'platformUpdateDomainCount': platform_update_domain_count,
            'platformFaultDomainCount': platform_fault_domain_count,
        }
    }
    return av_set
Beispiel #44
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
Beispiel #45
0
def data_plane_azure_keyvault_administration_access_control_client(
        cli_ctx, command_args):
    from azure.keyvault.administration import KeyVaultAccessControlClient

    version = str(
        get_api_version(
            cli_ctx, ResourceType.DATA_KEYVAULT_ADMINISTRATION_ACCESS_CONTROL))
    profile = Profile(cli_ctx=cli_ctx)
    credential, _, _ = profile.get_login_credentials(
        resource='https://managedhsm.azure.net')
    vault_url = \
        command_args.get('hsm_name', None) or \
        command_args.get('vault_base_url', None) or \
        command_args.get('identifier', None)
    if not vault_url:
        raise RequiredArgumentMissingError('Please specify --hsm-name or --id')
    return KeyVaultAccessControlClient(vault_url=vault_url,
                                       credential=credential,
                                       api_version=version)
Beispiel #46
0
def keyvault_data_plane_factory(cli_ctx, _):
    from azure.keyvault import KeyVaultAuthentication, KeyVaultClient
    from azure.cli.core.profiles import ResourceType, get_api_version
    version = str(get_api_version(cli_ctx, ResourceType.DATA_KEYVAULT))

    def get_token(server, resource, scope):  # pylint: disable=unused-argument
        import adal
        from azure.cli.core._profile import Profile
        try:
            return Profile(cli_ctx=cli_ctx).get_raw_token(resource)[0]
        except adal.AdalError as err:
            from knack.util import CLIError
            # pylint: disable=no-member
            if (hasattr(err, 'error_response') and
                    ('error_description' in err.error_response) and
                    ('AADSTS70008:' in err.error_response['error_description'])):
                raise CLIError(
                    "Credentials have expired due to inactivity. Please run 'az login'")
            raise CLIError(err)

    return KeyVaultClient(KeyVaultAuthentication(get_token), api_version=version)
Beispiel #47
0
def keyvault_private_data_plane_factory_v7_2_preview(cli_ctx, _):
    from azure.cli.command_modules.keyvault.vendored_sdks.azure_keyvault_t1 import (
        KeyVaultAuthentication, KeyVaultClient)
    from azure.cli.core.util import should_disable_connection_verify

    version = str(get_api_version(cli_ctx, ResourceType.DATA_PRIVATE_KEYVAULT))

    def get_token(server, resource, scope):  # pylint: disable=unused-argument
        import adal
        try:
            return Profile(cli_ctx=cli_ctx).get_raw_token(
                resource=resource,
                subscription=cli_ctx.data.get('subscription_id'))[0]
        except adal.AdalError as err:
            # pylint: disable=no-member
            if (hasattr(err, 'error_response')
                    and ('error_description' in err.error_response) and
                ('AADSTS70008:' in err.error_response['error_description'])):
                raise CLIError(
                    "Credentials have expired due to inactivity. Please run 'az login'"
                )
            raise CLIError(err)

    client = KeyVaultClient(KeyVaultAuthentication(get_token),
                            api_version=version)

    # HACK, work around the fact that KeyVault library does't take confiuration object on constructor
    # which could be used to turn off the verifiaction. Remove this once we migrate to new data plane library
    # pylint: disable=protected-access
    if hasattr(client, '_client') and hasattr(client._client, 'config'):
        verify = not should_disable_connection_verify()
        client._client.config.connection.verify = verify
    else:
        from knack.log import get_logger
        logger = get_logger(__name__)
        logger.info(
            'Could not find the configuration object to turn off the verification if needed'
        )

    return client
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
Beispiel #49
0
def load_command_table(self, _):
    mgmt_api_version = str(get_api_version(self.cli_ctx, ResourceType.MGMT_KEYVAULT))
    mgmt_api_version = mgmt_api_version.replace('-', '_')
    data_api_version = str(get_api_version(self.cli_ctx, ResourceType.DATA_KEYVAULT))
    data_api_version = data_api_version.replace('.', '_')
    data_api_version = data_api_version.replace('-', '_')
    data_doc_string = 'azure.keyvault.v' + data_api_version + '.key_vault_client#KeyVaultClient.{}'
    # region Command Types
    kv_vaults_custom = CliCommandType(
        operations_tmpl='azure.cli.command_modules.keyvault.custom#{}',
        client_factory=keyvault_client_vaults_factory
    )

    kv_vaults_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.keyvault.operations.vaults_operations#VaultsOperations.{}',
        client_factory=keyvault_client_vaults_factory,
        resource_type=ResourceType.MGMT_KEYVAULT
    )

    kv_data_sdk = CliCommandType(
        operations_tmpl='azure.keyvault.key_vault_client#KeyVaultClient.{}',
        client_factory=keyvault_data_plane_factory,
        resource_type=ResourceType.DATA_KEYVAULT
    )
    # endregion

    # Management Plane Commands
    with self.command_group('keyvault', kv_vaults_sdk, client_factory=keyvault_client_vaults_factory) as g:
        g.custom_command('create', 'create_keyvault',
                         doc_string_source='azure.mgmt.keyvault.v' + mgmt_api_version + '.models#VaultProperties')
        g.custom_command('recover', 'recover_keyvault')
        g.custom_command('list', 'list_keyvault')
        g.show_command('show', 'get')
        g.command('delete', 'delete')
        g.command('purge', 'purge_deleted')
        g.custom_command('set-policy', 'set_policy')
        g.custom_command('delete-policy', 'delete_policy')
        g.command('list-deleted', 'list_deleted')
        g.generic_update_command('update', setter_name='update_keyvault_setter', setter_type=kv_vaults_custom,
                                 custom_func_name='update_keyvault')

    with self.command_group('keyvault network-rule',
                            kv_vaults_sdk,
                            min_api='2018-02-14',
                            client_factory=keyvault_client_vaults_factory) as g:
        g.custom_command('add', 'add_network_rule')
        g.custom_command('remove', 'remove_network_rule')
        g.custom_command('list', 'list_network_rules')

    # Data Plane Commands
    with self.command_group('keyvault key', kv_data_sdk) as g:
        g.keyvault_command('list', 'get_keys')
        g.keyvault_command('list-versions', 'get_key_versions')
        g.keyvault_command('list-deleted', 'get_deleted_keys')
        g.keyvault_custom('create', 'create_key', doc_string_source=data_doc_string.format('create_key'))
        g.keyvault_command('set-attributes', 'update_key')
        g.keyvault_command('show', 'get_key')
        g.keyvault_command('show-deleted', 'get_deleted_key')
        g.keyvault_command('delete', 'delete_key')
        g.keyvault_command('purge', 'purge_deleted_key')
        g.keyvault_command('recover', 'recover_deleted_key')
        g.keyvault_custom('backup', 'backup_key', doc_string_source=data_doc_string.format('backup_key'))
        g.keyvault_custom('restore', 'restore_key', doc_string_source=data_doc_string.format('restore_key'))
        g.keyvault_custom('import', 'import_key')

    with self.command_group('keyvault secret', kv_data_sdk) as g:
        g.keyvault_command('list', 'get_secrets')
        g.keyvault_command('list-versions', 'get_secret_versions')
        g.keyvault_command('list-deleted', 'get_deleted_secrets')
        g.keyvault_command('set', 'set_secret', validator=process_secret_set_namespace)
        g.keyvault_command('set-attributes', 'update_secret')
        g.keyvault_command('show', 'get_secret')
        g.keyvault_command('show-deleted', 'get_deleted_secret')
        g.keyvault_command('delete', 'delete_secret')
        g.keyvault_command('purge', 'purge_deleted_secret')
        g.keyvault_command('recover', 'recover_deleted_secret')
        g.keyvault_custom('download', 'download_secret')
        g.keyvault_custom('backup', 'backup_secret', doc_string_source=data_doc_string.format('backup_secret'))
        g.keyvault_custom('restore', 'restore_secret', doc_string_source=data_doc_string.format('restore_secret'))

    with self.command_group('keyvault certificate', kv_data_sdk) as g:
        g.keyvault_custom('create',
                          'create_certificate',
                          doc_string_source=data_doc_string.format('create_certificate'))
        g.keyvault_command('list', 'get_certificates')
        g.keyvault_command('list-versions', 'get_certificate_versions')
        g.keyvault_command('list-deleted', 'get_deleted_certificates')
        g.keyvault_command('show', 'get_certificate')
        g.keyvault_command('show-deleted', 'get_deleted_certificate')
        g.keyvault_command('delete', 'delete_certificate')
        g.keyvault_command('purge', 'purge_deleted_certificate')
        g.keyvault_command('recover', 'recover_deleted_certificate')
        g.keyvault_command('set-attributes', 'update_certificate')
        g.keyvault_custom('import', 'import_certificate')
        g.keyvault_custom('download', 'download_certificate')
        g.keyvault_custom('get-default-policy', 'get_default_policy')

    with self.command_group('keyvault certificate pending', kv_data_sdk) as g:
        g.keyvault_command('merge', 'merge_certificate')
        g.keyvault_command('show', 'get_certificate_operation')
        g.keyvault_command('delete', 'delete_certificate_operation', validator=process_certificate_cancel_namespace)

    with self.command_group('keyvault certificate contact', kv_data_sdk) as g:
        g.keyvault_command('list', 'get_certificate_contacts')
        g.keyvault_custom('add', 'add_certificate_contact')
        g.keyvault_custom('delete', 'delete_certificate_contact')

    with self.command_group('keyvault certificate issuer', kv_data_sdk) as g:
        g.keyvault_custom('update', 'update_certificate_issuer')
        g.keyvault_command('list', 'get_certificate_issuers')
        g.keyvault_custom('create', 'create_certificate_issuer')
        g.keyvault_command('show', 'get_certificate_issuer')
        g.keyvault_command('delete', 'delete_certificate_issuer')

    with self.command_group('keyvault certificate issuer admin', kv_data_sdk) as g:
        g.keyvault_custom('list', 'list_certificate_issuer_admins')
        g.keyvault_custom('add', 'add_certificate_issuer_admin')
        g.keyvault_custom('delete', 'delete_certificate_issuer_admin')

    if data_api_version != '2016_10_01':
        with self.command_group('keyvault storage', kv_data_sdk) as g:
            g.keyvault_command('add', 'set_storage_account')
            g.keyvault_command('list', 'get_storage_accounts')
            g.keyvault_command('show', 'get_storage_account')
            g.keyvault_command('update', 'update_storage_account')
            g.keyvault_command('remove', 'delete_storage_account')
            g.keyvault_command('regenerate-key', 'regenerate_storage_account_key')
            g.keyvault_command('list-deleted', 'get_deleted_storage_accounts')
            g.keyvault_command('show-deleted', 'get_deleted_storage_account')
            g.keyvault_command('purge', 'purge_deleted_storage_account')
            g.keyvault_command('recover', 'recover_deleted_storage_account')
            g.keyvault_custom('backup',
                              'backup_storage_account',
                              doc_string_source=data_doc_string.format('backup_storage_account'))
            g.keyvault_custom('restore',
                              'restore_storage_account',
                              doc_string_source=data_doc_string.format('restore_storage_account'))

    if data_api_version != '2016_10_01':
        with self.command_group('keyvault storage sas-definition', kv_data_sdk) as g:
            g.keyvault_command('create',
                               'set_sas_definition',
                               doc_string_source=data_doc_string.format('set_sas_definition'))
            g.keyvault_command('list', 'get_sas_definitions')
            g.keyvault_command('show', 'get_sas_definition')
            g.keyvault_command('update',
                               'update_sas_definition',
                               doc_string_source=data_doc_string.format('update_sas_definition'))
            g.keyvault_command('delete', 'delete_sas_definition')
            g.keyvault_command('list-deleted', 'get_deleted_sas_definitions')
            g.keyvault_command('show-deleted', 'get_deleted_sas_definition')
            g.keyvault_command('recover', 'recover_deleted_sas_definition')
 def test_get_api_version(self):
     ''' Can get correct resource type API version '''
     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.assertEqual(get_api_version(ResourceType.MGMT_STORAGE), '2020-10-10')
Beispiel #51
0
def load_command_table(self, _):

    # region Command Types
    network_ag_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.application_gateways_operations#ApplicationGatewaysOperations.{}',
        client_factory=cf_application_gateways
    )

    network_util = CliCommandType(
        operations_tmpl='azure.cli.command_modules.network._util#{}',
        client_factory=None
    )

    network_asg_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.application_security_groups_operations#ApplicationSecurityGroupsOperations.{}',
        client_factory=cf_application_security_groups
    )

    network_ddos_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.ddos_protection_plans_operations#DdosProtectionPlansOperations.{}',
        client_factory=cf_ddos_protection_plans
    )

    network_dns_zone_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.dns.operations.zones_operations#ZonesOperations.{}',
        client_factory=cf_dns_mgmt_zones,
        resource_type=ResourceType.MGMT_NETWORK_DNS
    )

    network_dns_record_set_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.dns.operations.record_sets_operations#RecordSetsOperations.{}',
        client_factory=cf_dns_mgmt_record_sets,
        resource_type=ResourceType.MGMT_NETWORK_DNS
    )

    network_dns_reference_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.dns.operations.dns_resource_reference_operations#DnsResourceReferenceOperations.{}',
        client_factory=cf_dns_references,
        resource_type=ResourceType.MGMT_NETWORK_DNS,
        min_api='2018-05-01'
    )

    network_endpoint_service_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.available_endpoint_services_operations#AvailableEndpointServicesOperations.{}',
        client_factory=cf_endpoint_services,
        min_api='2017-06-01'
    )

    network_er_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.express_route_circuits_operations#ExpressRouteCircuitsOperations.{}',
        client_factory=cf_express_route_circuits,
        min_api='2016-09-01'
    )

    network_erca_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.express_route_circuit_authorizations_operations#ExpressRouteCircuitAuthorizationsOperations.{}',
        client_factory=cf_express_route_circuit_authorizations,
        min_api='2016-09-01'
    )

    network_erconn_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.express_route_circuit_connections_operations#ExpressRouteCircuitConnectionsOperations.{}',
        client_factory=cf_express_route_circuit_connections,
        min_api='2018-07-01'
    )

    network_ersp_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.express_route_service_providers_operations#ExpressRouteServiceProvidersOperations.{}',
        client_factory=cf_express_route_service_providers,
        min_api='2016-09-01'
    )

    network_er_peering_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.express_route_circuit_peerings_operations#ExpressRouteCircuitPeeringsOperations.{}',
        client_factory=cf_express_route_circuit_peerings
    )

    network_interface_endpoint_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.interface_endpoints_operations#InterfaceEndpointsOperations.{}',
        client_factory=cf_interface_endpoints,
        min_api='2018-08-01'
    )

    network_lb_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.load_balancers_operations#LoadBalancersOperations.{}',
        client_factory=cf_load_balancers
    )

    network_lgw_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.local_network_gateways_operations#LocalNetworkGatewaysOperations.{}',
        client_factory=cf_local_network_gateways
    )

    network_nic_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.network_interfaces_operations#NetworkInterfacesOperations.{}',
        client_factory=cf_network_interfaces
    )

    network_profile_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.network_profiles_operations#NetworkProfilesOperations.{}',
        client_factory=cf_network_profiles,
        min_api='2018-08-01'
    )

    network_nsg_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.network_security_groups_operations#NetworkSecurityGroupsOperations.{}',
        client_factory=cf_network_security_groups
    )

    network_nsg_rule_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.security_rules_operations#SecurityRulesOperations.{}',
        client_factory=cf_security_rules
    )

    network_public_ip_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.public_ip_addresses_operations#PublicIPAddressesOperations.{}',
        client_factory=cf_public_ip_addresses
    )

    network_public_ip_prefix_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.public_ip_prefixes_operations#PublicIPPrefixesOperations.{}',
        client_factory=cf_public_ip_prefixes,
        min_api='2018-07-01'
    )

    network_rf_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations#RouteFiltersOperations.{}',
        client_factory=cf_route_filters,
        min_api='2016-12-01'
    )

    network_rfr_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations#RouteFilterRulesOperations.{}',
        client_factory=cf_route_filter_rules,
        min_api='2016-12-01'
    )

    network_rt_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.route_tables_operations#RouteTablesOperations.{}',
        client_factory=cf_route_tables
    )

    network_subnet_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.subnets_operations#SubnetsOperations.{}',
        client_factory=cf_subnets
    )

    network_tmp_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.trafficmanager.operations.profiles_operations#ProfilesOperations.{}',
        client_factory=cf_traffic_manager_mgmt_profiles
    )

    network_tme_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.trafficmanager.operations.endpoints_operations#EndpointsOperations.{}',
        client_factory=cf_traffic_manager_mgmt_endpoints
    )

    network_vgw_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.virtual_network_gateways_operations#VirtualNetworkGatewaysOperations.{}',
        client_factory=cf_virtual_network_gateways
    )

    network_vnet_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.virtual_networks_operations#VirtualNetworksOperations.{}',
        client_factory=cf_virtual_networks
    )

    network_vnet_peering_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.virtual_network_peerings_operations#VirtualNetworkPeeringsOperations.{}',
        client_factory=cf_virtual_network_peerings
    )

    network_vpn_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.virtual_network_gateway_connections_operations#VirtualNetworkGatewayConnectionsOperations.{}',
        client_factory=cf_virtual_network_gateway_connections
    )

    network_watcher_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.network_watchers_operations#NetworkWatchersOperations.{}',
        client_factory=cf_network_watcher
    )

    network_watcher_cm_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.connection_monitors_operations#ConnectionMonitorsOperations.{}',
        client_factory=cf_connection_monitor
    )

    network_watcher_pc_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.packet_captures_operations#PacketCapturesOperations.{}',
        client_factory=cf_packet_capture
    )

    network_sepd_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.service_endpoint_policy_definitions_operations#ServiceEndpointPolicyDefinitionsOperations.{}',
        client_factory=cf_service_endpoint_policy_definitions,
        min_api='2018-07-01'
    )

    network_sepp_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.service_endpoint_policies_operations#ServiceEndpointPoliciesOperations.{}',
        client_factory=cf_service_endpoint_policies,
        min_api='2018-07-01'
    )

    network_custom = CliCommandType(operations_tmpl='azure.cli.command_modules.network.custom#{}')

    # endregion

    # region NetworkRoot
    usage_path = 'azure.mgmt.network.operations.usages_operations#UsagesOperations.{}'
    with self.command_group('network') as g:
        g.command('list-usages', 'list', operations_tmpl=usage_path, client_factory=cf_usages, transform=transform_network_usage_list, table_transformer=transform_network_usage_table)

    # endregion

    # region ApplicationGateways
    with self.command_group('network application-gateway', network_ag_sdk) as g:
        g.custom_command('create', 'create_application_gateway', transform=DeploymentOutputLongRunningOperation(self.cli_ctx), supports_no_wait=True, table_transformer=deployment_validate_table_format, validator=process_ag_create_namespace, exception_handler=handle_template_based_exception)
        g.command('delete', 'delete', supports_no_wait=True)
        g.show_command('show', 'get')
        g.custom_command('list', 'list_application_gateways')
        g.command('start', 'start')
        g.command('stop', 'stop')
        g.command('show-backend-health', 'backend_health', min_api='2016-09-01')
        g.generic_update_command('update', supports_no_wait=True, custom_func_name='update_application_gateway')
        g.wait_command('wait')

    subresource_properties = [
        {'prop': 'authentication_certificates', 'name': 'auth-cert'},
        {'prop': 'ssl_certificates', 'name': 'ssl-cert'},
        {'prop': 'frontend_ip_configurations', 'name': 'frontend-ip'},
        {'prop': 'frontend_ports', 'name': 'frontend-port'},
        {'prop': 'backend_address_pools', 'name': 'address-pool'},
        {'prop': 'backend_http_settings_collection', 'name': 'http-settings', 'validator': process_ag_http_settings_create_namespace},
        {'prop': 'http_listeners', 'name': 'http-listener', 'validator': process_ag_listener_create_namespace},
        {'prop': 'request_routing_rules', 'name': 'rule', 'validator': process_ag_rule_create_namespace},
        {'prop': 'probes', 'name': 'probe'},
        {'prop': 'url_path_maps', 'name': 'url-path-map', 'validator': process_ag_url_path_map_create_namespace}
    ]

    def _make_singular(value):
        try:
            if value.endswith('ies'):
                value = value[:-3] + 'y'
            elif value.endswith('s'):
                value = value[:-1]
            return value
        except AttributeError:
            return value

    for kwargs in subresource_properties:
        alias = kwargs['name']
        subresource = kwargs['prop']
        create_validator = kwargs.get('validator', None)
        with self.command_group('network application-gateway {}'.format(alias), network_util) as g:
            g.command('list', list_network_resource_property('application_gateways', subresource))
            g.show_command('show', get_network_resource_property_entry('application_gateways', subresource))
            g.command('delete', delete_network_resource_property_entry('application_gateways', subresource), supports_no_wait=True)
            g.custom_command('create', 'create_ag_{}'.format(_make_singular(subresource)), supports_no_wait=True, validator=create_validator)
            g.generic_update_command('update', command_type=network_ag_sdk, supports_no_wait=True,
                                     custom_func_name='update_ag_{}'.format(_make_singular(subresource)),
                                     child_collection_prop_name=subresource, validator=create_validator)

    with self.command_group('network application-gateway redirect-config', network_util, min_api='2017-06-01') as g:
        subresource = 'redirect_configurations'
        g.command('list', list_network_resource_property('application_gateways', subresource))
        g.show_command('show', get_network_resource_property_entry('application_gateways', subresource))
        g.command('delete', delete_network_resource_property_entry('application_gateways', subresource), supports_no_wait=True)
        g.custom_command('create', 'create_ag_{}'.format(_make_singular(subresource)), supports_no_wait=True, doc_string_source='ApplicationGatewayRedirectConfiguration')
        g.generic_update_command('update', command_type=network_ag_sdk,
                                 client_factory=cf_application_gateways, supports_no_wait=True,
                                 custom_func_name='update_ag_{}'.format(_make_singular(subresource)),
                                 child_collection_prop_name=subresource, doc_string_source='ApplicationGatewayRedirectConfiguration')

    with self.command_group('network application-gateway ssl-policy') as g:
        g.custom_command('set', 'set_ag_ssl_policy_2017_06_01', min_api='2017-06-01', supports_no_wait=True, validator=process_ag_ssl_policy_set_namespace, doc_string_source='ApplicationGatewaySslPolicy')
        g.custom_command('set', 'set_ag_ssl_policy_2017_03_01', max_api='2017-03-01', supports_no_wait=True, validator=process_ag_ssl_policy_set_namespace)
        g.custom_show_command('show', 'show_ag_ssl_policy')

    with self.command_group('network application-gateway ssl-policy', network_ag_sdk, min_api='2017-06-01') as g:
        g.command('list-options', 'list_available_ssl_options')
        g.command('predefined list', 'list_available_ssl_predefined_policies')
        g.show_command('predefined show', 'get_ssl_predefined_policy')

    with self.command_group('network application-gateway url-path-map rule') as g:
        g.custom_command('create', 'create_ag_url_path_map_rule', supports_no_wait=True, validator=process_ag_url_path_map_rule_create_namespace)
        g.custom_command('delete', 'delete_ag_url_path_map_rule', supports_no_wait=True)

    with self.command_group('network application-gateway waf-config') as g:
        g.custom_command('set', 'set_ag_waf_config_2017_03_01', min_api='2017-03-01', supports_no_wait=True)
        g.custom_command('set', 'set_ag_waf_config_2016_09_01', max_api='2016-09-01', supports_no_wait=True)
        g.custom_show_command('show', 'show_ag_waf_config')
        g.custom_command('list-rule-sets', 'list_ag_waf_rule_sets', min_api='2017-03-01', client_factory=cf_application_gateways, table_transformer=transform_waf_rule_sets_table_output)

    # endregion

    # region ApplicationSecurityGroups
    with self.command_group('network asg', network_asg_sdk, client_factory=cf_application_security_groups, min_api='2017-09-01') as g:
        g.custom_command('create', 'create_asg')
        g.show_command('show', 'get')
        g.command('list', 'list_all')
        g.command('delete', 'delete')
        g.generic_update_command('update', custom_func_name='update_asg')

    # endregion

    # region DdosProtectionPlans
    with self.command_group('network ddos-protection', network_ddos_sdk, min_api='2018-02-01') as g:
        g.custom_command('create', 'create_ddos_plan')
        g.command('delete', 'delete')
        g.custom_command('list', 'list_ddos_plans')
        g.show_command('show', 'get')
        g.generic_update_command('update', custom_func_name='update_ddos_plan')
    # endregion

    # region DNS
    with self.command_group('network dns', network_dns_reference_sdk) as g:
        g.command('list-references', 'get_by_target_resources')

    with self.command_group('network dns zone', network_dns_zone_sdk) as g:
        g.command('delete', 'delete', confirmation=True)
        g.show_command('show', 'get', table_transformer=transform_dns_zone_table_output)
        g.custom_command('list', 'list_dns_zones', table_transformer=transform_dns_zone_table_output)
        g.custom_command('import', 'import_zone')
        g.custom_command('export', 'export_zone')
        g.custom_command('create', 'create_dns_zone', client_factory=cf_dns_mgmt_zones)
        g.generic_update_command('update', custom_func_name='update_dns_zone')

    with self.command_group('network dns record-set') as g:
        g.custom_command('list', 'list_dns_record_set', client_factory=cf_dns_mgmt_record_sets, transform=transform_dns_record_set_output)

    api_version = str(get_api_version(self.cli_ctx, ResourceType.MGMT_NETWORK_DNS))
    api_version = api_version.replace('-', '_')
    dns_doc_string = 'azure.mgmt.dns.v' + api_version + '.operations#RecordSetsOperations.create_or_update'

    supported_records = ['a', 'aaaa', 'mx', 'ns', 'ptr', 'srv', 'txt']
    if self.supported_api_version(resource_type=ResourceType.MGMT_NETWORK_DNS, min_api='2018-02-01'):
        supported_records.append('caa')
    for record in supported_records:
        with self.command_group('network dns record-set {}'.format(record), network_dns_record_set_sdk, resource_type=ResourceType.MGMT_NETWORK_DNS) as g:
            g.show_command('show', 'get', transform=transform_dns_record_set_output)
            g.command('delete', 'delete', confirmation=True)
            g.custom_command('list', 'list_dns_record_set', client_factory=cf_dns_mgmt_record_sets, transform=transform_dns_record_set_output, table_transformer=transform_dns_record_set_table_output)
            g.custom_command('create', 'create_dns_record_set', transform=transform_dns_record_set_output, doc_string_source=dns_doc_string)
            g.custom_command('add-record', 'add_dns_{}_record'.format(record), transform=transform_dns_record_set_output)
            g.custom_command('remove-record', 'remove_dns_{}_record'.format(record), transform=transform_dns_record_set_output)
            g.generic_update_command('update', custom_func_name='update_dns_record_set', transform=transform_dns_record_set_output)

    with self.command_group('network dns record-set soa', network_dns_record_set_sdk) as g:
        g.show_command('show', 'get', transform=transform_dns_record_set_output)
        g.custom_command('update', 'update_dns_soa_record', transform=transform_dns_record_set_output)

    with self.command_group('network dns record-set cname', network_dns_record_set_sdk) as g:
        g.show_command('show', 'get', transform=transform_dns_record_set_output)
        g.command('delete', 'delete')
        g.custom_command('list', 'list_dns_record_set', client_factory=cf_dns_mgmt_record_sets, transform=transform_dns_record_set_output, table_transformer=transform_dns_record_set_table_output)
        g.custom_command('create', 'create_dns_record_set', transform=transform_dns_record_set_output, doc_string_source=dns_doc_string)
        g.custom_command('set-record', 'add_dns_cname_record', transform=transform_dns_record_set_output)
        g.custom_command('remove-record', 'remove_dns_cname_record', transform=transform_dns_record_set_output)

    # endregion

    # region ExpressRoutes
    with self.command_group('network express-route', network_er_sdk) as g:
        g.command('delete', 'delete', supports_no_wait=True)
        g.show_command('show', 'get')
        g.command('get-stats', 'get_stats')
        g.command('list-arp-tables', 'list_arp_table')
        g.command('list-route-tables', 'list_routes_table')
        g.custom_command('create', 'create_express_route', supports_no_wait=True)
        g.custom_command('list', 'list_express_route_circuits')
        g.command('list-service-providers', 'list', command_type=network_ersp_sdk)
        g.generic_update_command('update', custom_func_name='update_express_route', supports_no_wait=True)
        g.wait_command('wait')

    with self.command_group('network express-route auth', network_erca_sdk) as g:
        g.command('create', 'create_or_update', validator=process_auth_create_namespace)
        g.command('delete', 'delete')
        g.show_command('show', 'get')
        g.command('list', 'list')

    with self.command_group('network express-route peering', network_er_peering_sdk) as g:
        g.custom_command('create', 'create_express_route_peering', client_factory=cf_express_route_circuit_peerings)
        g.command('delete', 'delete')
        g.show_command('show', 'get')
        g.command('list', 'list')
        g.generic_update_command('update', setter_arg_name='peering_parameters', custom_func_name='update_express_route_peering')

    with self.command_group('network express-route peering connection', network_erconn_sdk) as g:
        g.custom_command('create', 'create_express_route_connection')
        g.command('delete', 'delete')
        g.show_command('show')
    # endregion

    # region InterfaceEndpoint
    with self.command_group('network interface-endpoint', network_interface_endpoint_sdk) as g:
        # TODO: Re-enable when service team asks. See issue #7271
        # g.custom_command('create', 'create_interface_endpoint')
        # g.command('delete', 'delete')
        g.custom_command('list', 'list_interface_endpoints')
        g.show_command('show')
        # g.generic_update_command('update', custom_func_name='update_interface_endpoint')
    # endregion

    # region LoadBalancers
    with self.command_group('network lb', network_lb_sdk) as g:
        g.show_command('show', 'get')
        g.custom_command('create', 'create_load_balancer', transform=DeploymentOutputLongRunningOperation(self.cli_ctx), supports_no_wait=True, table_transformer=deployment_validate_table_format, validator=process_lb_create_namespace, exception_handler=handle_template_based_exception)
        g.command('delete', 'delete')
        g.custom_command('list', 'list_lbs')
        g.generic_update_command('update')

    property_map = {
        'frontend_ip_configurations': 'frontend-ip',
        'inbound_nat_rules': 'inbound-nat-rule',
        'inbound_nat_pools': 'inbound-nat-pool',
        'backend_address_pools': 'address-pool',
        'load_balancing_rules': 'rule',
        'probes': 'probe',
    }
    for subresource, alias in property_map.items():
        with self.command_group('network lb {}'.format(alias), network_util) as g:
            g.command('list', list_network_resource_property('load_balancers', subresource))
            g.show_command('show', get_network_resource_property_entry('load_balancers', subresource))
            g.command('delete', delete_network_resource_property_entry('load_balancers', subresource))

    with self.command_group('network lb frontend-ip', network_lb_sdk) as g:
        g.custom_command('create', 'create_lb_frontend_ip_configuration', validator=process_lb_frontend_ip_namespace)
        g.generic_update_command('update', child_collection_prop_name='frontend_ip_configurations',
                                 custom_func_name='set_lb_frontend_ip_configuration',
                                 validator=process_lb_frontend_ip_namespace)

    with self.command_group('network lb inbound-nat-rule', network_lb_sdk) as g:
        g.custom_command('create', 'create_lb_inbound_nat_rule')
        g.generic_update_command('update', child_collection_prop_name='inbound_nat_rules',
                                 custom_func_name='set_lb_inbound_nat_rule')

    with self.command_group('network lb inbound-nat-pool', network_lb_sdk) as g:
        g.custom_command('create', 'create_lb_inbound_nat_pool')
        g.generic_update_command('update', child_collection_prop_name='inbound_nat_pools',
                                 custom_func_name='set_lb_inbound_nat_pool')

    with self.command_group('network lb address-pool', network_lb_sdk) as g:
        g.custom_command('create', 'create_lb_backend_address_pool')

    with self.command_group('network lb rule', network_lb_sdk) as g:
        g.custom_command('create', 'create_lb_rule')
        g.generic_update_command('update', child_collection_prop_name='load_balancing_rules',
                                 custom_func_name='set_lb_rule')

    with self.command_group('network lb probe', network_lb_sdk) as g:
        g.custom_command('create', 'create_lb_probe')
        g.generic_update_command('update', child_collection_prop_name='probes',
                                 custom_func_name='set_lb_probe')

    with self.command_group('network lb outbound-rule', network_lb_sdk, min_api='2018-07-01') as g:
        g.custom_command('create', 'create_lb_outbound_rule', validator=process_lb_outbound_rule_namespace)
        g.generic_update_command('update', child_collection_prop_name='outbound_rules',
                                 custom_func_name='set_lb_outbound_rule', validator=process_lb_outbound_rule_namespace)

    with self.command_group('network lb outbound-rule', network_util, min_api='2018-07-01') as g:
        g.command('list', list_network_resource_property('load_balancers', 'outbound_rules'))
        g.show_command('show', get_network_resource_property_entry('load_balancers', 'outbound_rules'))
        g.command('delete', delete_network_resource_property_entry('load_balancers', 'outbound_rules'))
    # endregion

    # region LocalGateways
    with self.command_group('network local-gateway', network_lgw_sdk) as g:
        g.command('delete', 'delete', supports_no_wait=True)
        g.show_command('show', 'get')
        g.command('list', 'list', table_transformer=transform_local_gateway_table_output)
        g.custom_command('create', 'create_local_gateway', supports_no_wait=True, validator=process_local_gateway_create_namespace)
        g.generic_update_command('update', custom_func_name='update_local_gateway', supports_no_wait=True)
        g.wait_command('wait')
    # endregion

    # region NetworkInterfaces: (NIC)
    with self.command_group('network nic', network_nic_sdk) as g:
        g.custom_command('create', 'create_nic', transform=transform_nic_create_output, validator=process_nic_create_namespace, supports_no_wait=True)
        g.command('delete', 'delete', supports_no_wait=True)
        g.show_command('show', 'get')
        g.custom_command('list', 'list_nics')
        g.command('show-effective-route-table', 'get_effective_route_table', min_api='2016-09-01')
        g.command('list-effective-nsg', 'list_effective_network_security_groups', min_api='2016-09-01')
        g.generic_update_command('update', custom_func_name='update_nic', supports_no_wait=True)
        g.wait_command('wait')

    resource = 'network_interfaces'
    subresource = 'ip_configurations'
    with self.command_group('network nic ip-config', network_nic_sdk) as g:
        g.custom_command('create', 'create_nic_ip_config')
        g.generic_update_command('update',
                                 child_collection_prop_name='ip_configurations', child_arg_name='ip_config_name',
                                 custom_func_name='set_nic_ip_config')
        g.command('list', list_network_resource_property(resource, subresource), command_type=network_util)
        g.show_command('show', get_network_resource_property_entry(resource, subresource), command_type=network_util)
        g.command('delete', delete_network_resource_property_entry(resource, subresource), command_type=network_util)

    with self.command_group('network nic ip-config address-pool') as g:
        g.custom_command('add', 'add_nic_ip_config_address_pool')
        g.custom_command('remove', 'remove_nic_ip_config_address_pool')

    with self.command_group('network nic ip-config inbound-nat-rule') as g:
        g.custom_command('add', 'add_nic_ip_config_inbound_nat_rule')
        g.custom_command('remove', 'remove_nic_ip_config_inbound_nat_rule')

    # endregion

    # region NetworkSecurityGroups
    with self.command_group('network nsg', network_nsg_sdk) as g:
        g.command('delete', 'delete')
        g.show_command('show', 'get')
        g.custom_command('list', 'list_nsgs')
        g.custom_command('create', 'create_nsg', transform=transform_nsg_create_output)
        g.generic_update_command('update')

    with self.command_group('network nsg rule', network_nsg_rule_sdk) as g:
        g.command('delete', 'delete')
        g.custom_command('list', 'list_nsg_rules', table_transformer=lambda x: [transform_nsg_rule_table_output(i) for i in x])
        g.show_command('show', 'get', table_transformer=transform_nsg_rule_table_output)
        g.custom_command('create', 'create_nsg_rule_2017_06_01', min_api='2017-06-01')
        g.generic_update_command('update', setter_arg_name='security_rule_parameters', min_api='2017-06-01',
                                 custom_func_name='update_nsg_rule_2017_06_01', doc_string_source='SecurityRule')
        g.custom_command('create', 'create_nsg_rule_2017_03_01', max_api='2017-03-01')
        g.generic_update_command('update', max_api='2017-03-01', setter_arg_name='security_rule_parameters',
                                 custom_func_name='update_nsg_rule_2017_03_01', doc_string_source='SecurityRule')
    # endregion

    # region NetworkProfiles
    with self.command_group('network profile', network_profile_sdk) as g:
        g.command('delete', 'delete', confirmation=True)
        g.custom_command('list', 'list_network_profiles')
        g.show_command('show')
    # endregion

    # region NetworkWatchers
    with self.command_group('network watcher', network_watcher_sdk, client_factory=cf_network_watcher, min_api='2016-09-01') as g:
        g.custom_command('configure', 'configure_network_watcher')
        g.command('list', 'list_all')
        g.custom_command('test-ip-flow', 'check_nw_ip_flow', client_factory=cf_network_watcher)
        g.custom_command('test-connectivity', 'check_nw_connectivity', client_factory=cf_network_watcher, validator=process_nw_test_connectivity_namespace)
        g.custom_command('show-next-hop', 'show_nw_next_hop', client_factory=cf_network_watcher)
        g.custom_command('show-security-group-view', 'show_nw_security_view', client_factory=cf_network_watcher)
        g.custom_command('show-topology', 'show_topology_watcher', validator=process_nw_topology_namespace)
        g.custom_command('run-configuration-diagnostic', 'run_network_configuration_diagnostic', client_factory=cf_network_watcher, min_api='2018-06-01', validator=process_nw_config_diagnostic_namespace)

    with self.command_group('network watcher connection-monitor', network_watcher_cm_sdk, client_factory=cf_connection_monitor, min_api='2018-01-01') as g:
        g.custom_command('create', 'create_nw_connection_monitor', validator=process_nw_cm_create_namespace)
        g.command('delete', 'delete')
        g.show_command('show', 'get')
        g.command('stop', 'stop')
        g.command('start', 'start')
        g.command('query', 'query')
        g.command('list', 'list')

    with self.command_group('network watcher packet-capture', network_watcher_pc_sdk, min_api='2016-09-01') as g:
        g.custom_command('create', 'create_nw_packet_capture', client_factory=cf_packet_capture, validator=process_nw_packet_capture_create_namespace)
        g.show_command('show', 'get')
        g.command('show-status', 'get_status')
        g.command('delete', 'delete')
        g.command('stop', 'stop')
        g.command('list', 'list')

    with self.command_group('network watcher flow-log', client_factory=cf_network_watcher, min_api='2016-09-01') as g:
        g.custom_command('configure', 'set_nsg_flow_logging', validator=process_nw_flow_log_set_namespace)
        g.custom_show_command('show', 'show_nsg_flow_logging', validator=process_nw_flow_log_show_namespace)

    with self.command_group('network watcher troubleshooting', client_factory=cf_network_watcher, min_api='2016-09-01') as g:
        g.custom_command('start', 'start_nw_troubleshooting', supports_no_wait=True, validator=process_nw_troubleshooting_start_namespace)
        g.custom_show_command('show', 'show_nw_troubleshooting_result', validator=process_nw_troubleshooting_show_namespace)
    # endregion

    # region PublicIPAddresses
    public_ip_show_table_transform = '{Name:name, ResourceGroup:resourceGroup, Location:location, $zone$AddressVersion:publicIpAddressVersion, AllocationMethod:publicIpAllocationMethod, IdleTimeoutInMinutes:idleTimeoutInMinutes, ProvisioningState:provisioningState}'
    public_ip_show_table_transform = public_ip_show_table_transform.replace('$zone$', 'Zones: (!zones && \' \') || join(` `, zones), ' if self.supported_api_version(min_api='2017-06-01') else ' ')

    with self.command_group('network public-ip', network_public_ip_sdk) as g:
        g.command('delete', 'delete')
        g.show_command('show', 'get', table_transformer=public_ip_show_table_transform)
        g.custom_command('list', 'list_public_ips', table_transformer='[].' + public_ip_show_table_transform)
        g.custom_command('create', 'create_public_ip', transform=transform_public_ip_create_output, validator=process_public_ip_create_namespace)
        g.generic_update_command('update', custom_func_name='update_public_ip')

    with self.command_group('network public-ip prefix', network_public_ip_prefix_sdk, client_factory=cf_public_ip_prefixes) as g:
        g.custom_command('create', 'create_public_ip_prefix')
        g.command('delete', 'delete')
        g.custom_command('list', 'list_public_ip_prefixes')
        g.show_command('show')
        g.generic_update_command('update', custom_func_name='update_public_ip_prefix')

    # endregion

    # region RouteFilters
    with self.command_group('network route-filter', network_rf_sdk, min_api='2016-12-01') as g:
        g.custom_command('create', 'create_route_filter', client_factory=cf_route_filters)
        g.custom_command('list', 'list_route_filters', client_factory=cf_route_filters)
        g.show_command('show', 'get')
        g.command('delete', 'delete')
        g.generic_update_command('update', setter_arg_name='route_filter_parameters')

    with self.command_group('network route-filter rule', network_rfr_sdk, min_api='2016-12-01') as g:
        g.custom_command('create', 'create_route_filter_rule', client_factory=cf_route_filter_rules)
        g.command('list', 'list_by_route_filter')
        g.show_command('show', 'get')
        g.command('delete', 'delete')
        g.generic_update_command('update', setter_arg_name='route_filter_rule_parameters')
        sc_path = 'azure.mgmt.network.operations#BgpServiceCommunitiesOperations.{}'
        g.command('list-service-communities', 'list', operations_tmpl=sc_path, client_factory=cf_service_community, table_transformer=transform_service_community_table_output)

    # endregion

    # region RouteTables
    with self.command_group('network route-table', network_rt_sdk) as g:
        g.custom_command('create', 'create_route_table', validator=process_route_table_create_namespace)
        g.command('delete', 'delete')
        g.show_command('show', 'get')
        g.custom_command('list', 'list_route_tables')
        g.generic_update_command('update', custom_func_name='update_route_table')

    network_rtr_sdk = CliCommandType(
        operations_tmpl='azure.mgmt.network.operations.routes_operations#RoutesOperations.{}',
        client_factory=cf_routes
    )
    with self.command_group('network route-table route', network_rtr_sdk) as g:
        g.custom_command('create', 'create_route')
        g.command('delete', 'delete')
        g.show_command('show', 'get')
        g.command('list', 'list')
        g.generic_update_command('update', setter_arg_name='route_parameters', custom_func_name='update_route')

    # endregion

    # region ServiceEndpoint
    with self.command_group('network service-endpoint', network_endpoint_service_sdk) as g:
        g.command('list', 'list')

    with self.command_group('network service-endpoint policy', network_sepp_sdk) as g:
        g.custom_command('create', 'create_service_endpoint_policy')
        g.command('delete', 'delete')
        g.custom_command('list', 'list_service_endpoint_policies')
        g.show_command('show')
        g.generic_update_command('update', custom_func_name='update_service_endpoint_policy')

    with self.command_group('network service-endpoint policy-definition', network_sepd_sdk) as g:
        g.custom_command('create', 'create_service_endpoint_policy_definition')
        g.command('delete', 'delete')
        g.command('list', 'list_by_resource_group')
        g.show_command('show')
        g.generic_update_command('update', custom_func_name='update_service_endpoint_policy_definition',
                                 setter_arg_name='service_endpoint_policy_definitions')
    # endregion

    # region TrafficManagers
    with self.command_group('network traffic-manager profile', network_tmp_sdk) as g:
        g.command('check-dns', 'check_traffic_manager_relative_dns_name_availability')
        g.show_command('show', 'get')
        g.command('delete', 'delete')
        g.custom_command('list', 'list_traffic_manager_profiles')
        g.custom_command('create', 'create_traffic_manager_profile', transform=transform_traffic_manager_create_output)
        g.generic_update_command('update', custom_func_name='update_traffic_manager_profile')

    with self.command_group('network traffic-manager endpoint', network_tme_sdk) as g:
        g.show_command('show', 'get')
        g.command('delete', 'delete')
        g.custom_command('create', 'create_traffic_manager_endpoint', validator=process_tm_endpoint_create_namespace)
        g.custom_command('list', 'list_traffic_manager_endpoints')
        g.generic_update_command('update', custom_func_name='update_traffic_manager_endpoint')

        tm_geographic_path = 'azure.mgmt.trafficmanager.operations.geographic_hierarchies_operations#GeographicHierarchiesOperations.{}'
        g.command('show-geographic-hierarchy', 'get_default', client_factory=cf_tm_geographic, operations_tmpl=tm_geographic_path, table_transformer=transform_geographic_hierachy_table_output)

    # endregion

    # region VirtualNetworks
    with self.command_group('network vnet', network_vnet_sdk) as g:
        g.command('delete', 'delete')
        g.custom_command('list', 'list_vnet', table_transformer=transform_vnet_table_output)
        g.show_command('show', 'get')
        g.command('check-ip-address', 'check_ip_address_availability', min_api='2016-09-01')
        g.custom_command('create', 'create_vnet', transform=transform_vnet_create_output, validator=process_vnet_create_namespace)
        g.generic_update_command('update', custom_func_name='update_vnet')
        g.command('list-endpoint-services', 'list', command_type=network_endpoint_service_sdk)

    with self.command_group('network vnet peering', network_vnet_peering_sdk, min_api='2016-09-01') as g:
        g.custom_command('create', 'create_vnet_peering')
        g.show_command('show', 'get')
        g.command('list', 'list')
        g.command('delete', 'delete')
        g.generic_update_command('update', setter_name='update_vnet_peering', setter_type=network_custom)

    with self.command_group('network vnet subnet', network_subnet_sdk) as g:
        g.custom_command('create', 'create_subnet')
        g.command('delete', 'delete')
        g.show_command('show', 'get')
        g.command('list', 'list')
        g.generic_update_command('update', setter_arg_name='subnet_parameters',
                                 custom_func_name='update_subnet')
        g.custom_command('list-available-delegations', 'list_avail_subnet_delegations', min_api='2018-08-01', validator=process_list_delegations_namespace)
    # endregion

    # region VirtualNetworkGateways
    with self.command_group('network vnet-gateway', network_vgw_sdk, min_api='2016-09-01') as g:
        g.custom_command('create', 'create_vnet_gateway', supports_no_wait=True, transform=transform_vnet_gateway_create_output, validator=process_vnet_gateway_create_namespace)
        g.generic_update_command('update', custom_func_name='update_vnet_gateway', supports_no_wait=True, validator=process_vnet_gateway_update_namespace)
        g.wait_command('wait')
        g.command('delete', 'delete', supports_no_wait=True)
        g.show_command('show', 'get')
        g.command('list', 'list')
        g.command('reset', 'reset')
        g.command('list-bgp-peer-status', 'get_bgp_peer_status')
        g.command('list-advertised-routes', 'get_advertised_routes')
        g.command('list-learned-routes', 'get_learned_routes')

    with self.command_group('network vnet-gateway vpn-client', network_vgw_sdk, client_factory=cf_virtual_network_gateways) as g:
        g.custom_command('generate', 'generate_vpn_client')
        g.command('show-url', 'get_vpn_profile_package_url', min_api='2017-08-01')

    with self.command_group('network vnet-gateway revoked-cert', network_vgw_sdk) as g:
        g.custom_command('create', 'create_vnet_gateway_revoked_cert')
        g.custom_command('delete', 'delete_vnet_gateway_revoked_cert')

    with self.command_group('network vnet-gateway root-cert', network_vgw_sdk) as g:
        g.custom_command('create', 'create_vnet_gateway_root_cert')
        g.custom_command('delete', 'delete_vnet_gateway_root_cert')

    # endregion

    # region VirtualNetworkGatewayConnections
    with self.command_group('network vpn-connection', network_vpn_sdk) as g:
        g.custom_command('create', 'create_vpn_connection', transform=DeploymentOutputLongRunningOperation(self.cli_ctx), table_transformer=deployment_validate_table_format, validator=process_vpn_connection_create_namespace, exception_handler=handle_template_based_exception)
        g.command('delete', 'delete')
        g.show_command('show', 'get', transform=transform_vpn_connection)
        g.command('list', 'list', transform=transform_vpn_connection_list)
        g.generic_update_command('update', custom_func_name='update_vpn_connection')

    with self.command_group('network vpn-connection shared-key', network_vpn_sdk) as g:
        g.show_command('show', 'get_shared_key')
        g.command('reset', 'reset_shared_key')
        g.generic_update_command('update', setter_name='set_shared_key')

    with self.command_group('network vpn-connection ipsec-policy', network_vpn_sdk, min_api='2017-03-01') as g:
        g.custom_command('add', 'add_vpn_conn_ipsec_policy', supports_no_wait=True, doc_string_source='IpsecPolicy')
        g.custom_command('list', 'list_vpn_conn_ipsec_policies')
        g.custom_command('clear', 'clear_vpn_conn_ipsec_policies', supports_no_wait=True)
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
 def test_get_api_version_invalid_rt_2(self):
     ''' None is not a valid resource type '''
     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):
             get_api_version(None)
 def test_get_api_version_invalid_rt(self):
     # Resource Type not in 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):
             get_api_version(ResourceType.MGMT_COMPUTE)
Beispiel #55
0
def get_subscription_service_client():
    return _get_mgmt_service_client(get_client_class(ResourceType.MGMT_RESOURCE_SUBSCRIPTIONS),
                                    subscription_bound=False,
                                    api_version=get_api_version(ResourceType.MGMT_RESOURCE_SUBSCRIPTIONS))
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
    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
 def test_get_api_version_invalid_active_profile(self):
     ''' The active profile is not in our profile dict '''
     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):
             get_api_version(ResourceType.MGMT_STORAGE)
def build_vm_resource(  # pylint: disable=too-many-locals
        name, location, tags, size, storage_profile, nics, admin_username,
        availability_set_id=None, admin_password=None, ssh_key_value=None, ssh_key_path=None,
        image_reference=None, os_disk_name=None, custom_image_os_type=None,
        os_caching=None, data_caching=None, storage_sku=None,
        os_publisher=None, os_offer=None, os_sku=None, os_version=None, os_vhd_uri=None,
        attach_os_disk=None, attach_data_disks=None, data_disk_sizes_gb=None, image_data_disks=None,
        custom_data=None, secrets=None, license_type=None):

    def _build_os_profile():

        os_profile = {
            'computerName': name,
            'adminUsername': admin_username
        }

        if admin_password:
            os_profile['adminPassword'] = admin_password

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

        if ssh_key_value and ssh_key_path:
            os_profile['linuxConfiguration'] = {
                'disablePasswordAuthentication': True,
                'ssh': {
                    'publicKeys': [
                        {
                            'keyData': ssh_key_value,
                            'path': ssh_key_path
                        }
                    ]
                }
            }

        if secrets:
            os_profile['secrets'] = secrets

        return os_profile

    def _build_storage_profile():

        storage_profiles = {
            'SACustomImage': {
                'osDisk': {
                    'createOption': 'fromImage',
                    'name': os_disk_name,
                    'caching': os_caching,
                    'osType': custom_image_os_type,
                    'image': {'uri': image_reference},
                    'vhd': {'uri': os_vhd_uri}
                }
            },
            'SAPirImage': {
                'osDisk': {
                    'createOption': 'fromImage',
                    'name': os_disk_name,
                    'caching': os_caching,
                    'vhd': {'uri': os_vhd_uri}
                },
                'imageReference': {
                    'publisher': os_publisher,
                    'offer': os_offer,
                    'sku': os_sku,
                    'version': os_version
                }
            },
            'SASpecializedOSDisk': {
                'osDisk': {
                    'createOption': 'attach',
                    'osType': custom_image_os_type,
                    'name': os_disk_name,
                    'vhd': {'uri': attach_os_disk}
                }
            },
            'ManagedPirImage': {
                'osDisk': {
                    'createOption': 'fromImage',
                    'name': os_disk_name,
                    'caching': os_caching,
                    'managedDisk': {'storageAccountType': storage_sku}
                },
                'imageReference': {
                    'publisher': os_publisher,
                    'offer': os_offer,
                    'sku': os_sku,
                    'version': os_version
                }
            },
            'ManagedCustomImage': {
                'osDisk': {
                    'createOption': 'fromImage',
                    'name': os_disk_name,
                    'caching': os_caching,
                    'managedDisk': {'storageAccountType': storage_sku}
                },
                "imageReference": {
                    'id': image_reference
                }
            },
            'ManagedSpecializedOSDisk': {
                'osDisk': {
                    'createOption': 'attach',
                    'osType': custom_image_os_type,
                    'managedDisk': {
                        'id': attach_os_disk
                    }
                }
            }
        }
        profile = storage_profiles[storage_profile.name]
        return _build_data_disks(profile, data_disk_sizes_gb, image_data_disks,
                                 data_caching, storage_sku, attach_data_disks=attach_data_disks)

    vm_properties = {
        'hardwareProfile': {'vmSize': size},
        'networkProfile': {'networkInterfaces': nics}
    }

    vm_properties['storageProfile'] = _build_storage_profile()

    if availability_set_id:
        vm_properties['availabilitySet'] = {'id': availability_set_id}

    if not attach_os_disk:
        vm_properties['osProfile'] = _build_os_profile()

    if license_type:
        vm_properties['licenseType'] = license_type

    vm_api_version = get_api_version(ResourceType.MGMT_COMPUTE)
    vm = {
        'apiVersion': vm_api_version,
        'type': 'Microsoft.Compute/virtualMachines',
        'name': name,
        'location': location,
        'tags': tags,
        'dependsOn': [],
        'properties': vm_properties,
    }
    return vm
Beispiel #59
0
def get_network_watcher_from_resource(namespace):
    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)