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

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

Go 和版本配置文件Go and version profiles

配置文件结合了不同服务的不同版本的不同资源类型。A profile is a combination of different resource types with different versions from different services. 使用配置文件有助于混合和匹配不同的资源类型。Using a profile helps you mix and match between different resource types. 配置文件提供以下优点:Profiles can provide the following benefits:

  • 通过锁定到特定的 API 版本提供应用稳定性。Stability for your app by locking to specific API versions.
  • 提供应用与 Azure Stack 和区域性 Azure 数据中心的兼容性。Compatibility for your app with Azure Stack and regional Azure datacenters.

在 Go SDK 中,配置文件在配置文件路径下可用。In the Go SDK, profiles are available under the profiles path. 配置文件版本号以 YYYY-MM-DD 格式标记。Profile version numbers are labeled in the YYYY-MM-DD format. 最新的 Azure Stack API 配置文件版本为 2019-03-01,适用于 Azure Stack 版本 1904 或更高版本。The latest Azure Stack API profile version is 2019-03-01 for Azure Stack versions 1904 or later. 若要从配置文件导入给定的服务,请从配置文件导入其相应的模块。To import a given service from a profile, import its corresponding module from the profile. 例如,若要从 2019-03-01 配置文件导入计算服务,请使用以下代码:For example, to import Compute service from 2019-03-01 profile, use the following code:

import "github.com/Azure/azure-sdk-for-go/profiles/2019-03-01/compute/mgmt/compute"

安装 Azure SDK for GoInstall the Azure SDK for Go

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

  2. 安装 Go 编程语言Install the Go programming language. Azure 的 API 配置文件需要 Go 1.9 或更高版本。API profiles for Azure require Go version 1.9 or newer.

  3. 运行以下 bash 命令,安装 Azure Go SDK 及其依赖项:Install the Azure Go SDK and its dependencies by running the following bash command:

    go get -u -d github.com/Azure/azure-sdk-for-go/...
    

Go SDKThe Go SDK

可通过以下链接找到有关 Azure Go SDK 的详细信息:You can find more information about the Azure Go SDK at the following links:

Go-AutoRest 依赖项Go-AutoRest dependencies

Go SDK 依赖 Azure Go-AutoRest 模块将 REST 请求发送到 Azure 资源管理器终结点。The Go SDK depends on the Azure Go-AutoRest modules to send REST requests to Azure Resource Manager endpoints. 必须从 GitHub 上的 Azure Go-AutoRest 导入 Azure Go-AutoRest 模块依赖项。You must import the Azure Go-AutoRest module dependencies from Azure Go-AutoRest on GitHub. 可以在 Install 节中找到 install bash 命令。You can find the install bash commands in the Install section.

如何在 Azure Stack 上使用 Go SDK 配置文件How to use Go SDK profiles on Azure Stack

若要在 Azure Stack 上运行 Go 代码的示例,请遵循以下步骤:To run a sample of Go code on Azure Stack, follow these steps:

  1. 安装 Azure SDK for Go 及其依赖项。Install the Azure SDK for Go and its dependencies. 有关说明,请参阅上一部分安装 Azure SDK for GoFor instructions, see the previous section, Install Azure SDK for Go.

  2. 从资源管理器终结点获取元数据信息。Get the metadata info from the Resource Manager endpoint. 该终结点返回 JSON 文件,其中包含运行 Go 代码所需的信息。The endpoint returns a JSON file with the info required to run your Go code.

    Note

    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.<region>.<fqdn>/The ResourceManagerUrl in integrated systems is: https://management.<region>.<fqdn>/
    检索所需的元数据:<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"]
      }
    }
    
  3. 如果不可用,请创建订阅,并保存订阅 ID 供稍后使用。If not available, create a subscription and save the subscription ID to be used later. 有关创建订阅的信息,请参阅在 Azure Stack 中创建套餐的订阅For info on creating a subscription, see Create subscriptions to offers in Azure Stack.

  4. 创建使用客户端密码、具有“订阅”范围和“所有者”角色的服务主体。 Create a service principal that uses a client secret, with Subscription scope and Owner role. 保存服务主体的 ID 和机密。Save the service principal ID and secret. 有关为 Azure Stack 创建服务主体的信息,请参阅使用应用标识访问资源For information about creating a service principal for Azure Stack, see Use an app identity to access resources. 现已设置 Azure Stack 环境。Your Azure Stack environment is now set up.

  5. 在代码中从 Go SDK 配置文件导入服务模块。Import a service module from the Go SDK profile in your code. 最新版本的 Azure Stack 配置文件为 2019-03-01The current version of Azure Stack profile is 2019-03-01. 例如,若要从 2019-03-01 配置文件类型导入网络模块,请使用以下代码:For example, to import a network module from the 2019-03-01 profile type, use the following code:

    package main
     import "github.com/Azure/azure-sdk-for-go/profiles/2019-03-01/network/mgmt/network"
    
  6. 在函数中,使用 New 客户端函数调用创建客户端并对其进行身份验证。In your function, create and authenticate a client with a New client function call. 若要创建虚拟网络客户端,请使用以下代码:To create a virtual network client, use the following code:

    package main
    
    import "github.com/Azure/azure-sdk-for-go/profiles/2019-03-01/network/mgmt/network"
    
    func main() {
       vnetClient := network.NewVirtualNetworksClientWithBaseURI("<baseURI>", "(subscriptionID>")
       vnetClient.Authorizer = autorest.NewBearerAuthorizer(token)
    

    <baseURI> 设置为在步骤 2 中使用的 ResourceManagerUrl 值。Set <baseURI> to the ResourceManagerUrl value used in step 2. <subscriptionID> 设置为在步骤 3 中保存的 SubscriptionID 值。Set <subscriptionID> to the SubscriptionID value saved from step 3.

    若要创建令牌,请参阅下一部分。To create the token, see the next section.

  7. 使用在上一步骤中创建的客户端调用 API 方法。Invoke API methods by using the client that you created in the previous step. 例如,若要使用上一步骤所述的客户端创建虚拟网络,请参阅以下示例:For example, to create a virtual network by using the client from the previous step, see the following example:

    package main
    
    import "github.com/Azure/azure-sdk-for-go/profiles/2019-03-01/network/mgmt/network"
    func main() {
    vnetClient := network.NewVirtualNetworksClientWithBaseURI("<baseURI>", "(subscriptionID>")
    vnetClient .Authorizer = autorest.NewBearerAuthorizer(token)
    
    vnetClient .CreateOrUpdate( )
    

有关使用 Go SDK 配置文件在 Azure Stack 中创建虚拟网络的完整示例,请参阅示例For a complete example of creating a virtual network on Azure Stack by using the Go SDK profile, see the example.

身份验证Authentication

若要使用 Go SDK 从 Azure Active Directory 获取 Authorizer 属性,请安装 Go-AutoRest 模块。To get the Authorizer property from Azure Active Directory using the Go SDK, install the Go-AutoRest modules. 这些模块应该已通过“GO SDK”安装进行安装。These modules should have been already installed with the "Go SDK" installation. 如果未安装,请从 GitHub 安装身份验证包If they aren't, install the authentication package from GitHub.

Authorizer 必须设置为资源客户端的授权者。The Authorizer must be set as the authorizer for the resource client. 可通过不同的方式使用客户端凭据在 Azure Stack 上获取授权者令牌:There are different ways to get authorizer tokens on Azure Stack by using client credentials:

  1. 如果可以使用订阅中具有所有者角色的某个服务主体,请跳过此步骤。If a service principal with owner role on the subscription is available, skip this step. 否则,请参阅使用应用标识访问资源,了解有关如何创建使用客户端密码的服务主体的说明以及有关如何为其分配范围为订阅的“所有者”角色的帮助。Otherwise, see Use an app identity to access resources for instructions on creating a service principal that uses a client secret, and for help on how to assign it an "owner" role scoped to your subscription. 确保捕获服务主体应用程序 ID 和机密。Be sure to capture the service principal application ID and secret.

  2. 在代码中通过 Go-AutoRest 导入 adal 包。Import the adal package from Go-AutoRest in your code.

    package main
    import "github.com/Azure/go-autorest/autorest/adal"
    
  3. 使用 NewOAuthConfig 方法从 adal 模块创建 oauthConfigCreate an oauthConfig by using NewOAuthConfig method from adal module.

    package main
    
    import "github.com/Azure/go-autorest/autorest/ada1"
    
    func CreateToken() (adal.OAuthTokenProvider, error) {
       var token adal.OAuthTokenProvider
       oauthConfig, err := adal.NewOAuthConfig(activeDirectoryEndpoint, tenantID)
    }
    

    <activeDirectoryEndpoint> 设置为在本文上一部分中检索的 ResourceManagerUrl 元数据中的 loginEndpoint 属性值。Set <activeDirectoryEndpoint> to the value of the loginEndpoint property from the ResourceManagerUrl metadata retrieved on the previous section of this document. <tenantID> 值设置为 Azure Stack 租户 ID。Set the <tenantID> value to your Azure Stack tenant ID.

  4. 最后,使用 NewServicePrincipalToken 方法从 adal 模块创建服务主体令牌:Finally, create a service principal token by using the NewServicePrincipalToken method from the adal module:

    package main
    
    import "github.com/Azure/go-autorest/autorest/adal"
    
    func CreateToken() (adal.OAuthTokenProvider, error) {
        var token adal.OAuthTokenProvider
        oauthConfig, err := adal.NewOAuthConfig(activeDirectoryEndpoint, tenantID)
        token, err = adal.NewServicePrincipalToken(
            *oauthConfig,
            clientID,
            clientSecret,
            activeDirectoryResourceID)
        return token, err
    

    <activeDirectoryResourceID> 设置为在本文上一部分中检索的 ResourceManagerUrl 元数据中的“audience”列表值之一。Set <activeDirectoryResourceID> to one of the values in the "audience" list from the ResourceManagerUrl metadata retrieved in the previous section of this article. <clientID> 设置为在本文上一部分创建服务主体时保存的服务主体应用程序 ID。Set <clientID> to the service principal application ID saved when the service principal was created in the previous section of this article. <clientSecret> 设置为在本文上一部分创建服务主体时保存的服务主体应用程序机密。Set <clientSecret> to the service principal application secret saved when the service principal was created in the previous section of this article.

示例Example

本示例演示用于在 Azure Stack 中创建虚拟网络的 Go 代码示例。This example shows a sample of Go code that creates a virtual network on Azure Stack. 有关 Go SDK 的完整示例,请参阅 Azure Go SDK 示例存储库For complete examples of the Go SDK, see the Azure Go SDK samples repository. 可从该存储库的服务文件夹中的 hybrid 路径下获取 Azure Stack 示例。Azure Stack samples are available under the hybrid path inside service folders of the repository.

Note

若要运行此示例中的代码,请验证使用的订阅是否具有列为“已注册”的“网络”资源提供程序。 To run the code in this example, verify that the subscription used has the Network resource provider listed as Registered. 若要验证,请在 Azure Stack 门户中找到该订阅,然后选择“资源提供程序”。 To verify, look for the subscription in the Azure Stack portal, and select Resource providers.

  1. 在代码中导入所需的包。Import the required packages in your code. 使用 Azure Stack 上最新的可用配置文件来导入网络模块。Use the latest available profile on Azure Stack to import the network module:

    package main
    
    import (
        "context"
        "fmt"
        "github.com/Azure/azure-sdk-for-go/profiles/2019-03-01/network/mgmt/network"
        "github.com/Azure/go-autorest/autorest"
        "github.com/Azure/go-autorest/autorest/adal"
        "github.com/Azure/go-autorest/autorest/to"
    )
    
  2. 定义环境变量。Define your environment variables. 若要创建虚拟网络,必须有一个资源组。To create a virtual network, you must have a resource group.

    var (
        activeDirectoryEndpoint = "yourLoginEndpointFromResourceManagerUrlMetadata"
        tenantID = "yourAzureStackTenantID"
        clientID = "yourServicePrincipalApplicationID"
        clientSecret = "yourServicePrincipalSecret"
        activeDirectoryResourceID = "yourAudienceFromResourceManagerUrlMetadata"
        subscriptionID = "yourSubscriptionID"
        baseURI = "yourResourceManagerURL"
        resourceGroupName = "existingResourceGroupName"
    )
    
  3. 定义环境变量后,请使用 adal 包添加用于创建身份验证令牌的方法。Now that you've defined your environment variables, add a method to create an authentication token by using the adal package. 有关身份验证的详细信息,请参阅上一部分。For more info on authentication, see the previous section.

    //CreateToken creates a service principal token
    func CreateToken() (adal.OAuthTokenProvider, error) {
       var token adal.OAuthTokenProvider
       oauthConfig, err := adal.NewOAuthConfig(activeDirectoryEndpoint, tenantID)
       token, err = adal.NewServicePrincipalToken(
           *oauthConfig,
           clientID,
           clientSecret,
           activeDirectoryResourceID)
       return token, err
    }
    
  4. 添加 main 方法。Add the main method. main 方法首先使用上一步骤中定义的方法获取令牌。The main method first gets a token by using the method that is defined in the previous step. 然后,该方法使用配置文件中的网络模块创建客户端。Then, it creates a client by using a network module from the profile. 最后创建虚拟网络。Finally, it creates a virtual network.

    package main
    
    import (
       "context"
       "fmt"
       "github.com/Azure/azure-sdk-for-go/profiles/2019-03-01/network/mgmt/network"
       "github.com/Azure/go-autorest/autorest"
       "github.com/Azure/go-autorest/autorest/adal"
       "github.com/Azure/go-autorest/autorest/to"
    )
    
    var (
       activeDirectoryEndpoint = "yourLoginEndpointFromResourceManagerUrlMetadata"
       tenantID = "yourAzureStackTenantID"
       clientID = "yourServicePrincipalApplicationID"
       clientSecret = "yourServicePrincipalSecret"
       activeDirectoryResourceID = "yourAudienceFromResourceManagerUrlMetadata"
      subscriptionID = "yourSubscriptionID"
      baseURI = "yourResourceManagerURL"
      resourceGroupName = "existingResourceGroupName"
    )
    
    //CreateToken creates a service principal token
    func CreateToken() (adal.OAuthTokenProvider, error) {
       var token adal.OAuthTokenProvider
       oauthConfig, err := adal.NewOAuthConfig(activeDirectoryEndpoint, tenantID)
       token, err = adal.NewServicePrincipalToken(
           *oauthConfig,
           clientID,
           clientSecret,
           activeDirectoryResourceID)
       return token, err
    }
    
    func main() {
       token, _ := CreateToken()
       vnetClient := network.NewVirtualNetworksClientWithBaseURI(baseURI, subscriptionID)
       vnetClient.Authorizer = autorest.NewBearerAuthorizer(token)
       future, _ := vnetClient.CreateOrUpdate(
           context.Background(),
           resourceGroupName,
           "sampleVnetName",
           network.VirtualNetwork{
               Location: to.StringPtr("local"),
               VirtualNetworkPropertiesFormat: &network.VirtualNetworkPropertiesFormat{
                   AddressSpace: &network.AddressSpace{
                       AddressPrefixes: &[]string{"10.0.0.0/8"},
                   },
                   Subnets: &[]network.Subnet{
                       {
                           Name: to.StringPtr("subnetName"),
                           SubnetPropertiesFormat: &network.SubnetPropertiesFormat{
                               AddressPrefix: to.StringPtr("10.0.0.0/16"),
                           },
                       },
                   },
               },
           })
       err := future.WaitForCompletionRef(context.Background(), vnetClient.Client)
       if err != nil {
           fmt.Printf(err.Error())
           return
       }
    }
    

使用 Go SDK 可用于 Azure Stack 的一些代码示例如下:Some of the code samples available for Azure Stack using the Go SDK are:

后续步骤Next steps