共用方式為


使用 Azure SDK for Go 管理資源群組

在本文中,您將瞭解如何使用 Azure SDK for Go 管理連結庫建立資源群組。

1.設定環境

重要

目前 Azure 資源管理連結庫版本的套件位於 sdk/**/arm**。 舊版管理連結庫的套件位於 底下 /services。 如果您使用舊版,請參閱 此 Azure SDK for Go 移轉指南

2.向 Azure 進行驗證

使用您的 Azure 驗證資訊,設定適當的環境變數,讓您的程式代碼可以向 Azure 進行驗證。

  1. 新增下列環境變數,以編輯 ~/.bashrc 檔案。 將佔位元取代為上一節的適當值。

    export AZURE_SUBSCRIPTION_ID="<azure_subscription_id>"
    export AZURE_TENANT_ID="<active_directory_tenant_id>"
    export AZURE_CLIENT_ID="<service_principal_appid>"
    export AZURE_CLIENT_SECRET="<service_principal_password>"
    
  2. 若要執行 ~/.bashrc 腳本,請執行 source ~/.bashrc (或其縮寫的對等用法 . ~/.bashrc)。

    . ~/.bashrc
    
  3. 設定環境變數之後,您可以確認其值,如下所示:

    printenv | grep ^AZURE*
    

3.建立資源群組

  1. 建立目錄,在其中測試並執行範例 Go 程式代碼,並將其設為目前目錄。

  2. 執行 go mod init 以在目前目錄中建立模組。

    go mod init <module_path>
    

    重點︰

    • 參數 <module_path> 通常是 GitHub 存放庫中的位置,例如 github.com/<your_github_account_name>/<directory>
    • 當您建立命令行應用程式作為測試,且不會發佈應用程式時, <module_path> 就不需要存在。
  3. 執行 go 以 下載、建置及安裝必要的 Azure SDK for Go 模組。

    go get github.com/Azure/azure-sdk-for-go/sdk/azcore
    go get github.com/Azure/azure-sdk-for-go/sdk/azcore/to
    go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
    go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources
    
  4. 建立名為 main.go 的檔案,並插入下列程序代碼。 程序代碼的每個區段都會加上批注,以說明其用途。

    package main
    
    // Import key modules.
    import (
    	"context"
    	"log"
    	"os"
    
    	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
    	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
    	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    	"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources"
    )
    
    // Define key global variables.
    var (
    	subscriptionId    = os.Getenv("AZURE_SUBSCRIPTION_ID")
    	location          = "eastus"
    	resourceGroupName = "myResourceGroup" // !! IMPORTANT: Change this to a unique name in your subscription.
    	ctx               = context.Background()
    )
    
    // Define the function to create a resource group.
    func createResourceGroup(subscriptionId string, credential azcore.TokenCredential) (armresources.ResourceGroupsClientCreateOrUpdateResponse, error) {
    	rgClient, _ := armresources.NewResourceGroupsClient(subscriptionId, credential, nil)
    
    	param := armresources.ResourceGroup{
    		Location: to.Ptr(location),
    	}
    
    	return rgClient.CreateOrUpdate(ctx, resourceGroupName, param, nil)
    }
    
    // Define the standard 'main' function for an app that is called from the command line.
    func main() {
    
    	// Create a credentials object.
    	cred, err := azidentity.NewDefaultAzureCredential(nil)
    	if err != nil {
    		log.Fatalf("Authentication failure: %+v", err)
    	}
    
    	// Call your function to create an Azure resource group.
    	resourceGroup, err := createResourceGroup(subscriptionId, cred)
    	if err != nil {
    		log.Fatalf("Creation of resource group failed: %+v", err)
    	}
    
    	// Print the name of the new resource group.
    	log.Printf("Resource group %s created", *resourceGroup.ResourceGroup.ID)
    }
    

    重點︰

    • 此值 subscriptionId 會從環境變數擷 AZURE_SUBSCRIPTION_ID 取。
    • locationresourceGroupName 字串已得到測試值。 如有必要,請將這些值變更為適合您環境的值。
  5. 執行 go mod tidy ,以根據您的原始程式碼清除檔案中的 go.mod 相依性。

    go mod tidy
    
  6. 執行 go run 以建置並執行應用程式。

    go run .
    

4.確認結果

  1. 瀏覽至 Azure 入口網站

  2. 登入並選取您的 Azure 訂用帳戶。

  3. 在左側功能表中,選取 [資源群組]

  4. 新的資源群組將會列在您的 Azure 訂用帳戶的資源群組中。

5.更新資源群組

  1. 返回您的 main.go 檔案。

  2. 在函式正上方 main 插入下列程序代碼。

    // Update the resource group by adding a tag to it.
    func updateResourceGroup(subscriptionId string, credential azcore.TokenCredential) (armresources.ResourceGroupsClientUpdateResponse, error) {
        rgClient := armresources.NewResourceGroupsClient(subscriptionId, credential, nil)
    
        update := armresources.ResourceGroupPatchable{
            Tags: map[string]*string{
                "new": to.StringPtr("tag"),
            },
        }
        return rgClient.Update(ctx, resourceGroupName, update, nil)
    }
    

6.列出 Azure 訂用帳戶的資源群組

  1. 返回您的 main.go 檔案。

  2. 在函式正上方 main 插入下列程序代碼。

    // List all the resource groups of an Azure subscription.
    func listResourceGroups(subscriptionId string, credential azcore.TokenCredential) ([]*armresources.ResourceGroup, error) {
        rgClient := armresources.NewResourceGroupsClient(subscriptionId, credential, nil)
    
        pager := rgClient.List(nil)
    
        var resourceGroups []*armresources.ResourceGroup
        for pager.NextPage(ctx) {
            resp := pager.PageResponse()
            if resp.ResourceGroupListResult.Value != nil {
                resourceGroups = append(resourceGroups, resp.ResourceGroupListResult.Value...)
            }
        }
        return resourceGroups, pager.Err()
    }
    

7.刪除資源群組

  1. 返回您的 main.go 檔案。

  2. 在函式正上方 main 插入下列程序代碼。

    // Delete a resource group.
    func deleteResourceGroup(subscriptionId string, credential azcore.TokenCredential) error {
        rgClient := armresources.NewResourceGroupsClient(subscriptionId, credential, nil)
    
        poller, err := rgClient.BeginDelete(ctx, resourceGroupName, nil)
        if err != nil {
            return err
        }
        if _, err := poller.PollUntilDone(ctx, nil); err != nil {
            return err
        }
        return nil
    }
    

8.更新主要函式

在本文中,您已瞭解如何建立、更新和刪除資源群組。 您也已瞭解如何列出 Azure 訂用帳戶的所有資源群組。 若要循序執行所有這些函式,請使用下列程式代碼取代 函 main 式:

func main() {

    // Create a credentials object.
    cred, err := azidentity.NewDefaultAzureCredential(nil)
    if err != nil {
        log.Fatalf("Authentication failure: %+v", err)
    }

    // Call your function to create an Azure resource group.
    resourceGroup, err := createResourceGroup(subscriptionId, cred)
    if err != nil {
        log.Fatalf("Creation of resource group failed: %+v", err)
    }
    // Print the name of the new resource group.
    log.Printf("Resource group %s created", *resourceGroup.ResourceGroup.ID)

    // Call your function to add a tag to your new resource group.
    updatedRG, err := updateResourceGroup(subscriptionId, cred)
    if err != nil {
        log.Fatalf("Update of resource group failed: %+v", err)
    }
    log.Printf("Resource Group %s updated", *updatedRG.ResourceGroup.ID)

    // Call your function to list all the resource groups.
    rgList, err := listResourceGroups(subscriptionId, cred)
    if err != nil {
        log.Fatalf("Listing of resource groups failed: %+v", err)
    }
    log.Printf("Your Azure subscription has a total of %d resource groups", len(rgList))

    // Call your function to delete the resource group you created.
    if err := deleteResourceGroup(subscriptionId, cred); err != nil {
        log.Fatalf("Deletion of resource group failed: %+v", err)
    }
    log.Printf("Resource group deleted")
}

疑難排解

下一步