Reputation: 1511
My requirement is to set TAGS to resource groups. I have to make sure anyone who creates Resource Groups should provide appropriate tags and values. I want to use Azure Policy to enforce checking that a TAG should not have NULL value. I am using the below Policy definition, but it seems not to be working properly. That is, it is allowing me to create resource groups with TAG having null values. Example: Environment = "" --> This tag should not be allowed and RG group creation should fail.
Policy Definition:
"parameters": {
"tagName": {
"type": "String",
"metadata": {
"displayName": "Tag Name",
"description": "Name of the tag, such as 'environment'"
}
}
},
"policyRule": {
"if": {
"allOf": [
{
"field": "type",
"equals": "Microsoft.Resources/subscriptions/resourceGroups"
},
{
"field": "[concat('tags[', parameters('tagName'), ']')]",
"exists": "true"
},
{
"value": "[concat('tags[', parameters('tagName'), ']')]",
"equals": ""
}
]
},
"then": {
"effect": "deny"
}
}
}
Upvotes: 1
Views: 2261
Reputation: 1262
Option 1:
{
"not": {
"value": "[contains(string(field('tags')), '\"\"')]",
"equals": true
}
}
Option 2:
{
"value": "[indexOf(string(field('tags')), '\"\"')]",
"greaterOrEquals": 0
}
Description:
Option 1:
Use contains
to check wheather an object contains a key or a string contains a substring.
The container
contains nested parameters.
string
converts the specified value to a string. In this case, the specified value is the field = tags
, which are objects, not an array. In this case, the specified value is the field = tags, which are objects
, not an array
.
Example of 2 tags, "tagnumber1" with the value "value1" and "tagnumber2" with an empty value:
"{\"tagnumber1\":\"value1\",\"tagnumber2\":\"\"}"
Note that the empty value is \"\"
- this is our itemToFind
.
Option 2:
Use the indexOf
to return the first position of a value within a string.
The stringToSearch
contains nested parameters.
The stringToFind
is empty.
string
converts the specified value to a string. In this case, the specified value is the field = tags
, which are objects
, not an array
.
Example of 2 tags, "tagnumber1" with the value "value1" and "tagnumber2" with an empty value:
"{\"tagnumber1\":\"value1\",\"tagnumber2\":\"\"}"
Note that the empty value is \"\"
.
Therefore, we must search for that \"\"
as this represents the empty value in the object.
The index is zero-based. If the item is not found, -1 is returned. An integer represents the first index of the item, so by looking at "greaterOrEquals": 0
it will only return that is the item is found - meaning a tag value is empty.
Links:
Upvotes: 0
Reputation: 204
This policy only enforces the tagName not the tagValue. To enforce both follow this built in: Require a tag and its value on resource groups
Upvotes: 1