如何使用 Azure Go SDK 处理角色分配?

问题描述 投票:0回答:1

创建这个问题,以便我在面对这个问题并找到解决方案后可以自己回答。

如何使用 Azure Go SDK 来处理角色分配?例如,我如何使用它来列出特定主体拥有的角色分配?

在查阅其文档后,我能够弄清楚如何为各种 Azure 服务创建客户端,但我无法弄清楚如何特别处理角色定义。在检查 Stack Overflow 是否已解决此问题后,我发现了一些带有答案的问题,但它们是针对其他编程语言(例如 .NET Core)的。

azure go sdk azure-rbac
1个回答
0
投票

SDK分为多个Go模块。 SDK 本身的文档从参考页面开始,其中列出了模块,但没有解释如何开始。

在另一个 Azure 文档页面上,有关于使用与要与 SDK 一起使用的服务主体关联的凭据的环境变量来验证 Go SDK 的说明 -

AZURE_TENANT_ID
AZURE_CLIENT_ID
AZURE_CLIENT_SECRET
。如果您还没有可与 SDK 一起使用的服务主体,则需要 使用 Microsoft Entra ID 创建一个服务主体(以前称为 Azure AD)。

设置这些环境变量后,您可以使用

NewDefaultAzureCredential
 包中的 
azidentity
创建可与 SDK 中的任何客户端一起使用的凭证变量。

您不能直接使用此凭据来创建用于处理角色定义的客户端。相反,您必须首先创建一个客户端工厂。必须使用正确的 Go 包创建客户端工厂,其中每个 Azure API 都有一个 Go 包。对于处理角色分配,包是

armauthorization

然后,您可以使用客户端工厂创建

*RoleAssignmentsClient
并使用客户端。您还需要使用您正在使用的范围的订阅的订阅 ID。

完整的代码示例(假设设置了上述环境变量):

package main

import (
    "context"
    "fmt"

    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/authorization/armauthorization/v2"
)

func main() {
    subscriptionID := "<subscription-id>"

    cred, _ := azidentity.NewDefaultAzureCredential(nil)

    // Initialize a client factory using the credential.
    clientFactory, _ := armauthorization.NewClientFactory(subscriptionID, cred, nil)

    // Get the client to be used from the factory.
    roleAssignmentsClient := clientFactory.NewRoleAssignmentsClient()

    // To demonstrate that the client was created properly, test the client by
    // using it to get the first page of a list of all of the role assignments
    // within the subscription scope.
    pager := roleAssignmentsClient.NewListForScopePager(fmt.Sprintf("/subscriptions/%s", subscriptionID), nil)
    page, _ := pager.NextPage(context.TODO())

    fmt.Printf("Role assignments: %v\n", page.Value)
}

输出示例:

Role assignments: [0xc0002b8080 0xc0002b80a0]

请注意,当它们从 API 返回时,它们是指针,并且我的示例中有两个:

  • 我创建 Azure 帐户时自动创建的用户
  • 我通过在 Microsoft Entra ID 中创建应用程序手动创建的服务主体,我用它来验证此示例
© www.soinside.com 2019 - 2024. All rights reserved.