azuredevopsazure-bicep

Azure Bicep reference existing resources from different subscriptions using ternary operators inside scope property


In my bicep file I am trying to reference an existing applicationInsights. Problem is that the referenced application insights changes depending on input parameters.

There are 3 possible modules that can be referenced and each of them is in different subscription and resource group.

param prefix string = ''
@allowed([
  'dev'
  'test'
  'prod'
])
@description('Deployment environment type.')
param deploymentEnvironment string

var isProd = deploymentEnvironment == 'prod'
var isTest = deploymentEnvironment == 'dev'
var usingExistingAin = prefix == 'mrax' && (isProd || isTest)
var prodOrTestlabNameTest = isProd ? 'appInsightsName1' : 'appInsightsName2'
var subscriptionIdTest = usingExistingAin ? (isProd && usingExistingAin ? 'subscriptionID1' : 'subscriptionID2') : subscription().id


resource applicationInsightsResource 'Microsoft.Insights/components@2020-02-02' existing = {
    name: usingExistingAin ? prodOrTestlabNameTest : appInsightsName 
    scope: resourceGroup(subscriptionIdTest, rsgNameTest)
}

(The condition isTest is correct even tho it looks like it isnt)

Right now I am getting this error:

The resource namespace 'subscriptions' is invalid. (Code: InvalidResourceNamespace)

What can I do differently to make this work?

Note: I dont want to do this using 2 resources approach (code below) because right now this would cause this error

AuthorizationFailed","message":"The client 'clientId' with object id 'objectId' does not have authorization to perform action 'Microsoft.Insights/components/read' over scope '/subscriptions/subID/resourcegroups/resourceGroupName/providers/Microsoft.Insights/components/appInsightsName' or the scope is invalid. If access was recently granted, please refresh your credentials."

param storageAccountName string
param location string = resourceGroup().location

@allowed([
  'new'
  'existing'
])
param newOrExisting string = 'new'

resource saNew 'Microsoft.Storage/storageAccounts@2023-04-01' = if (newOrExisting == 'new') {
  name: storageAccountName
  location: location
  sku: {
    name: 'Standard_LRS'
  }
  kind: 'StorageV2'
}

resource saExisting 'Microsoft.Storage/storageAccounts@2023-04-01' existing = if (newOrExisting == 'existing') {
  name: storageAccountName
}

output storageAccountId string = ((newOrExisting == 'new') ? saNew.id : saExisting.id)

Solution

  • I am going to mark this as an answer to my question, even tho I feel like this is a deeper issue with bicep validation. What I failed to notice in my depoloyment is that different environments (determined by prefix) use different subscriptions. This means that I did not need to use subscription to set my scope. Code bellow worked scope: resourceGroup(resourceGroupName)