Sentinel : Checking nested tagging values

Hi,
I am writing a policy to check whether a tag for a in Azure is within the allowed values.
Below is my policy:

import "tfplan/v2" as tfplan
import "strings"

allRGs = filter tfplan.resource_changes as _, rc {
	rc.type is "azurerm_resource_group" and
	rc.mode is "managed" and
	(rc.change.actions contains "create" or 
	 	rc.change.actions is ["update"])

}

allowed_appID = ["1234","567"]
violatingappIDs = {}

for allRGs as address, key {
    app_id_value = key.change.after.tags.app-id else null
    
    if app_id_value is null {
        violatingappIDs[address] = key
        print("App-id is null or undefined")
    } else if app_id_value not in allowed_appID {
        violatingappIDs[address] = key
        print("App-id isnt in the allowed list")
    }
}
violations = length(violatingappIDs)
main = rule {
    violations is 0
}

The resource_changes block for the mock is as below:

resource_changes = {
	"azurerm_resource_group.example": {
		"address": "azurerm_resource_group.example",
		"change": {
			"actions": [
				"create",
			],
			"after": {
				"location": "eastus2",
				"name":     "practice-rg",
				"tags": {
					"app-id":  "1234",
					"bill_id": "567",
					"env":     "test",
				},
				"timeouts": null,
			},
			"after_unknown": {
				"id":   true,
				"tags": {},
			},
			"before": null,
		},
		"deposed":        "",
		"index":          null,
		"mode":           "managed",
		"module_address": "",
		"name":           "example",
		"provider_name":  "registry.terraform.io/hashicorp/azurerm",
		"type":           "azurerm_resource_group",
	},
}

Issue is, the condition should pass as the values are as per allowed values, but its failing on the first if condition.
What is strange is, if I used the same code logic to test the bill_id or env tags, policy results are as expected.
Issue is only with app-id tag.
Is the hyphen causing any problems?

Thanks in advance!

@JiJo333 I have taken a look at your code and written the following example which uses the new features in Sentinel 0.17 to simplify the policy logic. You can read more about these features in the following blog post.

I am however conscious that you may not be running the latest version of Sentinel, so in order to fix your code you will need to update the for loop so that you are accessing the element in the map via the key value :

for allRGs as address, key {
    app_id_value = key.change.after.tags["app-id"] else null 
    
    if app_id_value is null {
        violatingappIDs[address] = key
        print("App-id is null or undefined")
    } else if app_id_value not in allowed_appID {
        violatingappIDs[address] = key
        print("App-id isnt in the allowed list")
    }
}

Hope this helps :slight_smile:

1 Like

Thank you @hcrhall , it worked!
Appreciate your help :slight_smile: