本文共 3994 字,大约阅读时间需要 13 分钟。
在使用Java的启动Azure VM的过程中,遇见了com.azure.core.management.exception.ManagementException: Status code 404错误,纠起原因就是订阅无法发现。详细的错误为:
Selected subscription: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx com.azure.core.management.exception.ManagementException: Status code 404, "{"error":{"code":"SubscriptionNotFound","message":"The subscription 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' could not be found."}}": The subscription 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' could not be found. sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) |
以上问题主要时在使用Java代码访问Azure资源的时候出现的权限问题有关。所以解决的办法是需要先让应用程序有权限访问到Azure VM资源,这里使用的是AAD认证。在代码中使用ApplicationTokenCredentials方式认证。
AzureTokenCredentials credentials = new ApplicationTokenCredentials("clientid", "tenantid", "clientsecret", AzureEnvironment.AZURE_CHINA);Azure azure = Azure.authenticate(credentials).withSubscription("subid"); VirtualMachine testvm = azure.virtualMachines().getById("/subscriptions//resourceGroups/ /providers/Microsoft.Compute/virtualMachines/ ");
(获取以上值的方式见附录一)
package org.example;import com.microsoft.azure.AzureEnvironment;import com.microsoft.azure.credentials.ApplicationTokenCredentials;import com.microsoft.azure.credentials.AzureTokenCredentials;import com.microsoft.azure.management.Azure;import com.microsoft.azure.management.compute.*;/**s* Hello world!**/public class App { public static void main( String[] args ) { AzureTokenCredentials credentials = new ApplicationTokenCredentials("clientid", "tenantid", "clientsecret", AzureEnvironment.AZURE_CHINA); Azure azure=null; azure=Azure.authenticate(credentials).withSubscription("subid"); VirtualMachine testvm = azure.virtualMachines().getById("vmresourceid"); testvm.start(); System.out.println( "Hello World!" ); }}
POM.XML文件内容(使用的依赖包:com.microsoft.azure):
4.0.0 org.example getvm 1.0-SNAPSHOT getvm http://www.example.com UTF-8 1.7 1.7 junit junit 4.11 test com.microsoft.azure azure 1.37.1 maven-clean-plugin 3.1.0 maven-resources-plugin 3.0.2 maven-compiler-plugin 3.8.0 maven-surefire-plugin 2.22.1 maven-jar-plugin 3.0.2 maven-install-plugin 2.5.2 maven-deploy-plugin 2.8.2 maven-site-plugin 3.7.1 maven-project-info-reports-plugin 3.0.0
一:获取 AAD中应用的Client ID, Tenant ID
二:获取AAD中应用的Secret
三:获取Azure VM的Resource ID
使用 Java 创建和管理 Azure 中的 Windows VM:
转载地址:http://baoyz.baihongyu.com/