Azure Policy创建CreatedDate标签后更新资源时被修改问题求助
解决Azure Policy中CreatedDate标签被更新覆盖的问题
问题根源
你的原Policy存在两个核心缺陷:
- 依赖
utcNow()生成时间,每次资源变更评估时都会返回当前时间,导致资源更新时若标签被重新添加,会覆盖为当前时间而非资源真实创建时间。 - 未添加标签保护逻辑,无法阻止更新操作中对CreatedDate标签的修改或覆盖。
修正方案
我们需要实现两条互补的规则:自动添加基于资源真实创建时间的CreatedDate标签,以及禁止后续修改该标签的值。你可以创建一个Azure Policy计划(Initiative)包含以下两个独立Policy:
1. 自动添加CreatedDate标签Policy
{ "properties": { "displayName": "Append CreatedDate Tag with Resource Creation Time", "description": "Automatically adds a CreatedDate tag using the resource's actual creation timestamp.", "mode": "Indexed", "policyRule": { "if": { "field": "tags['CreatedDate']", "exists": false }, "then": { "effect": "append", "details": [ { "field": "tags['CreatedDate']", "value": "[concat(substring(field('creationTimestamp'),5,2), '/', substring(field('creationTimestamp'),8,2), '/', substring(field('creationTimestamp'),0,4), '-', substring(field('creationTimestamp'),11,8))]" } ] } } } }
2. 禁止修改CreatedDate标签Policy
{ "properties": { "displayName": "Prevent Modification of CreatedDate Tag", "description": "Denies any attempt to modify the CreatedDate tag, which must match the resource's creation timestamp.", "mode": "Indexed", "policyRule": { "if": { "allOf": [ { "field": "tags['CreatedDate']", "exists": true }, { "not": { "field": "tags['CreatedDate']", "equals": "[concat(substring(field('creationTimestamp'),5,2), '/', substring(field('creationTimestamp'),8,2), '/', substring(field('creationTimestamp'),0,4), '-', substring(field('creationTimestamp'),11,8))]" } } ] }, "then": { "effect": "deny", "details": { "message": "CreatedDate tag is based on the resource's creation timestamp and cannot be modified." } } } } }
核心改进说明
- 使用
creationTimestamp字段:替换原Policy中的utcNow(),直接调用资源自身的创建时间属性,确保CreatedDate标签值始终为资源的真实创建时间,不会随后续操作时间变化。 - 标签保护机制:通过Deny规则拦截任何修改CreatedDate标签为非真实创建时间的操作,彻底避免标签被篡改。
内容的提问来源于stack exchange,提问作者Prawin
相关产品推荐
相关产品推荐

