在Azure中为特定的MySQL服务器创建私有终结点

问题描述

我在Azure云上创建了一个现有的MysqL服务器。现在,我想使用Java代码(SDK)建立专用端点连接。您能帮我使用哪个java类解决此问题。 Azure cloud screenshot

解决方法

如果要使用Java代码建立私有端点,请参考以下代码

  1. 创建服务主体并将角色分配给sp
az login
# it will create a service principal and assign a contributor rolen to the sp
az ad sp create-for-rbac -n "MyApp"   --sdk-auth

enter image description here

  1. sdk
<dependency>
      <groupId>com.microsoft.azure</groupId>
      <artifactId>azure</artifactId>
      <version>1.36.1</version>
    </dependency>
  1. 代码
String secret ="<the sp client secret>" ;
        String domain="<the sp tenantId>";
        String clientId="<the sp clientId>";
        String subscriptionId="";
        String groupName="testmysql";
        Region region = Region.JAPAN_EAST;
        String networkName="mysqlvnet1";
        String subnetName="default";
String serverId="<the mysql server resource id e.g. /subscriptions/b83c1ed3-c5b6-44fb-b5ba-2b83a074c23f/resourceGroups/v-wenxu-chinacxp/providers/Microsoft.DBforMySQL/servers/testsql08>"
        ApplicationTokenCredentials credentials = new ApplicationTokenCredentials(clientId,domain,secret,AzureEnvironment.AZURE);

      

        NetworkManager networkManager =NetworkManager.authenticate(credentials,subscriptionId);
        // create vnet
        Network network = networkManager.networks()
                .define(networkName)
                .withRegion(region)
                .withExistingResourceGroup(groupName)
                .withAddressSpace("172.31.0.0/16")
                .defineSubnet(subnetName)
                    .withAddressPrefix("172.31.0.0/24")
                    .attach()
                .create();
        network.subnets().get(subnetName).inner().withPrivateEndpointNetworkPolicies("Disabled");
        network.subnets().get(subnetName).inner().withPrivateLinkServiceNetworkPolicies("Enabled");

        network.update()
                .updateSubnet(subnetName)
                .parent()
                .apply();

        // create network private endpoint.
        PrivateLinkServiceConnection privateLinkServiceConnection = new PrivateLinkServiceConnection()
                .withName("mysql1")
                .withPrivateLinkServiceId("the resource id of mysql service")
                .withPrivateLinkServiceConnectionState(new PrivateLinkServiceConnectionState()
                        .withStatus("Approved"))
                .withGroupIds(Arrays.asList(serverId);
        PrivateEndpointInner privateEndpoint = new PrivateEndpointInner()
                .withPrivateLinkServiceConnections(Arrays.asList(privateLinkServiceConnection))
                .withSubnet(network.subnets().get(subnetName).inner());

        privateEndpoint.withLocation(region.toString());
        privateEndpoint =networkManager.inner().privateEndpoints().createOrUpdate(groupName,"mysql1",privateEndpoint);

enter image description here