terraform version
Policy Contributor role to assign Azure Policy
Write an OPA Rego policy that requires all Azure resources to have mandatory tags (environment, owner, cost-center, managed-by).
1 package azure.tags 2 3 import future.keywords.in 4 5 # Required tags for all Azure resources 6 required_tags := {"environment", "owner", "cost-center", "managed-by"} 7 8 # Actions that trigger tag checks 9 create_or_update := {"create", "update"} 10 11 # Deny resources missing required tags 12 deny[msg] { 13 resource := input.resource_changes[_] 14 resource.change.actions[_] in create_or_update 15 16 tags := object.get(resource.change.after, "tags", {}) 17 missing := required_tags - {tag | tags[tag]} 18 count(missing) > 0 19 20 msg := sprintf( 21 "Resource '%s' (%s) is missing required tags: %v. Add: environment, owner, cost-center, managed-by.", 22 [resource.address, resource.type, missing] 23 ) 24 } 25 26 # Validate owner tag is a valid email 27 deny[msg] { 28 resource := input.resource_changes[_] 29 resource.change.actions[_] in create_or_update 30 31 tags := object.get(resource.change.after, "tags", {}) 32 owner := object.get(tags, "owner", "") 33 owner != "" 34 not regex.match("^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$", owner) 35 36 msg := sprintf( 37 "Resource '%s' has invalid owner tag '%s'. Owner must be a valid email address.", 38 [resource.address, owner] 39 ) 40 }
Rego policy that denies resources missing required tags; opa eval passes
Sign in to share your feedback and join the discussion.