使用 Azure SDK for Go 管理資源群組
在本文中,您將瞭解如何使用 Azure SDK for Go 管理連結庫建立資源群組。
1.設定環境
Azure 訂用帳戶:如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶。
建立服務主體。 請注意服務主體的應用程式 (用戶端) 識別碼和秘密。 請確定您也遵循指示,將參與者角色指派給應用程式。
重要
目前 Azure 資源管理連結庫版本的套件位於 sdk/**/arm**
。 舊版管理連結庫的套件位於 底下 /services
。 如果您使用舊版,請參閱 此 Azure SDK for Go 移轉指南。
2.向 Azure 進行驗證
使用您的 Azure 驗證資訊,設定適當的環境變數,讓您的程式代碼可以向 Azure 進行驗證。
新增下列環境變數,以編輯
~/.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>"
若要執行
~/.bashrc
腳本,請執行source ~/.bashrc
(或其縮寫的對等用法. ~/.bashrc
)。. ~/.bashrc
設定環境變數之後,您可以確認其值,如下所示:
printenv | grep ^AZURE*
3.建立資源群組
建立目錄,在其中測試並執行範例 Go 程式代碼,並將其設為目前目錄。
執行 go mod init 以在目前目錄中建立模組。
go mod init <module_path>
重點︰
- 參數
<module_path>
通常是 GitHub 存放庫中的位置,例如github.com/<your_github_account_name>/<directory>
。 - 當您建立命令行應用程式作為測試,且不會發佈應用程式時,
<module_path>
就不需要存在。
- 參數
執行 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
建立名為
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
取。 location
和resourceGroupName
字串已得到測試值。 如有必要,請將這些值變更為適合您環境的值。
- 此值
執行 go mod tidy ,以根據您的原始程式碼清除檔案中的
go.mod
相依性。go mod tidy
執行
go run
以建置並執行應用程式。go run .
4.確認結果
瀏覽至 Azure 入口網站。
登入並選取您的 Azure 訂用帳戶。
在左側功能表中,選取 [資源群組]。
新的資源群組將會列在您的 Azure 訂用帳戶的資源群組中。
5.更新資源群組
返回您的
main.go
檔案。在函式正上方
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 訂用帳戶的資源群組
返回您的
main.go
檔案。在函式正上方
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.刪除資源群組
返回您的
main.go
檔案。在函式正上方
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")
}
疑難排解
- 檢查先前張貼到 Stack Overflow 的問題,或使用和
Go
標記詢問新的問題Azure
。 - 針對您遇到的任何錯誤,請提出 GitHub 問題
下一步
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應