在 Azure Stack Hub 中搭配使用 API 版本設定檔與 GOUse API version profiles with Go in Azure Stack Hub

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 Hub 和區域 Azure 資料中心的相容性。Compatibility for your app with Azure Stack Hub 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 Hub API 設定檔版本為 2019-03-01,其適用於 Azure Stack Hub 1904 版或更新版本。The latest Azure Stack Hub API profile version is 2019-03-01 for Azure Stack Hub 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 命令,以安裝 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 Resource Manager 端點。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. 您可以在 安裝 一節中找到安裝 bash 命令。You can find the install bash commands in the Install section.

如何在 Azure Stack Hub 上使用 Go SDK 設定檔How to use Go SDK profiles on Azure Stack Hub

若要在 Azure Stack Hub 上執行 Go 程式碼的範例,請遵循以下步驟:To run a sample of Go code on Azure Stack Hub, 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. 從 Resource Manager 端點取得中繼資料資訊。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.

    注意

    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.windows.net/",  
      "portal Endpoint": "https://portal.local.azurestack.external/",
      "authentication": {
        "loginEndpoint": "https://login.windows.net/",
        "audiences": ["https://management.<yourtenant>.onmicrosoft.com/3cc5febd-e4b7-4a85-a2ed-1d730e2f5928"]
      }
    }
    
  3. 如果無法使用,請建立訂用帳戶,並儲存訂用帳戶識別碼供後續使用。If not available, create a subscription and save the subscription ID to be used later. 如需建立訂用帳戶的相關資訊,請參閱在 Azure Stack Hub 中建立供應項目的訂用帳戶For info on creating a subscription, see Create subscriptions to offers in Azure Stack Hub.

  4. 建立會使用用戶端密碼且具有 訂用帳戶 範圍和 擁有者 角色的服務主體。Create a service principal that uses a client secret, with Subscription scope and Owner role. 儲存服務主體的識別碼和密碼。Save the service principal ID and secret. 如需為 Azure Stack Hub 建立服務主體的相關資訊,請參閱使用應用程式身分識別來存取資源For information about creating a service principal for Azure Stack Hub, see Use an app identity to access resources. 您的 Azure Stack Hub 環境現在已設定完成。Your Azure Stack Hub environment is now set up.

  5. 使用程式碼從 GO SDK 設定檔匯入服務模組。Import a service module from the Go SDK profile in your code. Azure Stack Hub 設定檔目前的版本是 2019-03-01The current version of Azure Stack Hub 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. 在您的函式中,使用 新增 用戶端函式呼叫建立並驗證用戶端。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 Hub 上建立虛擬網路的完整範例,請參閱範例For a complete example of creating a virtual network on Azure Stack Hub by using the Go SDK profile, see the example.

驗證Authentication

若要使用 Go SDK 從 Azure Active Directory 取得 授權者 屬性,請安裝 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.

[授權者] 必須設為資源用戶端的授權者。The Authorizer must be set as the authorizer for the resource client. 使用用戶端認證在 Azure Stack Hub 上取得授權者權杖的方法有很多種:There are different ways to get authorizer tokens on Azure Stack Hub 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. 請務必要擷取服務主體應用程式識別碼和祕密。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 Hub 租用戶識別碼。Set the <tenantID> value to your Azure Stack Hub 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 中繼資料中的「對象」清單值之一。Set <activeDirectoryResourceID> to one of the values in the "audience" list from the ResourceManagerUrl metadata retrieved in the previous section of this article. <clientID> 設定為在本文上一節建立服務主體時所儲存的服務主體應用程式識別碼。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 Hub 上建立虛擬網路的 GO 程式碼範例。This example shows a sample of Go code that creates a virtual network on Azure Stack Hub. 如需 Go SDK 的完整範例,請參閱 Azure Go SDK 範例存放庫For complete examples of the Go SDK, see the Azure Go SDK samples repository. Azure Stack Hub 範例可從該存放庫的服務資料夾內的 hybrid 路徑下取得。Azure Stack Hub samples are available under the hybrid path inside service folders of the repository.

注意

若要執行此範例中的程式碼,請確認使用的訂用帳戶具有列示為 已註冊網路 資源提供者。To run the code in this example, verify that the subscription used has the Network resource provider listed as Registered. 若要確認,請在 Azure Stack Hub 入口網站中找出訂用帳戶,然後選取 [資源提供者]。To verify, look for the subscription in the Azure Stack Hub portal, and select Resource providers.

  1. 使用程式碼匯入所需的套件。Import the required packages in your code. 使用 Azure Stack Hub 上最新的可用設定檔來匯入網路模組:Use the latest available profile on Azure Stack Hub 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 Hub 適用的程式碼範例包括:Some of the code samples available for Azure Stack Hub using the Go SDK are:

後續步驟Next steps