以编程方式将 Azure 资源 A 分配给 Azure 资源 B 的贡献者角色
Programmatically assign azure resource A a contributor role to Azure resource B
我想以编程方式为 Azure VM 提供贡献者角色,以便另一个修改其他资源(例如路由表、存储帐户)中的内容。
上面的 msft 文档解释了如何使用 Azure CLI 为启用 MSI 的 VM 提供 Azure 存储帐户的贡献者角色。有人可以使用 Azure Python SDK 而不是 Azure CLI 实现相同的目标吗?不启用MSI是否可以达到同样的目的?
如果您为 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将只能作用于那个角色,仅此而已。
我想以编程方式为 Azure VM 提供贡献者角色,以便另一个修改其他资源(例如路由表、存储帐户)中的内容。
上面的 msft 文档解释了如何使用 Azure CLI 为启用 MSI 的 VM 提供 Azure 存储帐户的贡献者角色。有人可以使用 Azure Python SDK 而不是 Azure CLI 实现相同的目标吗?不启用MSI是否可以达到同样的目的?
如果您为 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将只能作用于那个角色,仅此而已。