咨询:如何用Azure Monitor Alerts实现Key Vault密钥/证书多时段到期告警
Azure Key Vault密钥/证书多间隔到期告警解决方案
核心问题分析
Key Vault仅在密钥/证书到期前30天触发一次SecretNearExpiryEventGridNotification或CertificateNearExpiryEventGridNotification事件,而Azure Monitor日志告警的window_duration上限为1天,导致无法基于单次历史事件重复触发15天、5天等后续间隔的告警。
可行解决方案
方案1:使用Azure Resource Graph查询实现定期状态检查
直接查询Key Vault对象的当前到期状态,无需依赖事件,每天评估一次即可匹配到当前符合告警条件的对象。
查询语句(Resource Graph KQL)
resources | where type in ("Microsoft.KeyVault/vaults/secrets", "Microsoft.KeyVault/vaults/certificates") | where split(id, '/')[8] == "mykeyvault" // 精准过滤目标Key Vault | extend expiryTimestamp = properties.attributes.exp | where expiryTimestamp != "" | extend daysUntilExpiry = datetime_diff('day', unixtime_seconds_todatetime(expiryTimestamp), now()) | where daysUntilExpiry in (30, 15, 5, 3, 1) or daysUntilExpiry < 0 | project VaultName = split(id, '/')[8], ObjectName = name, ObjectType = iff(type contains "secret", "Secret", "Certificate"), DaysUntilExpiration = daysUntilExpiry, ExpirationDateString = format_datetime(unixtime_seconds_todatetime(expiryTimestamp), 'yyyy-MM-dd'), ExpiredStatus = iff(daysUntilExpiry <= 0, "Expired", "Active")
告警配置
evaluation_frequency = "P1D"(每天评估一次)window_duration = "P1D"(无需长窗口,仅需当天查询当前状态)time_aggregation_method = "Count"operator = "GreaterThanOrEqual"threshold = 1
该方案利用Resource Graph直接读取Key Vault对象的属性,每天检查所有对象的剩余到期天数,只要符合目标间隔就会触发告警,完美解决单次事件无法重复触发的问题。
方案2:用Logic Apps/Azure Functions自定义轮询逻辑
通过定时任务定期调用Key Vault API获取密钥/证书的到期信息,自定义判断逻辑并发送告警,灵活性更高。
实现步骤
- 创建Logic App(或Azure Function),添加Recurrence触发器,设置每日执行一次
- 添加Azure Key Vault动作,分别列出目标Vault下的所有密钥和证书
- 添加条件分支,计算每个对象的剩余到期天数,判断是否在
30/15/5/3/1天范围内或已过期 - 符合条件时,调用通知动作(如Office 365邮件、Teams机器人、Webhook等)发送告警
此方案可自定义告警内容、通知渠道,还能针对不同剩余天数设置不同的告警优先级,适合复杂场景需求。
方案3:Event Grid + 存储账户缓存事件(不推荐)
将Key Vault的NearExpiry事件通过Event Grid写入存储账户(如Table Storage),然后在日志告警查询中读取存储的事件并计算当前剩余天数。但需要额外维护存储资源,且逻辑复杂度高于前两种方案,仅作为备选。
内容的提问来源于stack exchange,提问作者0c0
相关产品推荐
相关产品推荐

