使用 Azure SDK for Go 管理资源组
本文介绍了如何使用 Azure SDK for Go 管理库创建资源组。
1.配置环境
重要
当前版本的 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 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
创建名为
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 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.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. 创建 main 函数
本文介绍了如何创建、更新和删除资源组, 还介绍了如何列出 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 的问题,或使用
Azure
和Go
标记提出新问题。 - 对于遇到的任何错误,请提交 GitHub 问题
后续步骤
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈