如何使用 Bicep 将服务总线实体上的正确角色分配给 Azure 函数托管标识?

Sam*_*tte 3 azure azureservicebus azure-functions azure-managed-identity azure-bicep

我有一个 Azure Functions 项目,其中有一个使用服务总线绑定的函数(用于侦听订阅并发送到主题)。

Azure 函数部署在托管标识下运行。由于我们希望使用 Azure Bicep 自动部署所有内容,因此我希望在 Azure Bicep 文件中自动为该托管标识的服务总线命名空间(或实体)提供正确的角色分配。

但我似乎不知道该怎么做。有人能够指示正确的二头肌片段来创建角色分配Azure Service Bus Data Receiver以及Azure Service Bus Data Sender在服务总线实体上针对特定托管身份吗?

(更好的是:我知道我对二头肌相当陌生,我怎样才能自己找到答案)

此致

Tho*_*mas 5

可以在此处找到使用 Bicep 创建 RBAC 的文档。可以在此处
找到 Azure 内置角色

因此,对于 ServiceBus 和托管身份,您可以创建一个如下所示的模块

// servicebus-role-assignment.bicep

param serviceBusName string
param principalId string

@allowed([
  '4f6d3b9b-027b-4f4c-9142-0e5a2a2247e0' // Azure Service Bus Data Receiver
  '69a216fc-b8fb-44d8-bc22-1f3c2cd27a39' // Azure Service Bus Data Sender
])
param roleId string


// Get a reference to servicebus namespace
resource servicebus 'Microsoft.ServiceBus/namespaces@2022-01-01-preview' existing = {
  name: serviceBusName
}

// Grant permissions to the principalID to specific role to servicebus
resource roleAssignment 'Microsoft.Authorization/roleAssignments@2020-04-01-preview' = {
  name: guid(servicebus.id, roleId, principalId)
  scope: servicebus
  properties: {
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', roleId)
    principalId: principalId
    principalType: 'ServicePrincipal'
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用用户分配的身份,则可以在创建身份后调用此模块:

param location string = resourceGroup().location
param identityName string
param serviceBusName string

// Create the identity
resource identity 'Microsoft.ManagedIdentity/userAssignedIdentities@2022-01-31-preview' = {
  name: identityName
  location:location
}

// Do the role assignment
module serviceBusRoleAssignment 'servicebus-role-assignment.bicep' = {
  name: 'servicebus-role-assignment'
  params: {
    serviceBusName: serviceBusName
    roleId: '4f6d3b9b-027b-4f4c-9142-0e5a2a2247e0' // Azure Service Bus Data Receiver    
    principalId: identity.properties.principalId
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用系统分配的身份,则需要首先创建函数应用程序:

param location string = resourceGroup().location
param functionAppName string
param serviceBusName string
...

// Create the function app
resource functionApp 'Microsoft.Web/sites@2022-03-01' = {
  name: functionAppName
  identity: {
    type: 'SystemAssigned'
  }
  ...
}

// Do the role assignment
module serviceBusRoleAssignment 'servicebus-role-assignment.bicep' = {
  name: 'servicebus-role-assignment'
  params: {
    serviceBusName: serviceBusName
    roleId: '4f6d3b9b-027b-4f4c-9142-0e5a2a2247e0' // Azure Service Bus Data Receiver    
    principalId: functionApp.identity.principalId
  }
}
Run Code Online (Sandbox Code Playgroud)