Azure Java SDK: ServiceException: ForbiddenError:

ぃ、小莉子 提交于 2019-12-02 10:01:58

The issue is caused by using the incorrect Azure Java SDK libraries. When I used the maven dependencies in the file pom.xml below, I reproduced the same exception.

<dependency>
   <groupId>com.microsoft.azure</groupId>
   <artifactId>azure-mgmt-compute</artifactId>
   <version>0.8.3</version>
</dependency>

The library supply the VM restart function need two arguments: resource group name and vm name. But the API of library azure-mgmt-compute is used for Azure Resource Management.

To restart VM, you need to use the API of library azure-svc-mgmt-compute for Azure Service Management if you used JKS certificates. The Class VirtualMachineOperations supply the same name function restart need three arguments: service name, deployment name and vm name. You can find these names from Cloud Service dashboard on Azure Portal. In your issue code, the vm name should be "sqlvm".

The right maven pom.xml for dependencies as below:

<dependency>
   <groupId>com.microsoft.azure</groupId>
   <artifactId>azure-svc-mgmt</artifactId>
   <version>0.8.3</version>
</dependency>
<dependency>
   <groupId>com.microsoft.azure</groupId>
   <artifactId>azure-svc-mgmt-compute</artifactId>
   <version>0.8.3</version>
</dependency>

And the code as below

virtualMachinesOperations.restart("<service name: sqlvm>", "<deployment name: sqlvm>", "<vm name: sqlvm>");

The steps below for genkeypair by using Java Keytool in the path JAVA_HOME/bin:

keytool -genkeypair -alias keyfile -keyalg RSA -keystore <KeyStore.jks> 
-keysize 2048 -storepass "<password>"

keytool -v -export -file <KeyStore.cer> -keystore KeyStore.jks -alias keyfile

My code:

String uri = "https://management.core.windows.net/";
String subscriptionId = "<subscription_id>";
String keyStoreLocation = "KeyStore.jks";
String keyStorePassword = "<password>";

Configuration config = ManagementConfiguration.configure(
       new URI(uri), 
       subscriptionId,
       keyStoreLocation, // the file path to the JKS
       keyStorePassword, // the password for the JKS
       KeyStoreType.jks // flags that I'm using a JKS keystore
    ); 
ComputeManagementClient computeManagementClient = ComputeManagementService.create(config);
VirtualMachineOperations virtualMachinesOperations = computeManagementClient.getVirtualMachinesOperations();
virtualMachinesOperations.restart("petercore", "petercore", "petercore");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!