policytest
The policytest {} block defines the policies that Terraform policy will test.
Configuration model
policytest {
targets = [
"<path_to_policy_file>",
"<path_to_policy_directory>"
]
}
Complete configuration example
policytest {
targets = [
"path/to/single_policy.policy.hcl",
"path/containing/multiple_policies/"
]
}
Specification
Arguments
| Argument | Required | Type | Description |
|---|---|---|---|
targets | No | List of Strings | A list of policy files or directories containing policy files for Terraform policy to test against the mock providers, resources, data sources, and modules defined in the test file. |
Behavior
If you do not specify targets in your policytest {} block, Terraform policy will evaluate the policy files in the path you provide when you run your tests using the --policies flag.
Examples
Test specific policy files
policytest {
targets = [
"../policies/aws_provider.policy.hcl",
"../policies/encrypted_ebs.policy.hcl"
]
}
provider "aws" "example" {
meta = {
source = "hashicorp/aws"
version = "5.0.0"
}
attrs = {
region = "us-east-1"
}
}
resource "aws_ebs_volume" "encrypted" {
attrs = {
availability_zone = "us-east-1a"
size = 10
encrypted = true
}
}
Test all policies in a directory
policytest {
targets = [
"../policies"
]
}
resource "aws_instance" "example" {
attrs = {
instance_type = "t3.micro"
ami = "ami-12345678"
}
}
Test multiple policy directories
policytest {
targets = [
"../policies/security",
"../policies/compliance",
"../policies/cost-optimization"
]
}
resource "aws_s3_bucket" "example" {
attrs = {
bucket = "example-bucket"
}
}
Omit targets to use command-line path
# No policytest block - will use --policies flag value
resource "aws_instance" "example" {
attrs = {
instance_type = "t3.micro"
ami = "ami-12345678"
}
}
When running tests without a policytest {} block:
$ tfpolicy test --policies=../policies --tests=.
Related documentation
- Write and run policy tests - Learn how to write and run tests
tfpolicy testcommand - CLI reference for running tests