在 Azure Stack 中将 API 版本配置文件与 Java 配合使用Use API version profiles with Java in Azure Stack

适用于:Azure Stack 集成系统和 Azure Stack 开发工具包Applies to: Azure Stack integrated systems and Azure Stack Development Kit

用于 Azure Stack 资源管理器的 Java SDK 提供了相关工具来帮助构建和管理基础结构。The Java SDK for the Azure Stack Resource Manager provides tools to help you build and manage your infrastructure. 该 SDK 中的资源提供程序包括了计算、网络、存储、应用服务和 KeyVaultResource providers in the SDK include compute, networking, storage, app services, and KeyVault. Java SDK 纳入了 API 配置文件,其方法是:将依赖项包括在 Pom.xml 文件中,由后者加载 .java 文件中的正确模块。The Java SDK incorporates API profiles by including dependencies in the Pom.xml file that loads the correct modules in the .java file. 不过,可以添加多个作为依赖项的配置文件,例如,添加 2018-03-01-hybridlatest 作为 Azure 配置文件。However, you can add multiple profiles as dependencies, such as the 2018-03-01-hybrid, or latest as the Azure profile. 使用这些依赖项来加载正确的模块,这样在创建资源类型时,就可以从那些要使用的配置文件中选择具体的 API 版本。Using these dependencies loads the correct module so that when you create your resource type, you are able to select which API version from those profiles you want to use. 这样就可以使用 Azure 中的最新版本,同时使用 Azure Stack 的最新 API 版本进行开发。This enables you to use the latest versions in Azure, while developing against the most current API versions for Azure Stack. 使用 Java SDK 可以获得真正的混合云开发人员体验。Using the Java SDK enables a true hybrid cloud developer experience. Java SDK 中的 API 配置文件可以用来在公有云 Azure 资源和 Azure Stack 中的资源之间进行切换,实现混合云开发。API profiles in the Java SDK enable hybrid cloud development by helping you switch between global Azure resources and resources in Azure Stack.

Java 与 API 版本配置文件Java and API version profiles

API 配置文件是资源提供程序和 API 版本的组合。An API profile is a combination of resource providers and API versions. 可以使用 API 配置文件获取资源提供程序包中每个资源类型的最新且最稳定的版本。You can use an API profile to get the latest, most stable version of each resource type in a resource provider package.

  • 若要使用所有服务的最新版本,请使用 latest 配置文件作为依赖项。To use the latest versions of all the services, use the latest profile as the dependency.

    • 若使用 latest 配置文件,则依赖项为 com.microsoft.azureTo use the latest profile, the dependency is com.microsoft.azure.

    • 若要使用与 Azure Stack 兼容的服务,请使用 com.microsoft.azure.profile_2018_03_01_hybrid 配置文件。To use the services compatible with Azure Stack, use the com.microsoft.azure.profile_2018_03_01_hybrid profile.

      • 请在 Pom.xml 文件中将其指定为依赖项,如果从下拉列表中选择了正确的类,则会自动加载模块,就像使用 .NET 一样。This is to be specified in the Pom.xml file as a dependency, which loads modules automatically if you choose the right class from the dropdown list as you would with .NET.

      • 每个模块的顶部都如下所示: Import com.microsoft.azure.management.resources.v2018_03_01.ResourceGroupThe top of each module appears as follows: Import com.microsoft.azure.management.resources.v2018_03_01.ResourceGroup

    • 依赖项如下所示:Dependencies appear as follows:

      <dependency>
      <groupId>com.microsoft.azure.profile_2018_03_01_hybrid</groupId>
      <artifactId>azure</artifactId>
      <version>1.0.0-beta</version>
      </dependency>
      
    • 若要使用特定资源提供程序中某个资源类型的特定 API 版本,请使用通过 Intellisense 定义的特定 API 版本。To use specific API versions for a resource type in a specific resource provider, use the specific API versions defined through Intellisense.

请注意,可以在同一应用程序中组合所有选项。Note that you can combine all of the options in the same application.

安装 Azure Java SDKInstall the Azure Java SDK

使用以下步骤安装 Java SDK:Use the following steps to install the Java SDK:

  1. 按照正式说明安装 Git。Follow the official instructions to install Git. 有关说明,请参阅入门 - 安装 GitFor instructions, see Getting Started - Installing Git.

  2. 按照说明安装 Java SDKMavenFollow the instructions to install the Java SDK and Maven. 正确的版本是 Java 开发人员工具包的版本 8。The correct version is version 8 of the Java Developer Kit. 正确的 Apache Maven 是 3.0 或更高版本。The correct Apache Maven is version 3.0 or above. JAVA_HOME 环境变量必须设置为 Java 开发人员工具包的安装位置,以完成本快速入门。The JAVA_HOME environment variable must be set to the install location of the Java Development Kit to complete the quickstart. 有关详细信息,请参阅使用 Java 和 Maven 创建第一个函数For more information, see Create your first function with Java and Maven.

  3. 若要安装正确的依赖项包,请在 Java 应用程序中打开 Pom.xml 文件。To install the correct dependency packages, open the Pom.xml file in your Java application. 添加一个依赖项,如以下代码中所示:Add a dependency, as shown in the following code:

    <dependency>
    <groupId>com.microsoft.azure.profile_2018_03_01_hybrid</groupId>
    <artifactId>azure</artifactId>
    <version>1.0.0-beta</version>
    </dependency>
    
  4. 需要安装的包取决于你要使用的配置文件版本。The set of packages that need to be installed depends on the profile version you want to use. 配置文件版本的包名如下:The package names for the profile versions are:

    • com.microsoft.azure.profile_2018_03_01_hybridcom.microsoft.azure.profile_2018_03_01_hybrid
    • com.microsoft.azurecom.microsoft.azure
      • latestlatest
  5. 如果不可用,请创建一个订阅,并保存订阅 ID 供以后使用。If not available, create a subscription and save the subscription ID for later use. 有关如何创建订阅的说明,请参阅在 Azure Stack 中创建套餐的订阅For instructions on how to create a subscription, see Create subscriptions to offers in Azure Stack.

  6. 创建服务主体并保存客户端 ID 和客户端机密。Create a service principal and save the client ID and the client secret. 有关如何为 Azure Stack 创建服务主体的说明,请参阅提供对 Azure Stack 的应用程序访问权限For instructions on how to create a service principal for Azure Stack, see Provide applications access to Azure Stack. 请注意,创建服务主体时的客户端 ID 也称为应用程序 ID。Note that the client ID is also known as the application ID when creating a service principal.

  7. 确保服务主体在订阅上具有“参与者/所有者”角色。Make sure your service principal has the contributor/owner role on your subscription. 有关如何将角色分配到服务主体的说明,请参阅提供对 Azure Stack 的应用程序访问权限For instructions on how to assign a role to service principal, see Provide applications access to Azure Stack.

先决条件Prerequisites

若要将 Azure Java SDK 与 Azure Stack 配合使用,必须提供以下值,然后使用环境变量来设置值。To use the Azure Java SDK with Azure Stack, you must supply the following values, and then set values with environment variables. 若要设置环境变量,请参阅表后针对操作系统的说明。To set the environmental variables, see the instructions following the table for your operating system.

ValueValue 环境变量Environment variables 说明Description
租户 IDTenant ID AZURE_TENANT_IDAZURE_TENANT_ID Azure Stack 租户 ID 的值。The value of your Azure Stack tenant ID.
客户端 IDClient ID AZURE_CLIENT_IDAZURE_CLIENT_ID 在上一部分中创建服务主体时保存的服务主体应用程序 ID。The service principal application ID saved when the service principal was created in the previous section.
订阅 IDSubscription ID AZURE_SUBSCRIPTION_IDAZURE_SUBSCRIPTION_ID 订阅 ID 用于访问 Azure Stack 中的套餐。The subscription ID is how you access offers in Azure Stack.
客户端机密Client Secret AZURE_CLIENT_SECRETAZURE_CLIENT_SECRET 创建服务主体时保存的服务主体应用程序机密。The service principal application secret saved when the service principal was created.
资源管理器终结点Resource Manager Endpoint ARM_ENDPOINTARM_ENDPOINT 请参阅 Azure Stack 资源管理器终结点See the Azure Stack Resource Manager endpoint.
位置Location RESOURCE_LOCATIONRESOURCE_LOCATION 对于 Azure Stack 来说为 LocalLocal for Azure Stack.

若要查找你的 Azure Stack 的租户 ID,请参阅此处的说明。To find the tenant ID for your Azure Stack, see the instructions here. 若要设置环境变量,请执行以下操作:To set your environment variables, do the following:

Microsoft WindowsMicrosoft Windows

若要在 Windows 命令提示符中设置环境变量,请使用以下格式:To set the environment variables in a Windows command prompt, use the following format:

Set AZURE_TENANT_ID=<Your_Tenant_ID>

基于 MacOS、Linux 和 Unix 的系统MacOS, Linux, and Unix-based systems

在基于 Unix 的系统中,使用以下命令:In Unix based systems, use the following command:

Export AZURE_TENANT_ID=<Your_Tenant_ID>

信任 Azure Stack CA 根证书Trust the Azure Stack CA root certificate

如果使用的是 ASDK,则必须信任远程计算机上的 CA 根证书。If you are using the ASDK, you must trust the CA root certificate on your remote machine. 不需要对集成系统进行此操作。You will not need to do this with the integrated systems.

WindowsWindows

  1. 将 Azure Stack 自签名证书导出到桌面。Export the Azure Stack self-signed certificate to your desktop.

  2. 在命令提示符中,将目录更改为 %JAVA_HOME%\bin。In a command prompt, change directory to %JAVA_HOME%\bin.

  3. 运行以下命令:Run the following command:

    .\keytool.exe -importcert -noprompt -file <location of the exported certificate here> -alias root -keystore %JAVA_HOME%\lib\security\cacerts -trustcacerts -storepass changeit
    

Azure Stack 资源管理器终结点The Azure Stack Resource Manager endpoint

Azure 资源管理器是一种管理框架,可供管理员用来部署、管理和监视 Azure 资源。The Azure Resource Manager is a management framework that allows administrators to deploy, manage, and monitor Azure resources. Azure 资源管理器可以通过单个操作以组任务而不是单个任务的形式处理这些任务。Azure Resource Manager can handle these tasks as a group, rather than individually, in a single operation.

可以从资源管理器终结点获取元数据信息。You can get the metadata information from the Resource Manager endpoint. 该终结点返回 JSON 文件,以及运行代码所需的信息。The endpoint returns a JSON file with the information required to run your code.

请注意以下事项:Note the following considerations:

  • Azure Stack 开发工具包 (ASDK) 中的 ResourceManagerUrl 为: https://management.local.azurestack.external/。The ResourceManagerUrl in the Azure Stack Development Kit (ASDK) is: https://management.local.azurestack.external/.

  • 集成系统中的 ResourceManagerUrl 为:https://management.<location>.ext-<machine-name>.masd.stbtest.microsoft.com/The ResourceManagerUrl in integrated systems is: https://management.<location>.ext-<machine-name>.masd.stbtest.microsoft.com/.

检索所需的元数据:<ResourceManagerUrl>/metadata/endpoints?api-version=1.0To retrieve the metadata required: <ResourceManagerUrl>/metadata/endpoints?api-version=1.0.

示例 JSON 文件:Sample JSON file:

{
   "galleryEndpoint": "https://portal.local.azurestack.external:30015/",
   "graphEndpoint": "https://graph.chinacloudapi.cn/",
   "portal Endpoint": "https://portal.local.azurestack.external/",
   "authentication":
      {
      "loginEndpoint": "https://login.chinacloudapi.cn/",
      "audiences": ["https://management.<yourtenant>.partner.onmschina.cn/3cc5febd-e4b7-4a85-a2ed-1d730e2f5928"]
      }
}

现有 API 配置文件Existing API Profiles

  • com.microsoft.azure.profile_2018_03_01_hybrid:为 Azure Stack 生成的最新配置文件。com.microsoft.azure.profile_2018_03_01_hybrid: Latest profile built for Azure Stack. 请将此配置文件用于与 Azure Stack 最兼容的服务,前提是使用 1808 或更高的戳记。Use this profile for services to be most compatible with Azure Stack as long as you are on 1808 stamp or further.

  • com.microsoft.azure:包含所有服务的最新版本的配置文件。com.microsoft.azure: Profile consisting of the latest versions of all services. 使用所有服务的最新版本。Use the latest versions of all the services.

有关 Azure Stack 和 API 配置文件的详细信息,请参阅 API 配置文件的摘要For more information about Azure Stack and API profiles, see the Summary of API profiles.

Azure Java SDK API 配置文件的使用Azure Java SDK API profile usage

以下代码用于在 Azure Stack 上对服务主体进行身份验证。The following code authenticates the service principal on Azure Stack. 它使用租户 ID 和特定于 Azure Stack 的身份验证基准创建令牌:It creates a token using the tenant ID and the authentication base, which is specific to Azure Stack:

AzureTokenCredentials credentials = new ApplicationTokenCredentials(client, tenant, key, AZURE_STACK)
                    .withDefaultSubscriptionID(subscriptionID);
Azure azureStack = Azure.configure()
                    .withLogLevel(com.microsoft.rest.LogLevel.BASIC)
                    .authenticate(credentials, credentials.defaultSubscriptionID());

这样即可使用 API 配置文件依赖项将应用程序成功部署到 Azure Stack。This enables you to use the API profile dependencies to deploy your application successfully to Azure Stack.

定义 Azure Stack 环境设置函数Define Azure Stack environment setting functions

若要将 Azure Stack 云注册到正确的终结点,请使用以下代码:To register the Azure Stack cloud with the correct endpoints, use the following code:

AzureEnvironment AZURE_STACK = new AzureEnvironment(new HashMap<String, String>() {
                {
                    put("managementEndpointUrl", settings.get("audience"));
                    put("resourceManagerEndpointUrl", armEndpoint);
                    put("galleryEndpointUrl", settings.get("galleryEndpoint"));
                    put("activeDirectoryEndpointUrl", settings.get("login_endpoint"));
                    put("activeDirectoryResourceID", settings.get("audience"));
                    put("activeDirectoryGraphResourceID", settings.get("graphEndpoint"));
                    put("storageEndpointSuffix", armEndpoint.substring(armEndpoint.indexOf('.')));
                    put("keyVaultDnsSuffix", ".vault" + armEndpoint.substring(armEndpoint.indexOf('.')));
                }
            });

以下代码中的 getActiveDirectorySettings 调用从元数据终结点检索终结点。The getActiveDirectorySettings call in the following code retrieves the endpoints from the metadata endpoints. 它从所做的调用声明环境变量:It states the environment variables from the call that is made:

public static HashMap<String, String>
getActiveDirectorySettings(String armEndpoint) {

HashMap<String, String> adSettings = new HashMap<String, String>();

try {

// create HTTP Client
HttpClient httpClient = HttpClientBuilder.create().build();

// Create new getRequest with below mentioned URL
HttpGet getRequest = new
HttpGet(String.format("%s/metadata/endpoints?api-version=1.0",
armEndpoint));

// Add additional header to getRequest which accepts application/xml data
getRequest.addHeader("accept", "application/xml");

// Execute request and catch response
HttpResponse response = httpClient.execute(getRequest);

使用 API 配置文件的示例Samples using API profiles

若要使用 .NET 和 Azure Stack API 配置文件来创建解决方案,可以将以下 GitHub 示例用作参考:You can use the following GitHub samples as references for creating solutions with .NET and Azure Stack API profiles:

示例单元测试项目Sample Unit Test Project

  1. 使用以下命令克隆存储库:Clone the repository using the following command:

    git clone https://github.com/Azure-Samples/Hybrid-resources-java-manage-resource-group.git

  2. 创建 Azure 服务主体并分配用于访问订阅的角色。Create an Azure service principal and assign a role to access the subscription. 有关如何创建服务主体的说明,请参阅使用 Azure PowerShell 创建具有证书的服务主体For instructions on creating a service principal, see Use Azure PowerShell to create a service principal with a certificate.

  3. 检索以下必需的环境变量值:Retrieve the following required environment variable values:

    • AZURE_TENANT_IDAZURE_TENANT_ID
    • AZURE_CLIENT_IDAZURE_CLIENT_ID
    • AZURE_CLIENT_SECRETAZURE_CLIENT_SECRET
    • AZURE_SUBSCRIPTION_IDAZURE_SUBSCRIPTION_ID
    • ARM_ENDPOINTARM_ENDPOINT
    • RESOURCE_LOCATIONRESOURCE_LOCATION
  4. 使用命令提示符,根据从已创建的服务主体检索的信息设置以下环境变量:Set the following environment variables using the information you retrieved from the service principal you created using the command prompt:

    • export AZURE_TENANT_ID={你的租户 ID}export AZURE_TENANT_ID={your tenant ID}
    • export AZURE_CLIENT_ID={你的客户端 ID}export AZURE_CLIENT_ID={your client ID}
    • export AZURE_CLIENT_SECRET={你的客户端机密}export AZURE_CLIENT_SECRET={your client secret}
    • export AZURE_SUBSCRIPTION_ID={你的订阅 ID}export AZURE_SUBSCRIPTION_ID={your subscription ID}
    • export ARM_ENDPOINT={你的 Azure Stack 资源管理器 URL}export ARM_ENDPOINT={your Azure Stack Resource Manager URL}
    • export RESOURCE_LOCATION={Azure Stack 的位置}export RESOURCE_LOCATION={location of Azure Stack}

    在 Windows 中,请使用 set 而不是 exportIn Windows, use set instead of export.

  5. 使用 getactivedirectorysettings 代码检索 arm 元数据终结点,使用 HTTP 客户端设置终结点信息。Use the getactivedirectorysettings code to retrieve the arm metadata endpoint and use the HTTP client to set the endpoint information.

    public static HashMap<String, String> getActiveDirectorySettings(String armEndpoint) {
    HashMap<String, String> adSettings = new HashMap<String,> String>();
    
    try {
    
    // create HTTP Client
    HttpClient httpClient = HttpClientBuilder.create().build();
    
    // Create new getRequest with below mentioned URL
    HttpGet getRequest = new
    HttpGet(String.format("%s/metadata/endpoints?api-version=1.0", armEndpoint));
    
    // Add additional header to getRequest which accepts application/xml data
    getRequest.addHeader("accept", "application/xml");
    
    // Execute request and catch response
    HttpResponse response = httpClient.execute(getRequest);
    
  6. 在 Pom.xml 文件中,添加以下依赖项,以便使用 Azure Stack 的 2018-03-01-hybrid 配置文件。In the Pom.xml file, add the following dependency to use the 2018-03-01-hybrid profile for Azure Stack. 此依赖项将为计算、网络、存储、KeyVault 和应用服务资源提供程序安装与此配置文件相关联的模块:This dependency installs the modules associated with this profile for the Compute, Networking, Storage, KeyVault and App Services resource providers:

    <dependency>
    <groupId>com.microsoft.azure.profile_2018_03_01_hybrid</groupId>
    <artifactId>azure</artifactId>
    <vers1s.0.0-beta</version>
    </dependency>
    
  7. 在打开的用于设置环境变量的命令提示符中,输入以下命令:In the command prompt that was open to set the environment variables, enter the following command:

    mvn clean compile exec:java
    

后续步骤Next steps

有关 API 配置文件的详细信息,请参阅:For more information about API profiles, see: