def _ensure_subnet_service_endpoint(cli_ctx, subnet_id):
    from msrestazure.tools import parse_resource_id
    subnet_id_parts = parse_resource_id(subnet_id)
    subnet_resource_group = subnet_id_parts['resource_group']
    subnet_vnet_name = subnet_id_parts['name']
    subnet_name = subnet_id_parts['resource_name']

    vnet_client = network_client_factory(cli_ctx,
                                         api_version=NETWORK_API_VERSION)
    subnet_obj = vnet_client.subnets.get(subnet_resource_group,
                                         subnet_vnet_name, subnet_name)
    subnet_obj.service_endpoints = subnet_obj.service_endpoints or []
    service_endpoint_exists = False
    for s in subnet_obj.service_endpoints:
        if s.service == "Microsoft.Web":
            service_endpoint_exists = True
            break

    if not service_endpoint_exists:
        web_service_endpoint = ServiceEndpointPropertiesFormat(
            service="Microsoft.Web")
        subnet_obj.service_endpoints.append(web_service_endpoint)
        poller = vnet_client.subnets.begin_create_or_update(
            subnet_resource_group,
            subnet_vnet_name,
            subnet_name,
            subnet_parameters=subnet_obj)
        # Ensure subnet is updated to avoid update conflict
        LongRunningOperation(cli_ctx)(poller)
def _ensure_subnet_service_endpoint(cli_ctx, subnet_id):
    from azure.cli.core.profiles import AD_HOC_API_VERSIONS, ResourceType
    subnet_id_parts = parse_resource_id(subnet_id)
    subnet_subscription_id = subnet_id_parts['subscription']
    subnet_resource_group = subnet_id_parts['resource_group']
    subnet_vnet_name = subnet_id_parts['name']
    subnet_name = subnet_id_parts['resource_name']

    if get_subscription_id(cli_ctx).lower() != subnet_subscription_id.lower():
        raise ArgumentUsageError('Cannot validate subnet in different subscription for missing service endpoint.'
                                 ' Use --ignore-missing-endpoint or -i to'
                                 ' skip validation and manually verify service endpoint.')

    vnet_client = network_client_factory(cli_ctx, api_version=AD_HOC_API_VERSIONS[ResourceType.MGMT_NETWORK]
                                         ['appservice_ensure_subnet'])
    subnet_obj = vnet_client.subnets.get(subnet_resource_group, subnet_vnet_name, subnet_name)
    subnet_obj.service_endpoints = subnet_obj.service_endpoints or []
    service_endpoint_exists = False
    for s in subnet_obj.service_endpoints:
        if s.service == "Microsoft.Web":
            service_endpoint_exists = True
            break

    if not service_endpoint_exists:
        web_service_endpoint = ServiceEndpointPropertiesFormat(service="Microsoft.Web")
        subnet_obj.service_endpoints.append(web_service_endpoint)
        poller = vnet_client.subnets.begin_create_or_update(
            subnet_resource_group, subnet_vnet_name,
            subnet_name, subnet_parameters=subnet_obj)
        # Ensure subnet is updated to avoid update conflict
        LongRunningOperation(cli_ctx)(poller)
def run_action(credentials, rule, entity, params):
    logging.info(f'{__file__} - ${run_action.__name__} started')
    subscription_id = entity['accountNumber']
    server_group_name = entity['resourceGroup']['name']
    sql_server_name = entity['name']
    sql_server_region = entity['region']
        
    logging.info(
        f'{__file__} - subscription_id : {subscription_id} - server_group_name : {server_group_name} - sql_server : {sql_server_name}')
    
    if not subscription_id or not credentials:
        return raise_credentials_error()

    try:  
        network_client = NetworkManagementClient(credentials,subscription_id)
        sql_client = SqlManagementClient(credentials, subscription_id)

        vnets = network_client.virtual_networks.list_all()
        acls = []
        endpoint_params = [ServiceEndpointPropertiesFormat(service='Microsoft.Sql', locations=["*"])]
        subnet_path = ""

        for v in vnets:
            vnet_name = v.name
            vnet_nsg_split = v.id.split('/')
            vnet_nsg = vnet_nsg_split[4]
            subnets = v.subnets
            vnet_region = v.location

            if sql_server_region == vnet_region:
                logging.info(f'Regions match - applying ACLs to {vnet_name}')
                for s in subnets:
                    subnet_path = s.id
                    subnet_name = s.name
                    subnet_address_prefix = s.address_prefix
                    service_endpoint_list = s.service_endpoints
                    firewall_rule_name = vnet_name + "-" + subnet_name + " auto-generated rule"
                    logging.info(f'Subnet path :  {subnet_path} Subnet Name : {subnet_name} Subnet CIDR : {subnet_address_prefix} Endpoint list : {service_endpoint_list}')
            
                    # Create storage endpoint if doesn't exist
                    if not service_endpoint_list:
                        network_client.subnets.begin_create_or_update(resource_group_name=vnet_nsg, virtual_network_name=vnet_name, subnet_name=subnet_name,
                            subnet_parameters=Subnet(address_prefix=subnet_address_prefix, service_endpoints=endpoint_params))
                    else:
                        logging.info(f'Service Endpoint for subnet {subnet_name} already exists, not creating')
                        logging.info(*service_endpoint_list)
                    
                    acls.append(VirtualNetworkRule(virtual_network_subnet_id=subnet_path))            
                    sql_client.virtual_network_rules.begin_create_or_update(server_group_name, sql_server_name, firewall_rule_name, parameters=VirtualNetworkRule(
                        virtual_network_subnet_id=subnet_path, ignore_missing_vnet_service_endpoint=False))
                    logging.info(f'Azure SQL firewall rule {firewall_rule_name} set successfully on : {sql_server_name}')
            else:
               logging.info(f'Regions do not match - skipping {vnet_name}')
     
    except (HttpResponseError, ResourceExistsError) as e:
        logging.info(f'An error occured : {e}')   
Beispiel #4
0
# AZURE_SUBSCRIPTION_ID: with your Azure Subscription Id
#

credentials, subscription_id = get_credentials()

network_client = NetworkManagementClient(credentials, subscription_id)
resource_client = ResourceManagementClient(credentials, subscription_id)
storage_client = StorageManagementClient(credentials, subscription_id)

resource_group_params = {'location':LOCATION}
resource_client.resource_groups.create_or_update(GROUP_NAME, resource_group_params)

vnet_params = { 'location': LOCATION, 'address_space' : { 'address_prefixes': [VNET_AP] } }
async_vnet_creation = network_client.virtual_networks.create_or_update(GROUP_NAME, VNET_NAME, vnet_params)
async_vnet_creation.wait()
ep = ServiceEndpointPropertiesFormat(service='Microsoft.Storage')
ep_list = [ep]
subnet = Subnet(address_prefix = SB_AP, service_endpoints = ep_list)
async_vnet_subnet_creation = network_client.subnets.create_or_update(GROUP_NAME, VNET_NAME, SB_NAME, subnet)
async_vnet_subnet_creation.wait()
if async_vnet_subnet_creation.status() == 'Succeeded':
    sb_result = async_vnet_subnet_creation.result()
    virtual_network_resource_id = sb_result.id
    vr = VirtualNetworkRule(virtual_network_resource_id=virtual_network_resource_id)
    vnets = [vr]
    ns = NetworkRuleSet(bypass='******', virtual_network_rules=vnets, default_action='Deny')
    storage_client = StorageManagementClient(credentials, subscription_id)
    sku = Sku(name=SkuName.standard_lrs)
    st1 = StorageAccountCreateParameters(sku=sku, kind=Kind.storage, location=LOCATION, network_rule_set=ns)
    storage_async_operation = storage_client.storage_accounts.create(GROUP_NAME, STORAGE_ACCOUNT_NAME, st1, location=LOCATION)
    #stlist = storage_client.storage_accounts.list()