references/tfpolicy-test.md · 24000
true attrs = { volume_id = "vol-12345" } }
resource "aws_instance" "server" { attrs = { ebs_block_device = [{ volume_id = aws_ebs_volume.available_for_reference.attrs.volume_id }] } }
**Use skip only when:** Resource is referenced or needed in getresources() counts.
### Testing Filters
If a resource doesn't match the filter, it's NOT evaluated (test passes):
```hcl
# Policy with filter
resource_policy "aws_s3_bucket" {
filter = attrs.bucket_prefix == "secure-"
enforce {
condition = attrs.versioning[0].enabled == true
}
}
# Test - doesn't match filter, so passes
resource "aws_s3_bucket" "filtered_out" {
attrs = {
bucket_prefix = "public-" # Doesn't match filter
versioning = [{ enabled = false }]
}
}
Best Practice: Test both resources that match and don't match the filter.
Resource Policy Meta Attributes
IMPORTANT: Meta attributes for resource_policy behave differently in mock tests vs real terraform plan evaluation.
Available Meta Attributes by Evaluation Mode:
| Meta Attribute | Mock Tests (tfpolicy test) | Real Plans (terraform plan --policies=) |
|----------------|------------------------------|------------------------------------------|
| meta.provider_type | ❌ UNDEFINED | ✅ Available (e.g., "aws", "azurerm") |
| meta.tfe_stack.deployment_name | ✅ Available in tfpolicy 0.3.x+ mocks | ✅ Always present; empty outside Stack evaluations (null on 0.5.0+) |
| meta.tfe_stack.stack_name | ✅ Available in tfpolicy 0.3.x+ mocks | ✅ Always present; empty outside Stack evaluations (null on 0.5.0+) |
| meta.tfe_stack.deployment_group | ✅ Available in tfpolicy 0.3.x+ mocks | ✅ Always present; empty outside Stack evaluations (null on 0.5.0+) |
| meta.tfe_workspace.tags | ✅ Available in tfpolicy 0.3.x+ mocks | ✅ Available for workspace evaluations; empty for Stacks or untagged workspaces |
| meta.type | ❌ UNDEFINED | ❌ UNDEFINED |
| meta.address | ❌ UNDEFINED | ❌ UNDEFINED |
Example:
# Policy using meta.provider_type
resource_policy "aws_ebs_volume" "check_provider" {
enforce {
condition = core::try(meta.provider_type, "UNDEFINED") == "aws"
error_message = "Provider type: ${core::try(meta.provider_type, "UNDEFINED")}"
}
}
Test behavior:
- With
tfpolicy test:meta.provider_typereturns UNDEFINED (test may fail) - With
terraform plan --policies=:meta.provider_typereturns "aws" (test passes)
Best Practice: When using meta.provider_type in policies, always wrap with core::try() and note that mock tests cannot fully validate this behavior. Test with real terraform plans for complete validation.
Stack and workspace metadata in tests (tfpolicy 0.3.x+): metadata can be mocked with meta.tfe_stack.* and meta.tfe_workspace.tags for resource, provider, and module policies. Stack fields are empty strings outside Stack evaluations on 0.3.x/0.4.x and null on 0.5.0+ (guard with != null; in mocks, set them to null explicitly to simulate a workspace, because an omitted key is missing rather than null and reading it fails), so use them for stack-scoped exclusion workflows:
resource "null_resource" "excluded_deployment" {
attrs = {
triggers = null
}
meta = {
tfe_stack = {
deployment_name = "excluded-deployment"
stack_name = "payments"
deployment_group = "nonprod"
}
}
}
Module Policy Testing
Module Test Syntax
module "source" "test_name" {
expect_failure = true/false # Optional
meta = {
source = "registry.terraform.io/namespace/name"
address = "module.name"
version = "1.0.0"
}
}
Available meta attributes:
source- Module sourceaddress- Module address (e.g., "module.database")version- Module version
Note: Modules use meta only (no attrs)
Example: Module Source Allowlist
Policy:
locals {
allowed_sources = [
"registry.terraform.io/hashicorp/aws",
"registry.terraform.io/terraform-aws-modules/vpc/aws"
]
}
module_policy "*" "approved_sources" {
filter = meta.source != null
enforce {
condition = core::contains(local.allowed_sources, meta.source)
error_message = "Unauthorized module source: ${meta.source}"
}
}
Test:
# Passing
module "registry.terraform.io/hashicorp/aws" "approved" {
meta = {
source = "registry.terraform.io/hashicorp/aws"
address = "module.database"
version = "1.0.0"
}
}
# Failing
module "registry.terraform.io/acme-corp/database" "unauthorized" {
expect_failure = true
meta = {
source = "registry.terraform.io/acme-corp/database"
address = "module.db"
version = "2.0.0"
}
}
Example: Module Version Enforcement
Policy:
module_policy "registry.terraform.io/hashicorp/aws" "version_check" {
filter = meta.source == "registry.terraform.io/hashicorp/aws"
enforce {
condition = meta.version != null ? core::semverconstraint(meta.version, ">= 4.0.0") : false
error_message = "Module must use version >= 4.0.0, found ${meta.version != null ? meta.version : "no version"}"
}
}
Provider Policy Testing
Provider Test Syntax
provider "type" "test_name" {
expect_failure = true/false # Optional
meta = {
source = "registry.terraform.io/namespace/name"
}
}
Available meta attributes:
source- Provider source (e.g., "registry.terraform.io/hashicorp/aws")
Note: Provider type (e.g., "aws") goes in block declaration, not meta.
Example: Provider Source Allowlist
Policy:
locals {
allowed_provider_sources = [
"registry.terraform.io/hashicorp/aws",
"registry.terraform.io/hashicorp/azurerm"
]
}
provider_policy "aws" {
enforce {
condition = core::contains(local.allowed_provider_sources, meta.source)
error_message = "Provider source '${meta.source}' is not approved"
}
}
Test:
# Passing
provider "aws" "official" {
meta = {
source = "registry.terraform.io/hashicorp/aws"
}
}
# Failing
provider "aws" "unofficial" {
expect_failure = true
meta = {
source = "registry.terraform.io/acme-corp/aws"
}
}
Common Provider Patterns
- Official providers only: Check
meta.source == "registry.terraform.io/hashicorp/aws" - Version constraints: Use
core::semverconstraint(meta.version, ">= 4.0.0, < 6.0.0")(on 0.5.0+ wrap it asmeta.version != null ? core::semverconstraint(...) : false, since an unspecified version isnulland&&does not short-circuit) - Allowlist by type: Create separate provider_policy for each allowed type
Advanced Techniques
Data Source Mocking
data "aws_ami" "ubuntu" {
attrs = {
id = "ami-12345"
name = "ubuntu-20.04"
}
}
# Policy can reference it
resource_policy "aws_instance" {
enforce {
condition = attrs.ami == data.aws_ami.ubuntu.attrs.id
}
}
Workspace Context Limitations
❌ Not Available: terraform.workspace or workspace context
Valid traversal roots:
input- Input variableslocal- Local variablesattrs- Resource/data source attributesmeta- Metadata
Workarounds:
- Use resource tags for environment-based logic
- Separate policy sets per environment in HCP Terraform
- CI/CD-level enforcement based on workspace name
- Tag-based validation
Testing Collections
resource "aws_security_group" "multiple_rules" {
attrs = {
ingress = [
{
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["10.0.0.0/8"]
},
{
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
]
}
}
Testing Null/Missing Attributes
Only works if policy uses core::try():
# Policy must use core::try() to handle missing attributes
resource_policy "aws_s3_bucket" "check" {
locals {
encryption = core::try(attrs.server_side_encryption_configuration, null)
}
enforce {
condition = local.encryption != null
error_message = "Encryption required"
}
}
# Test - omitted attribute handled by core::try()
resource "aws_s3_bucket" "no_encryption" {
expect_failure = true
attrs = {
bucket = "my-bucket"
# server_side_encryption_configuration omitted - handled by core::try()
}
}
Without core::try(), omitting accessed attributes causes evaluation errors.
Testing Policies with input Blocks
Policies that use input blocks can have their input values overridden per test file using an inputs {} block (plural). This allows you to test the policy behaviour under different configurations without changing the policy itself.
⚠️ The block is
inputs {}(plural) — usinginput {}(singular) throwsUnsupported block typeerror.
# Policy (test.policy.hcl)
input "port" {
type = number
default = 22
}
resource_policy "aws_security_group_rule" "no_open_ingress" {
filter = core::try(attrs.type, "") == "ingress"
locals {
covers_port = core::try(attrs.from_port <= input.port && attrs.to_port >= input.port, false)
}
enforce {
condition = !local.covers_port
error_message = "Ingress rule covers restricted port ${input.port}."
}
}
# Test file 1: test with default port (22)
policytest {
targets = ["test.policy.hcl"]
}
# No inputs block — uses input.port default = 22
# PASS: port range 80-443 does not cover default port 22
resource "aws_security_group_rule" "pass_default_port" {
attrs = {
type = "ingress"
from_port = 80
to_port = 443
protocol = "tcp"
}
}
# FAIL: port range 1-1024 covers default port 22
resource "aws_security_group_rule" "fail_default_port" {
expect_failure = true
attrs = {
type = "ingress"
from_port = 1
to_port = 1024
protocol = "tcp"
}
}
# Test file 2: test with custom port (90)
policytest {
targets = ["test.policy.hcl"]
}
inputs {
port = 90 # override default of 22
}
# FAIL: port range 80-443 DOES cover custom port 90
resource "aws_security_group_rule" "fail_custom_port" {
expect_failure = true
attrs = {
type = "ingress"
from_port = 80
to_port = 443
protocol = "tcp"
}
}
Key points:
- Each test file can have its own
inputs {}block with different values — use separate.policytest.hclfiles per input scenario - When no
inputs {}block is present, the policy'sdefaultvalues are used - Always add a comment to each test file stating which input values it assumes — prevents confusion when the same resource mock produces different results under different inputs
- Note: input values can only be overridden at policy-set level in HCP Terraform for live enforcement —
inputs {}in test files is for test-time validation only
Every generated .policytest.hcl must include test cases for the following scenarios. Missing any of these is a test coverage gap:
| Scenario | Mock pattern | Why it matters |
|----------|-------------|----------------|
| Missing attribute (omitted entirely) | attrs = { bucket = "x" } — target attribute not present | Crashes policies that don't use core::try(); most common real-world gap |
| Null attribute | attrs = { ..., field = null } | Tests core::try() default handling |
| Empty list | attrs = { ..., items = [] } | Policies expecting non-empty collections must handle [] |
| Empty string | attrs = { ..., value = "" } | String-check policies must not treat "" as compliant |
| Boundary value | Exact threshold (e.g. port = 443, count = max_allowed) | Off-by-one errors in range/count checks |
# ✅ Missing attribute — must fail (tests core::try() default)
resource "aws_s3_bucket" "missing_encryption" {
expect_failure = true
attrs = {
bucket = "test-bucket"
# server_side_encryption_configuration intentionally omitted
}
}
# ✅ Empty list — must fail
resource "aws_s3_bucket" "empty_encryption_rules" {
expect_failure = true
attrs = {
bucket = "test-bucket"
server_side_encryption_configuration = []
}
}
Best Practices
General Guidelines
- Use descriptive names:
encrypted_volume_passesnottest1 - Organize by scenario: Group passing/failing tests with comments
- Test edge cases: Always include missing-attribute, null, empty-collection, and boundary-value scenarios — see Mandatory Edge-Case Checklist above
- Consult provider schemas: Match provider's block/attribute structure
Testing Strategy
- Separate concerns: One test file per policy file
- Use skip strategically: Only when resource is referenced or in getresources() counts
- Test both sides of filters: Resources that match and don't match
- Document complex references: Add comments explaining relationships
File Organization
policies/
├── cis-4.1-deny-public-ssh.policy.hcl
├── cis-4.1-deny-public-ssh.policytest.hcl
├── cis-4.2-deny-public-rdp.policy.hcl
└── cis-4.2-deny-public-rdp.policytest.hcl
Quick Reference Table
| Policy Type | Test Block | Available Attributes |
|-------------|------------|---------------------|
| resource_policy | resource "type" "name" { attrs = {...} } | attrs.*, meta.provider_type (real plans only) |
| module_policy | module "source" "name" { meta = {...} } | meta.source, meta.address, meta.version |
| provider_policy | provider "type" "name" { meta = {...} } | meta.source |
| data source | data "type" "name" { attrs = {...} } | attrs.* |
Common Features
| Feature | Syntax | Scope |
|---------|--------|-------|
| Test target | policytest { targets = ["file.policy.hcl"] } | Optional (best practice when multiple policies in dir) |
| Override input values | inputs { key = value } | Per test file — uses policy default if omitted |
| Expected failure | expect_failure = true | All policies |
| Skip evaluation | skip = true | Resources only |
| Cross-resource ref | resource_type.name.attrs.attribute | Same file only |
| Omitted attributes | Don't specify in attrs = {} | Causes error unless policy uses core::try() |
Advanced Testing Patterns (Real-World Learnings)
Cross-Resource Lookup Pattern
Problem: Need to enforce that every S3 bucket has a corresponding encryption configuration.
Solution: Evaluate buckets, look up encryption configs via core::getresources().
# Top-level: Get all encryption configs once
locals {
all_encryption_configs = core::getresources("aws_s3_bucket_server_side_encryption_configuration", {})
}
# Resource-level: Find matching config for each bucket
resource_policy "aws_s3_bucket" "require_encryption" {
locals {
matching_configs = [
for config in local.all_encryption_configs :
config if config.bucket == attrs.bucket
]
}
enforce {
condition = core::try(local.matching_configs[0], null) != null
error_message = "Bucket must have encryption config"
}
}
Test Structure:
# Evaluated resource - NO skip
resource "aws_s3_bucket" "test" {
attrs = { bucket = "test" }
}
# Looked-up resource - YES skip (but still visible to core::getresources)
resource "aws_s3_bucket_server_side_encryption_configuration" "config" {
skip = true
attrs = {
bucket = aws_s3_bucket.test.bucket
rule = [{ ... }] # Must be array!
}
}
Key Points:
- ✅ Resources with
skip = trueARE visible tocore::getresources() - ✅ Use top-level
localsforcore::getresources()(performance) - ✅ Always evaluate the resource that must exist, look up optional ones
The Two-Check Pattern
Problem: Need to check two related attributes to determine compliance.
Example: S3 must use customer-managed KMS keys (not AWS-managed or AES256).
AWS encryption types:
- SSE-S3 (AES256) - S3-managed keys ❌
- SSE-KMS without key ID - AWS-managed "aws/s3" key ❌
- SSE-KMS with key ID - Customer-managed key ✅
Why one check fails:
# ❌ Only checks algorithm
condition = attrs.sse_algorithm == "aws:kms"
# PASSES even without kms_master_key_id (uses AWS-managed key!)
# ❌ Only checks key ID
condition = attrs.kms_master_key_id != ""
# PASSES even with "AES256" algorithm (not using KMS!)
Correct: Check both
locals {
sse_algorithm = core::try(attrs.encryption[0].sse_algorithm, "")
kms_key_id = core::try(attrs.encryption[0].kms_master_key_id, "")
}
enforce {
condition = local.sse_algorithm == "aws:kms" && local.kms_key_id != ""
error_message = "Must use customer-managed KMS. Found algorithm: '${local.sse_algorithm}', key specified: ${local.kms_key_id != ""}"
}
Test File Size Limitation
Discovery: With two-policy approach (one policy for buckets, another for encryption configs), test files fail when they contain 5+ buckets.
Workaround 1: Use single-policy approach (no limit observed)
# ✅ One policy evaluates buckets, looks up configs
resource_policy "aws_s3_bucket" "require_encryption" {
# Can test 6+ buckets in single file
}
Workaround 2: Split tests across multiple files (max 4 buckets each)
tests/
├── test-scenario-1.policytest.hcl # 4 buckets
├── test-scenario-2.policytest.hcl # 4 buckets
└── test-scenario-3.policytest.hcl # 4 buckets
Common Test Mistakes
Mistake: Wrong resource has skip or expect_failure
# ❌ WRONG - Policy evaluates buckets but test skips them
resource "aws_s3_bucket" "test" {
skip = true # Policy can't evaluate this!
}
resource "aws_s3_bucket_server_side_encryption_configuration" "config" {
expect_failure = true # Policy doesn't evaluate this!
}
# ✅ CORRECT - Match policy evaluation target
resource "aws_s3_bucket" "test" {
expect_failure = true # Policy evaluates buckets
}
resource "aws_s3_bucket_server_side_encryption_configuration" "config" {
skip = true # Policy looks this up via core::getresources()
}
Mistake: Using objects instead of arrays
# ❌ WRONG
attrs = {
rule = { key = "value" } # Object
}
# ✅ CORRECT
attrs = {
rule = [{ key = "value" }] # Array
}
Reason: Terraform resources use arrays. Policies access attrs.rule[0].
Known Policytest Framework Limitations
These are behaviors where tfpolicy test passes silently but a real terraform plan --policies= run fails or behaves differently. Always verify port-range and integer-arithmetic policies against a real plan.
core::range() with dynamic integer attributes returns empty in policytest
core::range(start, end) works correctly when called with hardcoded integer literals. However, when start or end come from mocked attrs.* integer values (e.g. attrs.from_port, attrs.to_port), the policytest framework treats those values as unknown/unevaluated at test time and core::range() silently returns an empty list [].
Impact: A policy that uses core::range() with dynamic port attributes will appear to pass all tests — including expect_failure cases — because the range is always empty. The bug only surfaces against a real plan.
Note:
core::alltrue()andcore::anytrue()are available starting in tfpolicy 0.3.x (see verified-syntax), but they do not fix thecore::range()limitation below:core::range()still returns[]for dynamicattrs.*bounds in policytest, so the count approach remains the correct fix.
# ❌ WRONG — core::range() + core::alltrue()/core::anytrue() — still problematic even on 0.3.0+
locals {
ports_in_range = core::range(core::try(attrs.from_port, 0), core::try(attrs.to_port, 0) + 1)
# ↑ returns [] in policytest because attrs.from_port/to_port are unknown at test time
all_authorized = core::alltrue([for p in local.ports_in_range : core::contains(local.authorized_ports, p)])
# ↑ core::alltrue vacuously returns true over an empty list — masks the real range bug either way
}
Fix: Use the count approach instead — it works correctly with dynamic attrs.* values in both policytest and real plans:
# ✅ Count approach — consistent in policytest and real plan evaluation
locals {
authorized_ports = [80, 443]
from_port = core::try(attrs.from_port, 0)
to_port = core::try(attrs.to_port, 0)
authorized_in_range = [for p in local.authorized_ports : p if p >= local.from_port && p <= local.to_port]
all_ports_authorized = core::length(local.authorized_in_range) == (local.to_port - local.from_port + 1)
}
See verified-syntax.md Mistake 23 for the full pattern.
core::getresources() sees ALL resources in the test file — isolate conflicting scenarios into separate files
In tfpolicy test, when a policy calls core::getresources("some_type", filter), the lookup searches all mock resources of that type in the entire test file — including resources marked expect_failure = true and resources marked skip = true.
Impact: A test scenario that requires core::getresources() to return zero results (or no compliant results) will silently produce the wrong outcome if any other scenario in the same file defines a resource of that type that satisfies the filter.
# ❌ PROBLEMATIC — both scenarios in the same test file
# "fail_no_defaults" incorrectly passes because core::getresources() picks up
# the compliant_defaults resource from the other scenario.
resource "aws_ec2_instance_metadata_defaults" "compliant_defaults" {
skip = true # skip = true is still visible to core::getresources()!
attrs = { http_tokens = "required" }
}
resource "aws_instance" "pass_with_defaults" {
attrs = { instance_type = "t3.micro" }
}
resource "aws_instance" "fail_no_defaults" {
expect_failure = true
attrs = { instance_type = "t3.micro" }
# WRONG: core::getresources("aws_ec2_instance_metadata_defaults", ...) still sees
# "compliant_defaults" above → policy evaluates as compliant → expect_failure passes incorrectly.
}
Fix: Place scenarios with conflicting core::getresources() context into separate .policytest.hcl files. Each file is an independent resource graph.
# ✅ File 1: test-with-compliant-defaults.policytest.hcl
resource "aws_ec2_instance_metadata_defaults" "compliant_defaults" {
skip = true
attrs = { http_tokens = "required" }
}
resource "aws_instance" "pass_with_defaults" {
attrs = { instance_type = "t3.micro" }
}
# ✅ File 2: test-no-defaults.policytest.hcl
# No aws_ec2_instance_metadata_defaults defined — core::getresources() returns empty list.
resource "aws_instance" "fail_no_defaults" {
expect_failure = true
attrs = { instance_type = "t3.micro" }
}
Rule: Whenever a test scenario relies on core::getresources() returning zero results (or no compliant results) for a given type, that scenario must be in its own .policytest.hcl file, completely isolated from any scenario that defines resources of that same type.