【Azure 环境】使用Azure bicep对多个ServicePrinciple 进行role assignment分配

问题描述

使用Azure bicep对多个ServicePrinciple 进行role assignment分配

 

步骤如下

第一步:定义传参,里面包括object ID和role的一个map如:

param servicePrincipals array = [
  {
    objectId: 'service-principal-object-id-1'
    roles: [
      'Contributor'
      'Reader'
    ]
  }
  {
    objectId: 'service-principal-object-id-2'
    roles: [
      'Contributor'
    ]
  }
]

 

第二步:把以上map转化为数组

Azure bicep现在不支持多层循环嵌套,因此只能使用一个数组

var assignments = [

  for sp in servicePrincipals: map(sp.roles, role => {

    objectId: sp.objectId

    role: role

  })

]

var assignmentArray = flatten(assignments)

 

第三步:使用循环进行roleAssignment的创建

resource roleAssignments 'Microsoft.Authorization/roleAssignments@2020-10-01-preview' = [
  for assignment in assignmentArray: {
    name: guid(storageAccount.id, assignment.objectId, assignment.role)
    scope: storageAccount
    properties: {
      roleDefinitionId: subscriptionResourceId(
        'Microsoft.Authorization/roleDefinitions',
        roleDefinitionMap[assignment.role]
      )
      principalId: assignment.objectId
      principalType: 'ServicePrincipal'
    }
  }
]

 

代码片段截图:

 

参考资料

  1. https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/existing-resource 
  2. https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/outputs?tabs=azure-powershell#get-output-values 

 

[END]

 

posted @ 2024-11-26 22:16  路边两盏灯  阅读(10)  评论(0编辑  收藏  举报