When running import "tfconfig" with sentinel I get import tfconfig is not available

1k Views Asked by At

I am doing some learnings with Terraform and sentinel.

I cant get some of the basic functionality working.

I have a policy here:

import "tfconfig"

default_foo = rule { tfconfig.variables.foo.default is "bar" }
default_number = rule { tfconfig.variables.number.default is 42 }

main = rule { default_foo and default_number }

and a variables file here:

variable "foo" {
  default = "bar"
}

variable "number" {
  default = 42
}

But when I run:

sentinel apply policy.sentinel 

I get the following error:

policy.sentinel:1:1: Import "tfconfig" is not available.

Any ideas as I have been looking for a solution for a number of hours now.

thanks

2

There are 2 best solutions below

2
Martin Atkins On BEST ANSWER

In order to use the Terraform-specific imports in the Sentinel SDK, you need to use mock data to produce a data structure to test against.

When you run Terraform via Terraform Cloud, a successful plan will produce a Sentinel mocks file that contains the same data that Terraform Cloud would itself use when evaluating policies against that plan, and so you can check that mock data into your repository as part of your test suite for your policies.

You can use speculative plans (run terraform plan on the command line with the remote backend enabled) to create mock data for intentionally-invalid configurations that you want to test your policy against, without having to push those invalid configurations into your version control system.

You can use sentinel test against test cases whose JSON definitions include a mock object referring to those mock files, and then the policies evaluated by those test cases will be able to import tfconfig, tfplan and tfstate and get an equivalent result to if the policies were run against the original plan in Terraform Cloud.

0
Max On

I had my mock data and everything and I was still getting this error.

Runtime error while running the policy: ensure-policy.sentinel:3:1: Import "tfplan" is not available

I realized I had forgotten the 'sentinel.json' file at the root of my policies dir, which tells sentinel where to look for the mock data

https://www.terraform.io/docs/cloud/sentinel/mock.html

here's how they recommend a default dir setup, but you still need that .json file to tell sentinel where to look and here's what the sentinel.json file should look like

enter image description here