Write and run policy tests
Once you have authored a policy, write tests that verify that your policy works as intended. Then, run your tests before you implement your new policy and whenever you update your policy.
Author policy tests
Each test file includes a set of mock providers, resources, data sources, and modules that Terraform policy uses to test your policies. Policy test files must have the .policytest.hcl extension.
We recommend storing your tests in the same VCS repository as your policies. Refer to Directory structure for more information about organizing your policies and tests.
To learn how to write policy tests, refer to the Policy test reference documentation.
Run tests
Run the tfpolicy test command to execute your tests locally before enforcing them against your infrastructure. You should also test policies after any updates.
Specify the path to the policies you want to test with the --policies flag:
$ tfpolicy test --policies=/path/to/policies
You can provide separate paths to the policy files and the test files. If you only specify the path to your policy files, Terraform policy only executes tests in that path.
$ tfpolicy test --policies=/path/to/policies --tests=/path/to/tests
When it runs your tests, Terraform policy loads values for input variables from your local environment that match the TF_VAR_ prefix. For example:
$ export TF_VAR_instance_type=t3.medium && tfpolicy test --policies=/path/to/policies --tests=/path/to/tests
Refer to tfpolicy test reference for more information about the tfpolicy test command.
Next steps
- Review the test reference documentation for detailed information about writing tests.
- Learn about the
tfpolicy testcommand - To install the
tfpolicyCLI, refer to Install the Terraform policy CLI