使用 Azure SDK for Go 管理资源组
本文介绍如何使用 Azure SDK for Go 管理库创建和管理资源组。
1.设置 Azure 资源
若要完成本文中的步骤,需要以下 Azure 资源和标识符:
Azure 订阅: 如果没有 Azure 订阅,请在开始前创建 免费帐户。
创建服务主体。 记下服务主体的应用程序(客户端)ID 和机密。 请确保还按照说明将订阅中的参与者角色分配给应用程序。 参与者角色是特权管理员角色,可授予管理订阅中所有资源的权限。
在继续下一节之前,请确保记下订阅 ID (Guid)、租户 ID (Guid) 和服务主体的客户端应用程序/应用程序 ID (Guid) 和机密。
2.设置身份验证
选择符合需求的身份验证方法。 我们为服务器和本地环境中托管的应用提供了多种无凭据身份验证方法。 使用 Azure SDK for Go 文章向 Azure 服务验证 Go 应用将帮助你确定哪种身份验证机制最适合你的方案。
3.创建资源组
创建一个目录,在其中测试和运行示例 Go 代码并将其设为当前目录。
运行 go mod init 在当前目录中创建模块。
go mod init <module_path>
要点:
<module_path>
参数通常是 GitHub 存储库中的一个位置,例如github.com/<your_github_account_name>/<directory>
。- 创建命令行应用作为测试且不会发布应用时,
<module_path>
无需引用实际位置。
使用 和 go get 来下载、构建并安装必要的 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
重要
当前版本的 Azure 资源管理库的包位于
sdk/**/arm**
中。 以前版本的管理库的包位于/services
下。 如果使用的是旧版本,请参阅 Azure SDK for Go 迁移指南。创建名为
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 = "<your_subscription_id>" location = "<your_region>" resourceGroupName = "<your_resource_group_name>" // !! 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) }
要点:
- 从
AZURE_SUBSCRIPTION_ID
环境变量中检索subscriptionId
值。 location
和resourceGroupName
字符串设置为测试值。 如有必要,请将这些值更改为适合你的位置和订阅的内容。
- 从
运行 go mod clean 以根据源代码清理
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.Ptr("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.NewListPager(nil) var resourceGroups []*armresources.ResourceGroup for pager.More() { resp, err := pager.NextPage(ctx) if err != nil { return nil, err } if resp.ResourceGroupListResult.Value != nil { resourceGroups = append(resourceGroups, resp.ResourceGroupListResult.Value...) } } return resourceGroups, nil }
添加代码后,转到下一部分。 将在后面的节中运行代码。
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. 更新主函数
在前面的部分中,已将代码添加到 main.go
以创建、更新和删除资源组。 此外,还添加了代码来列出 Azure 订阅中的所有资源组。 按顺序运行所有这些函数:
在
main.go
中,将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") }
运行代码并观察输出。
go run .
2024/07/31 15:29:06 Resource group /subscriptions/<subscription ID>/resourceGroups/myResourceGroup created 2024/07/31 15:29:07 Resource Group /subscriptions/<subscription ID>/resourceGroups/myResourceGroup updated 2024/07/31 15:29:07 Your Azure subscription has a total of 8 resource groups 2024/07/31 15:30:25 Resource group deleted
注意
删除资源组可能需要几分钟时间。
故障排除
- 请查看已发布到 Stack Overflow 的先前问题
,或使用 和 标签提出新问题。 - 对于遇到的任何错误,请提交 GitHub 问题