【问题标题】:Programmatically assign azure resource A a contributor role to Azure resource B以编程方式将 azure 资源 A 分配给 Azure 资源 B 的参与者角色
【发布时间】:2018-07-18 22:29:11
【问题描述】:

我想以编程方式为 Azure VM 赋予贡献者角色,以便另一个修改其他资源(如路由表、存储帐户)中的内容。

https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/howto-assign-access-cli

上面的 msft 文档解释了如何使用 Azure CLI 为启用 MSI 的 VM 赋予 Azure 存储帐户的贡献者角色。有人可以使用 Azure Python SDK 而不是 Azure CLI 来实现相同的目标吗?不开启微星也能达到同样的目的吗?

【问题讨论】:

    标签: azure azure-sdk azure-sdk-python


    【解决方案1】:

    如果您为 VM 创建服务主体,并以某种方式将凭据推送到 VM,则可以避免 MSI。但是创建 MSI 是为了避免这种情况,因为在 VM 中推送凭据并不是一个简单的过程,也不安全。

    要将角色分配给 Active Directory ID(无论使用 MSI 还是专用 ServicePrincipal),您可以使用此代码分配角色(使用 azure-mgmt-authorization 包)。

    https://github.com/Azure-Samples/compute-python-msi-vm#role-assignement-to-the-msi-credentials

    # Get "Contributor" built-in role as a RoleDefinition object
    role_name = 'Contributor'
    roles = list(authorization_client.role_definitions.list(
        resource_group.id,
        filter="roleName eq '{}'".format(role_name)
    ))
    assert len(roles) == 1
    contributor_role = roles[0]
    
    # Add RG scope to the AD id
    # This assumes "sp_id" is either a MSI id or a SP id
    role_assignment = authorization_client.role_assignments.create(
        resource_group.id,
        uuid.uuid4(), # Role assignment random name
        {
            'role_definition_id': contributor_role.id,
            'principal_id': sp_id
        }
    )
    

    那么这个 AD id 将只能作用于该角色,仅此而已。

    【讨论】:

    • 感谢劳伦特!如果您想将范围限制为特定资源而不是 RG,我想您仍然可以通过在上面的示例中将“resource_group.id”替换为“resource.id”来做到这一点。
    • 您如何获得我们正在使用的“authorization_client”对象?
    猜你喜欢
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 2019-11-13
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    相关资源
    最近更新 更多