AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

terraform-policy

Write, test, or convert Terraform Policy files (.policy.hcl, .policytest.hcl, Sentinel→tfpolicy). Triggers: policy.hcl, policytest, convert sentinel, tfpolicy, write a policy.

Original source
hashicorp
License
MPL-2.0
Pinned revision
bc6b14b77481c3cbfbb06a0166be7245ed45798c

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

This skill also requires local files or dependencies. Remote reading alone may not be enough.

Ask your assistant

Use Agentic Memory skills to read hashicorp--terraform-policy at revision bc6b14b77481c3cbfbb06a0166be7245ed45798c, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 22

references/tfpolicy-test.md


name: tfpolicy-test description: Expert agent for testing Terraform policies. Helps write and debug .policytest.hcl files, design resource mocks (attrs / prior_attrs), reason about runner behavior, and verify policy correctness before promotion to enforcement. license: MPL-2.0 metadata: copyright: Copyright IBM Corp. 2026 version: "0.1.0"

tfpolicy-test

Description

Expert agent for testing Terraform policies. Helps write .policytest.hcl files, design resource and module mocks, use expect_failure correctly, mock cross-resource lookups for core::getresources(), and reason about current tfpolicy test runner behavior.

Use When

  • The user has an existing policy and wants to write or improve tests for it.
  • The user is debugging a failing or unexpectedly-passing test, or asking why a mock behaves the way it does.
  • The user is writing .policytest.hcl files, policytest { targets = [...] } blocks, resource {} / module {} mocks, or using expect_failure / skip.
  • The user is testing operation-aware policies and needs to mock attrs and/or prior_attrs for create/update/delete scenarios.
  • The user is asking how to mock cross-resource lookups (e.g. aws_s3_bucket_versioning for core::getresources patterns).
  • The user is investigating a runner caveat (expect_failure not supported on data blocks, etc.).

Do not use this skill when:

  • The user is writing the policy itself rather than its test — use tfpolicy-author.
  • The user is converting a Sentinel test to a .policytest.hcl test — start with tfpolicy-author, then return here for test-side refinements.

Capabilities

1. Write .policytest.hcl Files from Existing Policies

Generate a focused test file that exercises the passing and failing paths of a policy, including expect_failure = true cases and any required prior_attrs mocks. For policies that use input blocks, generate separate test files per input scenario using inputs {} (plural) to override default values.

2. Design Mocks for Cross-Resource Lookups

Build the resource {} blocks needed for core::getresources() filters to match correctly (parent + child resources, skip = true on lookup-only resources, etc.).

3. Diagnose Runner Behavior

Explain why a mock fails, passes, or crashes. Cover the current caveats: expect_failure is rejected on data blocks, omitted attributes crash unless wrapped in core::try(), and replacement operations must be represented by separate create and delete policy blocks.

4. Recommend Test Organization

Decide when to split into multiple .policytest.hcl files (per-policy targeting) versus consolidating, and how to keep mocks aligned with the policy's actual evaluation target.

5. Generate Edge-Case Test Scenarios

For every generated test file, mandate test cases covering:

  • Missing attribute — resource mock where the attribute is entirely omitted (most common real-world gap; crashes policies that don't use core::try())
  • Empty collection — resource with an empty list [] or empty map {} where the policy expects a non-empty value
  • Boundary conditions — exact threshold values (e.g. port at limit, count at max)
  • Null attribute — resource where the checked attribute is explicitly set to null. ⚠️ This case must only be included when the rules below permit it — do not add it unconditionally.

Every generated .policytest.hcl must include at least one expect_failure = true resource that exercises a missing-attribute scenario.

Before finalizing each test case, verify polarity against the policy's condition. For each expect_failure = true case, confirm the condition evaluates to false for that mock. For each pass case (no expect_failure), confirm it evaluates to true. A fail case the policy actually passes produces Missing expected failure; a pass case the policy actually fails produces an unexpected violation.

🔴 Null test case decision rules:

Key fact: core::try(attrs.field, default) triggers the fallback only when the attribute key is absent. When a mock explicitly sets attrs.field = null, core::try returns null — not the default. This asymmetry means a null case and an omitted-attribute case exercise different code paths.

For every attribute you are about to set to null in a test mock — regardless of attribute name, nesting level, or resource type — apply this check before adding the case:

  • Two-step pattern (raw = core::try(attrs.field, null) then val = raw != null ? raw : []) — null is explicitly normalized to a safe default. Add a pass case (no expect_failure) with the attribute set to null to verify this normalization works.
  • Explicit non-compliance check (condition = val != null && val != "") — null is intentionally treated as non-compliant. Add a fail case (expect_failure = true) with the attribute set to null.
  • Single-step only (val = core::try(attrs.field, [])) without an explicit null guard — null is not normalized and will crash downstream expressions (for val in null, core::length(null)). Do NOT add a null case. Fix the policy to use the two-step pattern instead.

Never add fail_*_null when the policy treats null the same as the safe default (false / []). A null case that the policy silently normalizes to compliant produces a Missing expected failure error — caused by the test itself, not a real policy bug.

The three rules above apply at every nesting level. For a scalar accessed as core::try(local.list[0].attr, default), apply the same single-step / two-step determination at that specific access point.

6. Mock Cross-Resource Lookups for core::getresources()

When the policy under test uses core::getresources(resource_type, filter), the test runner resolves the lookup against the resources declared in the same .policytest.hcl file. For the lookup to return the expected results:

  1. Filter attribute values must match exactly. The companion resource mock must declare the linking attribute with the exact value that equals attrs.<linking_attr> of the parent resource at evaluation time. Resource names in the mock do not affect matching — only attribute values do.
  2. Use skip = true on companion resources. Resources that should be visible to core::getresources() but must not be evaluated directly by the policy should be declared with skip = true. Without this, the runner evaluates them as standalone resources, which may produce unexpected results.
  3. Test the no-match case explicitly. Include a test case where the companion resource is absent or has a non-matching filter attribute value. In this case core::getresources() returns an empty list — verify that the policy handles this as intended (e.g. treats the parent as non-compliant if a companion is required, or compliant if companion is optional).
  4. Test the match case explicitly. Include a test case where the companion resource is present with matching attributes to confirm the lookup resolves correctly.
  5. filter on the policy affects ALL resources in the test file when companions are present. When the policy uses a top-level core::getresources()-based filter (e.g. filter = core::length(local.all_companions) > 0), every parent resource in the test file is evaluated as soon as any companion resource is declared in that file. An unlinked parent (is_linked = false) then fails is_linked && check_attr == VALUE → violation — even if check_attr has the correct value. Do NOT include a "pass because not linked" case in the same file as companion resources. Omit it entirely; the meaningful cases are: (a) linked + correct attr → pass, (b) linked + wrong attr → fail. If the policy uses filter = local.has_qualifying (qualifying companions only), unlinked parents are not evaluated when no qualifying companions exist — but they still get evaluated when qualifying companions are present, so the same rule applies: no "unlinked pass" case in a file that also declares companion resources.

7. Enforce Explicit policytest { targets } Blocks

Best practice: every generated .policytest.hcl should include an explicit policytest { targets = ["<policy-file>.policy.hcl"] } block when multiple policies exist in the same directory. Without it, tfpolicy test evaluates the mock against every policy in the directory — causing a test written for one policy to run against a different policy, producing misleading pass/fail results.

8. Verify Default Values Match the Source Intent

When generating test cases for policies that use core::try(attr, default), confirm that the default value in the policy matches the intended behavior for absent or null attributes. A wrong default silently passes resources that should fail. For each boolean flag or enum attribute, add a comment in the test explaining the expected behavior when the attribute is omitted versus explicitly set to null.

Knowledge Base

The bulk of this skill is the testing guide:

Cross-cutting facts shared with the sibling skills live in:

  • verified-syntax.md — verified Terraform Policy syntax, function names, runtime limitations. Anything in conflict with the testing guide should defer to this file.

See Also


Table of Contents

  1. Testing Basics
  2. Resource Policy Testing
  3. Module Policy Testing
  4. Provider Policy Testing
  5. Advanced Techniques
  6. Best Practices

Testing Basics

Test File Structure

# tfpolicy 0.3.0+: the same policy { required_providers { ... } } block already
# required in the target .policy.hcl is what tfpolicy test uses to resolve
# provider schemas for preflighting the mocks below. .policytest.hcl itself
# does NOT declare its own required_providers block.
policytest {
  targets = ["policy-file-1.policy.hcl", "policy-file-2.policy.hcl"]
}

# Mock resources with expected outcomes
resource "aws_s3_bucket" "passing_bucket" {
  attrs = {
    bucket = "my-secure-bucket"
    versioning = [{ enabled = true }]
  }
}

resource "aws_s3_bucket" "failing_bucket" {
  expect_failure = true
  attrs = {
    bucket = "my-insecure-bucket"
    versioning = [{ enabled = false }]
  }
}

Full test file structure with all supported blocks:

policytest {
  targets = ["policy-file.policy.hcl"]
}

# Override input defaults for this test file
inputs {
  port = 90
}

resource "aws_security_group_rule" "should_fail_port_90" {
  expect_failure = true
  attrs = {
    type        = "ingress"
    from_port   = 80
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

Key Points:

  • required_providers lives only in .policy.hcl, not .policytest.hcl. There is no policytest { required_providers { ... } } block. On tfpolicy 0.3.0+, the existing top-level policy { required_providers { ... } } block in the targeted .policy.hcl file (see tfpolicy-author) is reused by tfpolicy test to resolve provider schemas and preflight the attrs/prior_attrs values declared in this test file — you do not declare it a second time in the test file itself.
  • Best practice: include policytest { targets = ["<policy-file>.policy.hcl"] } when multiple policies exist in the same directory. Without it, tfpolicy test evaluates the mock against every policy in the directory — a test resource intended for one policy will silently run against others, producing misleading results. expect_failure = true on such a resource can pass for the wrong reason.
  • expect_failure = true applies to ALL policies evaluating the resource
  • expect_failure is ONLY valid on resource {} blocks — using it on data {} blocks causes Unsupported argument error

⚠️ Critical: tfpolicy test does NOT evaluate error_message

tfpolicy test only evaluates the condition expression. It never evaluates or interpolates the error_message string. This means:

  • A policy with error_message = "Failed: ${meta.address}" will pass all tfpolicy test runs even though meta.address is UNDEFINED and will crash every resource at runtime.
  • Only terraform plan --policies= evaluates error_message — always validate generated policies against a real Terraform plan to catch this class of bug.
  • CRITICAL: Omitted attributes cause evaluation errors if accessed directly. Always use core::try() to handle missing attributes

Test Execution Behavior

  1. Multiple policies evaluate same resources - All matching policies run against all matching test resources
  2. Tests continue on failure - All tests run to completion, not stopping at first failure
  3. Exit codes for CI/CD:
    • Exit 0: All tests pass (including expected failures)
    • Exit 1: Unexpected failures or errors

Schema preflight validation (tfpolicy 0.3.0+): tfpolicy test now reuses the same provider-resolution path as tfpolicy validate. Before any test executes, provider, resource, and data-source policy inputs and every attrs/prior_attrs value in every test file — including mocks belonging to skip = true cases — are preflighted against the provider schemas resolved from the target .policy.hcl's top-level policy { required_providers { ... } } block. The same schemas validate arguments used by core::getdatasource() and core::getresources(). A mocked attribute that doesn't exist in the schema, or has the wrong type, fails preflight with a diagnostic pointing at the offending value, and no tests in that run execute — this is a hard stop, not a per-case warning. Fixtures that conform to the schema run unchanged, and the exact preflighted values (not a re-parsed copy) are what policies evaluate.

Pre-0.3.0 schema-verification caveat (superseded by preflight validation above on 0.3.0+):

  • tfpolicy validate --policies=... performs provider schema acquisition and validates resource types against the providers declared in policy.required_providers.
  • tfpolicy test --policies=... --tests=... can still emit: Warning: Resource types not verified against provider schemas even when validate succeeded separately.
  • Interpret this as a test-runner limitation/caveat, not necessarily a policy failure. The test runner can execute mocks structurally while warning that resource-type verification was not enforced in that execution path.
  • Do not rely on tfpolicy test alone to catch misspelled or unknown resource types. Always run tfpolicy validate as a separate step before or alongside tests.
  • In current behavior, this warning may still produce a non-zero process exit code from tfpolicy test, even when all individual test cases show pass.

CI/CD Usage:

tfpolicy validate --policies=./policies
tfpolicy test --policies=./policies --tests=./tests
if [ $? -eq 0 ]; then echo "Passed"; else echo "Failed"; exit 1; fi

Resource Policy Testing

Basic Syntax

resource "resource_type" "test_name" {
  expect_failure = true/false  # Optional — ONLY valid on resource blocks, NOT data blocks
  skip = true/false            # Optional
  attrs = {
    # All resource attributes
  }
}

⚠️ expect_failure is NOT supported on data {} blocks. Using it on a data block causes Unsupported argument "expect_failure". Only mock resource {} blocks support this attribute.

Every resource {} Mock Must Declare a Non-Empty State Block (tfpolicy 0.3.0+)

On tfpolicy 0.3.0+: every mock resource {} block must declare attrs or prior_attrs. If both evaluate to empty for a given resource block, tfpolicy skips that test case because no operation can be inferred. Use null for "attribute not set", e.g. attrs = { instance_type = null }, not an empty block. meta.operation alone is not a substitute — it still requires an accompanying state block. On tfpolicy < 0.3.0, meta-only fixtures are still accepted but silently do nothing (see below).

Scope: resource {} blocks only. This requirement applies exclusively to mock resource {} blocks (resource_policy tests). provider {} and module {} mocks are unaffected — meta-only fixtures (e.g. meta = { source = "...", version = "..." } with no attrs) continue to work as before for module_policy and provider_policy tests, since those policy types don't infer a create/update/delete operation from resource state the way resource_policy does.

An empty-state mock reports skipped with a warning rather than pass, and expect_failure = true fails on a skipped case because a skip asserts nothing.

Upgrading older fixtures: find resource {} blocks with neither attrs nor prior_attrs, or only empty {} ones, and add at least one attribute (null where you mean "unset").

Omitted Attributes Behavior

CRITICAL: Attributes accessed by policies MUST be provided in test mocks or wrapped with core::try().

Direct Access (Causes Error):

# Policy
resource_policy "aws_ebs_volume" "check" {
  enforce {
    condition = attrs.encrypted == true  # Direct access
  }
}

# Test - ERROR if encrypted is omitted
resource "aws_ebs_volume" "test" {
  attrs = {
    size = 100
    # encrypted omitted - causes "This object does not have an attribute named 'encrypted'"
  }
}

Safe Access with core::try():

# Policy
resource_policy "aws_ebs_volume" "check" {
  locals {
    encrypted = core::try(attrs.encrypted, false)  # Safe access
  }
  enforce {
    condition = local.encrypted == true
  }
}

# Test - Works even if encrypted is omitted
resource "aws_ebs_volume" "test" {
  attrs = {
    size = 100
    # encrypted omitted - core::try() returns false (default value)
  }
}

Rule: Only attributes NOT accessed by the policy can be safely omitted. All accessed attributes must either:

  1. Be provided in the mock's attrs = {} block, OR
  2. Be accessed via core::try() in the policy

Testing Operation-Aware Policies

Policies can scope themselves to specific plan operations via operations = ["create", "update", "delete", "no-op"] ("no-op" requires tfpolicy 0.4.0+). Test mocks support a matching prior_attrs = { ... } block alongside attrs = { ... }, so create, update, no-op, and delete-gate policies are all fully testable.

Mock shape per operation:

| Operation being tested | Provide attrs | Provide prior_attrs | | --- | --- | --- | | create | ✅ planned values | — | | update | ✅ planned values | ✅ pre-change values | | delete | — | ✅ pre-change values | | no-op (0.4.0+) | ✅ existing values | — |

If meta.operation is omitted, tfpolicy infers the operation from the state blocks: attrs only → create, attrs + prior_attrs → update, prior_attrs only → delete. It never infers no-op, so set meta = { operation = "no-op" } explicitly on no-op mocks. Otherwise a policy scoped to ["no-op"] skips them: passing mocks pass without being evaluated, and expect_failure mocks fail with "Missing expected failure".

Create / update policy (planned values only):

# Policy
resource_policy "tfe_workspace" "require_project" {
  operations = ["create", "update"]
  enforce {
    condition     = core::try(attrs.project_id, "") != ""
    error_message = "tfe_workspace must have project_id set."
  }
}
# Test
policytest { targets = ["workspace-require-project.policy.hcl"] }

resource "tfe_workspace" "with_project" {
  attrs = { project_id = "prj-123" }
}

resource "tfe_workspace" "missing_project" {
  expect_failure = true
  attrs          = {}
}

Update policy (reads both attrs and prior_attrs):

# Policy — block downgrades
resource_policy "tfe_workspace" "no_downgrade" {
  operations = ["update"]
  enforce {
    condition     = core::try(attrs.terraform_version, "") == core::try(prior_attrs.terraform_version, "")
                 || core::try(attrs.terraform_version, "") > core::try(prior_attrs.terraform_version, "")
    error_message = "terraform_version downgrade is not allowed."
  }
}
# Test
policytest { targets = ["workspace-no-downgrade.policy.hcl"] }

resource "tfe_workspace" "upgrade_ok" {
  attrs       = { terraform_version = "1.10.0" }
  prior_attrs = { terraform_version = "1.9.0" }
}

resource "tfe_workspace" "downgrade_blocked" {
  expect_failure = true
  attrs          = { terraform_version = "1.5.0" }
  prior_attrs    = { terraform_version = "1.9.0" }
}

Delete-gate policy (pre-change state only):

# Policy
resource_policy "tfe_workspace" "deny_delete_without_tag" {
  operations = ["delete"]
  locals {
    prior_tag_names = core::try(prior_attrs.tag_names, [])
  }
  enforce {
    condition     = core::contains(local.prior_tag_names, "delete")
    error_message = "Add 'delete' tag before destroying a workspace."
  }
}
# Test
policytest { targets = ["workspace-deny-delete-without-tag.policy.hcl"] }

resource "tfe_workspace" "has_delete_tag" {
  prior_attrs = { tag_names = ["delete", "prod"] }
}

resource "tfe_workspace" "missing_delete_tag" {
  expect_failure = true
  prior_attrs    = { tag_names = ["prod"] }
}

No-op policy (tfpolicy 0.4.0+, evaluates unchanged resources in state):

# Policy (operations omitted = ["create", "update", "no-op"])
resource_policy "aws_cloudtrail" "logging_enabled" {
  enforce {
    condition     = attrs.enable_logging == true
    error_message = "CloudTrail logging must be enabled."
  }
}
# Test
resource "aws_cloudtrail" "existing_trail" {
  meta  = { operation = "no-op" }
  attrs = { name = "existing-trail", s3_bucket_name = "my-bucket", enable_logging = true }
}

resource "aws_cloudtrail" "existing_trail_no_logging" {
  expect_failure = true
  meta           = { operation = "no-op" }
  attrs          = { name = "trail-without-logging", s3_bucket_name = "my-bucket", enable_logging = false }
}

Provider Schema Awareness

The structure of attrs = {} depends on provider schema. Consult provider docs to determine if attributes are blocks or direct values.

tfpolicy 0.3.0+: this is no longer just guidance — tfpolicy test preflights every attrs/prior_attrs value against the schemas resolved from required_providers before any test runs. An attribute that doesn't exist in the schema, or has the wrong shape/type (e.g. a block written as a map instead of a list-of-maps), fails preflight with a diagnostic and blocks the entire test run, not just the offending case.

Example - Blocks vs Attributes:

resource "aws_instance" "test" {
  attrs = {
    instance_type = "t2.micro"  # Direct attribute

    # Block (requires array of maps)
    default_tags = [{
      tags = {
        Environment = "Production"
      }
    }]
  }
}

In test files: Use = for blocks (not {} syntax used in policy files)

Cross-Resource References

Reference other test resources within the SAME file using resource_type.name.attrs.attribute:

resource "aws_security_group" "app_sg" {
  attrs = {
    name = "app-security-group"
  }
}

resource "aws_instance" "app_server" {
  attrs = {
    vpc_security_group_ids = [aws_security_group.app_sg.attrs.name]
  }
}

Limitation: References cannot span across test files.

The skip Attribute

Resources with skip = true:

  • Are added to resource graph
  • Are NOT evaluated by policies
  • CAN be referenced by other resources
  • ARE included in core::getresources() results
resource "aws_ebs_volume" "available_for_reference" {
  skip =