使用 Azure Resource Manage JAVA API 管理 Azure 资源

来源:互联网 发布:重力感应效果 js 编辑:程序博客网 时间:2024/04/25 12:00

Azure提供两种资源管理模式,Service Manage 和Resource Manage, Service Manage 是相对较旧的管理模式,目前Azure Global 最新的管理界面已经完全使用Resource Manage的方式来管理Azure 资源,而中国Azure更新相对Global较为迟缓,依然使用经典的管理界面来管理资源,而旧的管理界面大多是以Service Manage的API来管理资源,所以目前在国内,依然使用Service Manage的API来管理资源。

虽然国内没有更新管理界面,但是部分Resource Manage的API,已经在服务端部署,所以我们也是可以使用Resource Manage的API来操作Azure资源,只是创建的资源目前在Portal界面是无法看到的。

以下是具体使用Resource Manage来操作Azure 资源。

在PowerShell中,登录Azure 账户

Login-AzureRmAccount -EnvironmentName AzureChinaCloud

选择当前订阅ID

Set-AzureRmContext -SubscriptionId <subscription ID>

创建AD Application

$azureAdApplication = New-AzureRmADApplication -DisplayName "exampleapp" -HomePage "https://www.contoso.org" -IdentifierUris "https://www.contoso.org/example" -Password "<Your_Password>"

查看新创建的应用对象,属性ApplicationId,在后续会用来创建服务凭证,角色设置和access token.

PS C:\> $azureAdApplicationDisplayName             : exampleappType                    : ApplicationApplicationId           : 8bc80782-a916-47c8-a47e-4d76ed755275ApplicationObjectId     : c95e67a3-403c-40ac-9377-115fa48f8f39AvailableToOtherTenants : FalseAppPermissions          : {}IdentifierUris          : {https://www.contoso.org/example}ReplyUrls               : {}

创建服务凭证
为你的AD应用创建服务凭证。

PS C:\> New-AzureRmADServicePrincipal -ApplicationId $azureAdApplication.ApplicationId

当你创建完成服务凭证后,初始是没有任何权限的,我们需要为其设置权限范围,你需要现实的为你的服务凭证设置具体的权限

授权
为你的服务凭证添加角色设置,在这个例子里,你将为你的服务凭证设置访问你订阅下所有资源的读权限。 如果想了解更多内容,请参考:Azure Role-based Access Control|

PS C:\> New-AzureRmRoleAssignment -RoleDefinitionName Reader -ServicePrincipalName $azureAdApplication.ApplicationId

创建MAVEN项目,并引入Azure Resource SDK
Azure Resource SDK 依赖

<dependency>    <groupId>com.microsoft.azure</groupId>    <artifactId>azure-resources</artifactId>    <version>${azure-sdk-version}</version></dependency><dependency>    <groupId>com.microsoft.azure</groupId>    <artifactId>azure-mgmt</artifactId>    <version>${azure-sdk-version}</version></dependency><dependency>    <groupId>com.microsoft.azure</groupId>    <artifactId>azure-mgmt-compute</artifactId>    <version>${azure-sdk-version}</version></dependency><dependency>    <groupId>com.microsoft.azure</groupId>    <artifactId>azure-mgmt-network</artifactId>    <version>${azure-sdk-version}</version></dependency><dependency>    <groupId>com.microsoft.azure</groupId>    <artifactId>azure-mgmt-sql</artifactId>    <version>${azure-sdk-version}</version></dependency><dependency>    <groupId>com.microsoft.azure</groupId>    <artifactId>azure-mgmt-storage</artifactId>    <version>${azure-sdk-version}</version></dependency><dependency>    <groupId>com.microsoft.azure</groupId>    <artifactId>azure-mgmt-websites</artifactId>    <version>${azure-sdk-version}</version></dependency><dependency>    <groupId>com.microsoft.azure</groupId>    <artifactId>azure-mgmt-media</artifactId>    <version>${azure-sdk-version}</version></dependency><dependency>    <groupId>com.microsoft.azure</groupId>    <artifactId>azure-servicebus</artifactId>    <version>${azure-sdk-version}</version></dependency><dependency>    <groupId>com.microsoft.azure</groupId>    <artifactId>azure-serviceruntime</artifactId>    <version>${azure-sdk-version}</version></dependency><dependency>    <groupId>com.microsoft.azure</groupId>    <artifactId>adal4j</artifactId>    <version>1.0.0</version></dependency>

获取Access Token

private static AuthenticationResult getAccessTokenFromServicePrincipalCredentials() throws            ServiceUnavailableException, MalformedURLException, ExecutionException,            InterruptedException {    AuthenticationContext context;    AuthenticationResult result = null;    ExecutorService service = null;    try {        service = Executors.newFixedThreadPool(1);        context = new AuthenticationContext(                        "https://login.chinacloudapi.cn/{telent-id}",                         true,                         service);        ClientCredential cred = new ClientCredential("{application-id}", "{app password}");        Future<AuthenticationResult> future = context.acquireToken(                        "https://management.chinacloudapi.cn/",                         cred,                         null);        result = future.get();    } finally {        service.shutdown();    }    if (result == null) {        throw new ServiceUnavailableException(                "authentication result was null");    }    return result;}

telent-id 对应 订阅信息上使用的telentID
application-id 创建应用返回的ApplicationID
app password 创建应用时填写的密码

访问订阅下资源

  /**   * Request a listing of all resource groups within a subscription using a service principal    * for authentication.   *   * @param args arguments supplied at the command line (they are not used)   * @throws Exception all of the exceptions!!   */  public static void main(String[] args) throws Exception {      ResourceManagementClient client = ServicePrincipalExample.createResourceManagementClient();      List<ResourceGroupExtended> groups = client.getResourceGroupsOperations().list(null)              .getResourceGroups();      for (ResourceGroupExtended group : groups) {          System.out.println(group.getName());      }  }  /**   * Use the ResourceManagementService factory helper method to create a client based on the   * management config.   *   * @return ResourceManagementClient a client to be used to make authenticated requests to the ARM    * REST API   * @throws Exception all of the exceptions   */  protected static ResourceManagementClient createResourceManagementClient() throws Exception {      Configuration config = createConfiguration();      return ResourceManagementService.create(config);  }  /**   * Create configuration builds the management configuration needed for creating the        * ResourceManagementService.   *    * The config contains the baseURI which is the base of the ARM REST service, the subscription id as    * the context for the ResourceManagementService and the AAD token required for the HTTP   * Authorization header.   *   * @return Configuration the generated configuration   * @throws Exception all of the exceptions!!   */  public static Configuration createConfiguration() throws Exception {      String baseUri = "https://management.chinacloudapi.cn/";      Configuration config = ManagementConfiguration.configure(              null,              new URI(baseUri),              "e0fbea86-6cf2-4b2d-81e2-9c59f4f96bcb",              getAccessTokenFromServicePrincipalCredentials().getAccessToken());      config.setProperty(ManagementConfiguration.URI, new URI(baseUri));      return config;  }

相关资料:
https://azure.microsoft.com/en-us/documentation/articles/role-based-access-control-what-is/
https://azure.microsoft.com/en-us/documentation/articles/resource-group-overview/

0 0
原创粉丝点击