在 Azure Stack Hub 中将 API 版本配置文件与 Node.js 软件开发工具包 (SDK) 配合使用Use API version Profiles with Node.js software development kit (SDK) in Azure Stack Hub

Node.js 与 API 版本配置文件Node.js and API version profiles

可以使用 Node.js SDK 来帮助构建和管理应用的基础结构。You can use Node.js SDK to help build and manage the infrastructure for your apps. Node.js SDK 中的 API 配置文件可让你在 Azure 资源与 Azure Stack Hub 资源之间切换,为开发混合云解决方案提供帮助。API profiles in the Node.js SDK help with your hybrid cloud solutions by letting you switch between Azure resources and Azure Stack Hub resources. 只需编写代码一次,即可将目标限定于 Azure 和 Azure Stack Hub。You can code once and then target both Azure and Azure Stack Hub.

在本文中,可以使用 Visual Studio Code 作为开发工具。In this article, you can use Visual Studio Code as your development tool. Visual Studio Code 可以调试 Node.js SDK,并可让你运行应用并将其推送到 Azure Stack Hub 实例。Visual Studio Code can debug the Node.js SDK and allows you to run the app and push the app to your Azure Stack Hub instance. 可以通过 Visual Studio Code 或者在终端窗口中运行 node <nodefile.js> 命令进行调试。You can debug from Visual Studio Code or through a terminal window running the command node <nodefile.js>.

Node.js SDKThe Node.js SDK

Node.js SDK 提供 Azure Stack Hub 资源管理器工具。The Node.js SDK provides Azure Stack Hub Resource Manager tools. 该 SDK 中的资源提供程序包括了计算、网络、存储、应用服务和 KeyVault。Resource providers in the SDK include compute, networking, storage, app services, and KeyVault. 可在 Node.js 应用程序中安装的资源提供程序客户端库有 10 个。There are 10 resource provider client libraries that you can install in your node.js application. 还可以下载指定要用于 2018-03-01-hybrid2019-03-01-profile 的资源提供程序,以优化应用程序的内存。You can also download specify which resource provider you will use for the 2018-03-01-hybrid or 2019-03-01-profile in order to optimize the memory for your application. 每个模块包括资源提供程序、相应的 API 版本和 API 配置文件。Each module consists of a resource provider, the respective API version, and the API profile.

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 make use of the latest versions of all the services, use the latest profile of the packages.

  • 若要使用与 Azure Stack Hub 兼容的服务,请使用 @azure/arm-resources-profile-hybrid-2019-03-01@azure/arm-storage-profile-2019-03-01-hybridTo use the services compatible with Azure Stack Hub, use the @azure/arm-resources-profile-hybrid-2019-03-01 or @azure/arm-storage-profile-2019-03-01-hybrid

npm 中的包Packages in npm

每个资源提供程序都有自身的包。Each resource provider has its own package. 可以从 npm 注册表获取包。You can get the package from the npm registry.

可以找到以下包:You can find the following packages:

资源提供程序Resource provider 程序包Package
应用服务App Service @azure/arm-appservice-profile-2019-03-01-hybrid
Azure 资源管理器订阅Azure Resource Manager Subscriptions @azure/arm-subscriptions-profile-hybrid-2019-03-01
Azure 资源管理器策略Azure Resource Manager Policy @azure/arm-policy-profile-hybrid-2019-03-01
Azure 资源管理器 DNSAzure Resource Manager DNS @azure/arm-dns-profile-2019-03-01-hybrid
授权Authorization @azure/arm-authorization-profile-2019-03-01-hybrid
计算Compute @azure/arm-compute-profile-2019-03-01-hybrid
存储Storage @azure/arm-storage-profile-2019-03-01-hybrid
网络Network @azure/arm-network-profile-2019-03-01-hybrid
资源Resources @azure/arm-resources-profile-hybrid-2019-03-01
KeyvaultKeyvault @azure/arm-keyvault-profile-2019-03-01-hybrid

若要使用某个服务的最新 API 版本,请使用特定客户端库的最新配置文件。To use the latest API-version of a service, use the Latest profile of the specific client library. 例如,若要单独使用资源服务的最新 API 版本,请使用资源管理客户端库包的 azure-arm-resource 配置For example, if you would like to use the latest-API version of resources service alone, use the azure-arm-resource profile of the Resource Management Client Library. 文件。package.

对于资源提供程序的特定 API 版本,请使用包中定义的特定 API 版本。Use the specific API versions defined inside the package for the specific API-versions of a resource provider.

备注

可以在同一应用程序中组合所有选项。You can combine all of the options in the same application.

安装 Node.js SDKInstall the Node.js SDK

  1. 安装 Git。Install Git. 有关说明,请参阅入门 - 安装 GitFor instructions, see Getting Started - Installing Git.

  2. 安装或升级到 Node.js 的最新版本。Install or upgrade to the current version of Node.js. Node.js 还包含 npm JavaScript 包管理器。Node.js also includes the npm JavaScript package manager.

  3. 安装或升级 Visual Studio Code,并安装适用于 Visual Studio Code 的 Node.js 扩展Install or upgrade Visual Studio Code and install the Node.js extension for Visual Studio Code.

  4. 安装 Azure Stack Hub 资源管理器的客户端包。Install the client packages for the Azure Stack Hub Resource Manger. 有关详细信息,请参阅如何安装客户端库For more information, see how to install client libraries.

  5. 需安装的包取决于要使用的配置文件版本。The packages that need to be installed depends on the profile version you would like to use. 可以在 npm 中的包部分找到资源提供程序列表。You can find a list of resource providers in the Packages in npm section.

  6. 使用 npm 安装资源提供程序客户端库。Install the resource provider client library using npm. 从命令行中运行:npm install <package-name>From the command line, run: npm install <package-name>. 例如,可以运行 npm install @azure/arm-authorization-profile-2019-03-01-hybrid 来安装授权资源提供程序库。For example, you can run npm install @azure/arm-authorization-profile-2019-03-01-hybrid to install the authorization resource provider library.

  7. 使用 SDK 时,请创建订阅并记下订阅 ID。Create a subscription and make a note of the Subscription ID when you use the SDK. 有关说明,请参阅在 Azure Stack Hub 中创建套餐的订阅For instructions, see Create subscriptions to offers in Azure Stack Hub.

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

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

Node.js 先决条件Node.js prerequisites

若要将 Node.js Azure SDK 与 Azure Stack Hub 配合使用,必须提供以下值,然后使用环境变量来设置值。To use the Node.js Azure SDK with Azure Stack Hub, 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 TENANT_IDTENANT_ID Azure Stack Hub 租户 ID 的值。The value of your Azure Stack Hub tenant ID.
客户端 IDClient ID CLIENT_IDCLIENT_ID 在本文档上一部分创建服务主体时保存的服务主体应用程序 ID。The service principal application ID saved when service principal was created on the previous section of this document.
订阅 IDSubscription ID AZURE_SUBSCRIPTION_ID:订阅 ID 用于访问 Azure Stack Hub 中的套餐。AZURE_SUBSCRIPTION_ID The subscription ID is how you access offers in Azure Stack Hub.
客户端机密Client Secret APPLICATION_SECRETAPPLICATION_SECRET 创建服务主体时保存的服务主体应用程序机密。The service principal application Secret saved when service principal was created.
资源管理器终结点Resource Manager Endpoint ARM_ENDPOINTARM_ENDPOINT 参阅 Azure Stack Hub 资源管理器终结点See the Azure Stack Hub Resource Manager endpoint.

设置 Node.js 的环境变量Set your environmental variables for Node.js

若要定义环境变量:To set your environment variables:

  • Microsoft WindowsMicrosoft Windows

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

    set Tenant_ID=<Your_Tenant_ID>

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

    若要设置环境变量,请在 bash 提示符下使用以下格式:To set the environment variables, from a bash prompt, use the following format:

    export Azure_Tenant_ID=<Your_Tenant_ID>

Azure Stack Hub 资源管理器终结点The Azure Stack Hub 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.

备注

Azure Stack 开发工具包 (ASDK) 中的 ResourceManagerUrl 为:https://management.local.azurestack.external 集成系统中的 ResourceManagerUrlhttps://management.region.<fqdn>/,其中 <fqdn> 是完全限定的域名。The ResourceManagerUrl in the Azure Stack Development Kit (ASDK) is: https://management.local.azurestack.external The ResourceManagerUrl in integrated systems is: https://management.region.<fqdn>/, where <fqdn> is your fully qualified domain name. 检索所需的元数据:<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/",

    "graphEndpoint": "https://graph.windowsNode.js/",

    "portal Endpoint": "https://portal.local.azurestack.external/",

    "authentication": {

        "loginEndpoint": "https://login.windowsNode.js/",

        "audiences": ["https://management.<yourtenant>.partner.onmschina.cn/"]

    }

}

现有 API 配置文件Existing API profiles

  • @azure/arm-resourceprovider-profile-2019-03-01-hybrid@azure/arm-resourceprovider-profile-2019-03-01-hybrid

    为 Azure Stack Hub 生成的最新配置文件。Latest Profile built for Azure Stack Hub. 使用此配置文件可以使服务与阵列版本 1808 或更高版本的 Azure Stack Hub 最兼容。Use this profile for services to be most compatible with Azure Stack Hub as long as you are on 1808 stamp or further.

  • @azure-arm-resource@azure-arm-resource

    配置文件包含所有服务的最新版本。Profile consists of latest versions of all services. 使用 Azure 中所有服务的最新版本。Use the latest versions of all the services in Azure.

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

Azure Node.js SDK API 配置文件的用法Azure Node.js SDK API Profile usage

应该使用以下代码行来实例化配置文件客户端。The following lines should be used to instantiate a profile client. 此参数只是 Azure Stack Hub 或其他私有云所需要的。This parameter is only required for Azure Stack Hub or other private clouds. 默认情况下,全球 Azure 已有这些包含 @azure-arm-resource 或 @azure-arm-storage 的设置。Global Azure already has these settings by default with @azure-arm-resource or @azure-arm-storage.

var ResourceManagementClient = require('@azure/arm-resources-profile-hybrid-2019-03-01').ResourceManagementClient;

var StorageManagementClient = require('@azure/arm-storage-profile-2019-03-01-hybrid').StorageManagementClient;

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

var clientId = process.env['AZURE_CLIENT_ID'];
var tenantId = process.env['AZURE_TENANT_ID']; //"adfs"
var secret = process.env['AZURE_CLIENT_SECRET'];
var subscriptionId = process.env['AZURE_SUBSCRIPTION_ID'];
var base_url = process.env['ARM_ENDPOINT'];
var resourceClient, storageClient;

这样,便可以使用 API 配置文件客户端库将应用程序成功部署到 Azure Stack Hub。This will allow you to use the API Profile client library to deploy your application successfully to Azure Stack Hub.

以下代码片段使用为 Azure Stack Hub 实例指定的 Azure 资源管理器终结点,收集如上所示的数据,例如库终结点、图形终结点、受众和门户终结点。The below code snippet uses the Azure Resource Manager endpoint that you specify for your Azure Stack Hub instance and gathers the data shown above such as gallery endpoint, graph endpoint, audiences, and portal endpoint.

var map = {};
const fetchUrl = base_url + 'metadata/endpoints?api-version=1.0'

环境设置Environment settings

若要通过 Azure Stack Hub 环境对服务主体进行身份验证,请使用以下代码:使用此代码并在命令提示符中设置环境变量会自动为开发人员生成此映射。To authenticate the service principal to the Azure Stack Hub environment, use the following code: Using this code and setting your environment variables in the command prompt automatically generates this mapping for the developer.

function main() {
  var initializePromise = initialize();
  initializePromise.then(function (result) {
    var userDetails = result;
    console.log("Initialized user details");
    // Use user details from here
    console.log(userDetails)
    map["name"] = "AzureStack"
    map["portalUrl"] = userDetails.portalEndpoint 
    map["resourceManagerEndpointUrl"] = base_url 
    map["galleryEndpointUrl"] = userDetails.galleryEndpoint 
    map["activeDirectoryEndpointUrl"] = userDetails.authentication.loginEndpoint.slice(0, userDetails.authentication.loginEndpoint.lastIndexOf("/") + 1) 
    map["activeDirectoryResourceId"] = userDetails.authentication.audiences[0] 
    map["activeDirectoryGraphResourceId"] = userDetails.graphEndpoint 
    map["storageEndpointSuffix"] = "." + base_url.substring(base_url.indexOf('.'))  
    map["keyVaultDnsSuffix"] = ".vault" + base_url.substring(base_url.indexOf('.')) 
    map["managementEndpointUrl"] = userDetails.authentication.audiences[0] 
    map["validateAuthority"] = "false"
    Environment.Environment.add(map);

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

可以参考以下示例使用 Node.js 和 Azure Stack Hub API 配置文件来创建解决方案。You can use the following samples as a reference for creating solutions with Node.js and Azure Stack Hub API profiles. 可从 GitHub 上的以下存储库中获取示例:You can get the samples from GitHub in the following repositories:

示例 - 创建存储帐户Sample create storage account

  1. 克隆存储库。Clone the repository.

    git clone https://github.com/sijuman/storage-node-resource-provider-getting-started.git
    
  2. 使用 cd 命令转到存储库的克隆。cd into your clone of the repository.

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

  4. 检索以下必需值:Retrieve the following required values:

    • 租户 IDTenant ID
    • 客户端 ID(应用程序 ID)Client ID (application ID)
    • 客户端机密Client secret
    • Azure 订阅 IDAzure Subscription ID
    • Azure Stack Hub 资源管理器终结点Azure Stack Hub Resource Manager endpoint
  5. 使用命令提示符,根据从已创建的服务主体检索的信息设置以下环境变量:Set the following environment variables using the information you retrieved from the service principal you created using the command prompt:

    备注

    在 Windows 上,请使用 set 而不是 exportOn Windows, use set instead of export.

    export TENANT_ID=<your tenant id>
    export CLIENT_ID=<your client id>
    export APPLICATION_SECRET=<your client secret>K
    export AZURE_SUBSCRIPTION_ID=<your subscription id>
    export ARM_ENDPOINT=<your Azure Stack Hub Resource manager URL>
    
  6. 打开示例应用程序的 index.js 文件。Open the index.js file of the sample application.

  7. 将位置变量设置为你的 Azure Stack Hub 位置。Set the location variable to your Azure Stack Hub location. 例如 LOCAL = "local"For example, LOCAL = "local".

  8. 设置凭据,以便向 Azure Stack Hub 进行身份验证。Set the credentials that will allow you to authenticate to Azure Stack Hub. 此代码部分包含在本示例的 index.js 文件中。This portion of the code is included in this sample on the index.js file.

    var clientId = process.env['CLIENT_ID'];
    var tenantId = process.env['TENANT_ID']; //"adfs"
    var secret = process.env['APPLICATION_SECRET'];
    var subscriptionId = process.env['AZURE_SUBSCRIPTION_ID'];
    var base_url = process.env['ARM_ENDPOINT'];
    var resourceClient, storageClient;
    
  9. 使用上面规定的客户端库组合,检查是否设置了正确的客户端库。Checks that you have set the right client libraries, using a combination of the client libraries stipulated above. 本示例使用了以下代码:In this sample we have used the following below:

    var ResourceManagementClient = require('@azure/arm-resources-profile-hybrid-2019-03-01').ResourceManagementClient;
    var StorageManagementClient = require('@azure/arm-storage-profile-2019-03-01-hybrid').StorageManagementClient;
    
  10. 使用 npm 模块搜索,找到 2019-03-01-hybrid,为计算、网络、存储、KeyVault 和应用服务资源提供程序安装与此配置文件相关联的包。Using npm modules search, locate the 2019-03-01-hybrid and install the packages associated with this profile for the Compute, Networking, Storage, KeyVault and App Services resource providers.

    为此,可打开命令提示符,将其重定向到存储库的根文件夹,然后针对使用的每个资源提供程序运行 npm install @azure/arm-keyvault-profile-2019-03-01-hybridThis can be done by opening command prompt, redirecting it to the root folder of the repository, and running npm install @azure/arm-keyvault-profile-2019-03-01-hybrid for each resource provider used.

  11. 在命令提示符下,运行 npm install 命令安装所有 Node.js 模块。On the command prompt, run the command npm install to install all node.js modules.

  12. 运行该示例。Run the sample.

    node index.js
    
  13. 若要在用完 index.js 之后进行清理,请运行清理脚本。To clean up after index.js, run the cleanup script.

    Node cleanup.js <resourceGroupName> <storageAccountName>
    
  14. 本示例现已成功完成。The sample has successfully been completed. 有关示例的详细信息,请参阅下文。For more information on the sample, see below.

index.js 有何用途?What does index.js do?

本示例可创建新的存储帐户、列出订阅或资源组中的存储帐户、列出存储帐户密钥、重新生成存储帐户密钥、获取存储帐户属性、更新存储帐户 SKU,以及检查存储帐户名是否可用。The sample creates a new storage account, lists the storage accounts in the subscription or resource group, lists the storage account keys, regenerates the storage account keys, gets the storage account properties, updates the storage account SKU, and checks storage account name availability.

本示例首先使用你的服务主体登录,然后使用你的凭据和订阅 ID 创建 ResourceManagementClientStorageManagementClient 对象。The sample starts by logging in using your service principal and creating ResourceManagementClient and StorageManagementClient objects using your credentials and subscription ID.

然后,本示例设置要在其中创建新存储帐户的资源组。The sample then sets up a resource group in which it will create the new storage account.

function createResourceGroup(callback) {
  var groupParameters = { location: location, tags: { sampletag: 'sampleValue' } };
  console.log('\nCreating resource group: ' + resourceGroupName);
  return resourceClient.resourceGroups.createOrUpdate(resourceGroupName, groupParameters, callback);
}

新建存储帐户Create a new storage account

接下来,本示例创建新的存储帐户,并将其与上一步骤中创建的资源组相关联。Next, the sample creates a new storage account that is associated with the resource group created in the previous step.

在此情况下,系统会随机生成存储帐户名以确保唯一性。In this case, the storage account name is randomly generated to assure uniqueness. 但是,如果订阅中已有同名的帐户,则创建新存储帐户的调用仍会成功。However, the call to create a new storage account will succeed if an account with the same name already exists in the subscription.

var createParameters = {
    location: location,
    sku: {
        name: accType,
    },
    kind: 'Storage',
    tags: {
        tag1: 'val1',
        tag2: 'val2'
    }
};


console.log('\\n--&gt;Creating storage account: ' + storageAccountName + ' with parameters:\\n' + util.inspect(createParameters));

return storageClient.storageAccounts.create(resourceGroupName, storageAccountName, createParameters, callback);

列出订阅或资源组中的存储帐户List storage accounts in the subscription or resource group

本示例列出指定订阅中的所有存储帐户:The sample lists all of the storage accounts in a given subscription:

console.log('\\n--&gt;Listing storage accounts in the current subscription.');

return storageClient.storageAccounts.list(callback);

It also lists storage accounts in the resource group:

    console.log('\\n--&gt;Listing storage accounts in the resourceGroup : ' + resourceGroupName);

return storageClient.storageAccounts.listByResourceGroup(resourceGroupName, callback);

读取和重新生成存储帐户密钥Read and regenerate storage account keys

本示例列出新建的存储帐户和资源组的存储帐户密钥:The sample lists storage account keys for the newly created storage account and resource group:

console.log('\\n--&gt;Listing storage account keys for account: ' + storageAccountName);

return storageClient.storageAccounts.listKeys(resourceGroupName, storageAccountName, callback);

它还会重新生成帐户访问密钥:It also regenerates the account access keys:

console.log('\\n--&gt;Regenerating storage account keys for account: ' + storageAccountName);

return storageClient.storageAccounts.regenerateKey(resourceGroupName, storageAccountName, 'key1', callback);

获取存储帐户属性Get storage account properties

本示例读取存储帐户的属性:The sample reads the storage account's properties:

console.log('\\n--&gt;Getting info of storage account: ' + storageAccountName);

return storageClient.storageAccounts.getProperties(resourceGroupName, storageAccountName, callback);

检查存储帐户名的可用性Check storage account name availability

本示例检查 Azure 中是否可使用给定的存储帐户名:The sample checks whether a given storage account name is available in Azure:

console.log('\\n--&gt;Checking if the storage account name : ' + storageAccountName + ' is available.');

return storageClient.storageAccounts.checkNameAvailability(storageAccountName, callback);

删除存储帐户和资源组Delete the storage account and resource group

运行 cleanup.js 可删除本示例创建的存储帐户:Running cleanup.js deletes the storage account that the sample created:

console.log('\\nDeleting storage account : ' + storageAccountName);
return storageClient.storageAccounts.deleteMethod(resourceGroupName, storageAccountName, callback);

它还会删除本示例创建的资源组:It also deletes the resource group that the sample created:

console.log('\\nDeleting resource group: ' + resourceGroupName);

return resourceClient.resourceGroups.deleteMethod(resourceGroupName, callback);

后续步骤Next steps

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