Azure bicep set role assignment on storage account in a different subscription/resource group

56 Views Asked by At

I have the following bicep file

param accountName string
param roleId string
param principalId string

resource account 'Microsoft.Storage/storageAccounts@2022-09-01' existing = {
  name: accountName
}

resource roleDefinition 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = {
  scope: account
  name: roleId
}

resource roleAssignment 'Microsoft.Authorization/roleAssignments@2023-04-15' = {
  scope: account
  name: guid(account.id, principalId, roleDefinition.id)
  properties: {
    roleDefinitionId: roleDefinition.id
    principalId: principalId
    principalType: 'ServicePrincipal'
  }
}

When executing this the error is that it cannot find the account {accountName} in the resource-group that it's running from, however I am trying to set the roleAssignment on a storageAccount that already exists in another subscription/resource group. Since storage account names are unique I would think this should work?

1

There are 1 best solutions below

0
wenbo On

You should use Bicep Modules here. combine modules + scope two keywords help you to implement nested deployment accross resources groups.

For you circumstance, I have coded a sample and tested.

main.bicep

param roleId string
param principalId string

param storageAccountRgName string
param storageAccountName string

module asModule 'roleAssign.bicep' = {
  scope: resourceGroup(storageAccountRgName)
  name: 'deploymentRoleAssign'
  params: {
    accountName: storageAccountName
    principalId: principalId
    roleId: roleId
  }
}

roleAssign.bicep

param accountName string
param roleId string
param principalId string

resource account 'Microsoft.Storage/storageAccounts@2022-09-01' existing = {
  name: accountName
}

resource roleDefinition 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = {
  scope: account
  name: roleId
}

resource roleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  scope: account
  name: guid(account.id, principalId, roleDefinition.id)
  properties: {
    roleDefinitionId: roleDefinition.id
    principalId: principalId
    principalType: 'ServicePrincipal'
  }
}

deploy.ps1

$rgName = "wb-deployment-rg"
$location = "eastus"

$storageAccountRgName = "wb-sa-rg"
$storageAccountName = "wbsaxxx"

$roleId = 'xxxxx'
$principalId = 'xxxx'

New-AzResourceGroup -Name $rgName -Location $location -Force

$templateFile = "main.bicep"

$params = @{
  roleId = $roleId
  principalId = $principalId
  storageAccountRgName = $storageAccountRgName
  storageAccountName = $storageAccountName
}

New-AzResourceGroupDeployment `
  -Name 'wbtest' `
  -ResourceGroupName $rgName `
  -TemplateFile $templateFile `
  -TemplateParameterObject $params