Azure Bicep:部署更新计划时如何忽略空值属性
解决Azure Bicep部署更新计划时动态忽略null属性的问题
可以实现。你需要利用Bicep的条件属性和空值判断逻辑,动态决定是否在advancedSchedule中包含monthlyOccurrences属性,避免传入null值导致的报错。
修改后的完整代码
param parSchedules array = [ { name: 'mysched1' monthlyOccurrencesDay: null monthlyOccurrencesOccurence: null DaysOfWeek: 'Wednesday' StartTime: '${parBaseTimeForUpdateSchedules}T19:00:00' tag: { Update: [ 'tag1' ] } } { name: 'mysched2' monthlyOccurrencesDay: 'Wednesday' monthlyOccurrencesOccurence: 1 DaysOfWeek: 'Wednesday' StartTime: '${parBaseTimeForUpdateSchedules}T07:00:00' tag: { Update: [ 'tag2' ] } } ] resource resUpdateschedule 'Microsoft.Automation/automationAccounts/softwareUpdateConfigurations@2019-06-01' = [for schedule in parSchedules: { name: schedule.name parent: resAutomationAccount properties: { scheduleInfo: { advancedSchedule: { // 仅当两个属性都不为null时,才生成monthlyOccurrences monthlyOccurrences: !isNull(schedule.monthlyOccurrencesDay) && !isNull(schedule.monthlyOccurrencesOccurence) ? [ { day: schedule.monthlyOccurrencesDay occurrence: schedule.monthlyOccurrencesOccurence } ] : null weekDays: [ schedule.DaysOfWeek ] } description: '' frequency: 'Week' interval: 1 isEnabled: true startTime: schedule.StartTime timeZone: 'UTC' } updateConfiguration: { duration: 'PT2H' operatingSystem: 'Windows' targets: { azureQueries: [ { locations: [ parLocation ] scope: [ subscription().id ] tagSettings: { tags: schedule.tag } } ] } windows: { includedUpdateClassifications: 'Critical, Security' rebootSetting: 'IfRequired' } } } }]
关键逻辑说明
- 使用Bicep的
!isNull()函数判断参数是否为null,只有当monthlyOccurrencesDay和monthlyOccurrencesOccurence都不为null时,才构建monthlyOccurrences数组。 - 通过条件属性语法(
? :),当条件不满足时将属性值设为null,Bicep会自动忽略对象中值为null的属性,不会将其传入API请求。 - 这样既可以复用同一个
parSchedules数组,又能为不同计划动态生成符合要求的属性结构。
内容的提问来源于stack exchange,提问作者MoonHorse
相关产品推荐
相关产品推荐

