How to check a variable in a Hashicorp Sentinel policy

This blog is a minimalist example of a Hashicorp Sentinel policy to check the content of a string variable. I’ve struggled a bit to write my first policy and had difficulties understanding the elements required. Nico Vibert’s blog has helped a lot.

Hashicorps sentinel policy are policies as code that will allow you to control what users are pushing through Terraform Enterprise/Cloud. This is a paid feature, Open Policy Agent is the open source alternative.

The use case in this example is to check a variable in a Terraform script that we don’t want the user to be able to modify. Let’s say for instance that a variable named prefix is used to prefix all Terraform resources of an environment and we don’t want the user to be able to change it. The aim of this policy is to ensure that there is a variable “prefix” with the value “ABC” in the Terraform script. This is the equivalent of enforcing a variable to be in read only mode.

As this is my first blog on Hashicorp Sentinel policy, I created a serie of 3 posts to also explain how I tested and pushed to production the policy :

THE POLICY

import "tfplan/v2" as tfplan

#Get variable prefix
variablesPrefix = filter tfplan.variables as _, v {
    v.name is "prefix" and v.value is "ABC"
}

#This policy will be true if the variable "prefix" exist and its value is ABC
main = rule { length(variablesPrefix) is not 0 }
  • The import tfplan/v2 allows to get access to all the information of a plan.

  • Then the policy uses the Quantifier Expression filter to get all variables named prefix with a value equal to ABC.
    Below you have the output of the variablesPrefix after the filer has been applied and found the prefix variable with the value ABC :

Print messages:

{"prefix": {"name": "prefix", "value": "ABC"}}
  • The last line is the main rule that must be true to pass the enforcement_level. According to the enforcement level, you will be able to apply the configuration. In this case, if the length of the result is 0 that means there is no prefix variable with the value ABC so the rule is not respected and the policy will fail.

Related