如何在Bicep文件中根据条件创建嵌套资源?Service Bus规则资源条件创建报错解决方案问询
ruleName Is Empty You’re spot-on about the root cause: when you add the if (!empty(obj.ruleName)) condition to the rules loop, the index i now refers to the filtered list of subscriptions (only those with non-empty ruleName values), but the subscriptions resource array is created from the full list of subscriptions in your parameter. This mismatch causes the parent resource reference to point to the wrong subscription, triggering the ARM template validation error about incorrect segment lengths.
Here’s the correct way to implement your requirement:
Step 1: Keep Subscriptions Creation as-Is
First, your existing subscriptions loop works perfectly—we still want to create every subscription defined in the topic parameter:
resource subscriptions 'Microsoft.ServiceBus/namespaces/topics/subscriptions@2021-11-01' = [for obj in topic.subscriptions: { parent: topicResource name: obj.name }]
Step 2: Conditionally Create Rules with Accurate Parent References
Instead of relying on the filtered loop’s index, we’ll reference the correct subscription resource by finding its position in the original topic.subscriptions array. This ensures we always link the rule to its matching subscription, even when some rules are skipped:
resource rules 'Microsoft.ServiceBus/namespaces/topics/subscriptions/rules@2021-11-01' = [for obj in topic.subscriptions: if (!empty(obj.ruleName)) { // Get the index of the current subscription in the original unfiltered array parent: subscriptions[topic.subscriptions.findIndex(s => s.name == obj.name)] name: obj.ruleName properties: { filterType: 'CorrelationFilter' correlationFilter: { label: obj.ruleName } } }]
Alternative: Use a Filtered Variable for Cleaner Code
If you prefer more readable code, you can first create a variable that only includes subscriptions with non-empty ruleName values, then loop over that variable while still referencing the correct parent subscription:
// Filter to only subscriptions that need a rule var subscriptionsWithRules = [for sub in topic.subscriptions: if (!empty(sub.ruleName)) sub] resource rules 'Microsoft.ServiceBus/namespaces/topics/subscriptions/rules@2021-11-01' = [for sub in subscriptionsWithRules: { parent: subscriptions[topic.subscriptions.findIndex(s => s.name == sub.name)] name: sub.ruleName properties: { filterType: 'CorrelationFilter' correlationFilter: { label: sub.ruleName } } }]
Why This Works
By using topic.subscriptions.findIndex(s => s.name == obj.name), we always get the index of the subscription in the original, unfiltered array that the subscriptions resource array is built from. This guarantees the parent resource reference is always accurate, even when some rules are skipped entirely.
内容的提问来源于stack exchange,提问作者Martijn

