references/tfpolicy-author.md · 72000
s which resources/modules/providers to evaluate 2. locals - Computed once per filtered item 3. enforce - Each block evaluated; all must pass for policy to pass
Performance Best Practices
Critical for large configurations — choose the pattern based on what the filter depends on:
-
Top-level
core::getresources()only when the filter is a known literal/constant- Use when the filter value is a hardcoded string, a fixed ID, or another stable literal — not derived from
attrs.* - Executes once for the entire policy evaluation; result is reused by every
resource_policyblock - ❌ Do not use a top-level empty-filter call (
{}) and then filter byattrs.*insideresource_policy— that is the prohibited anti-pattern (O(N²) with silent correctness bugs)
locals { # OK — filter is a known literal, cached once for all resources all_buckets = core::getresources("aws_s3_bucket", {}) } resource_policy "aws_s3_bucket" "example" { locals { bucket_count = core::length(local.all_buckets) # Reuse cached value } } - Use when the filter value is a hardcoded string, a fixed ID, or another stable literal — not derived from
-
Inline
core::getresources()insideresource_policywhen the filter depends on the resource's own attribute- Use when "every parent must have at least one compliant child" and the linking key is
attrs.id,attrs.arn, orattrs.name - The filter value is unknown at plan time (it's the current resource's own attribute), so a top-level cache is impossible
- Executes once per evaluated resource (apply-time); the lookup fully resolves once the resource is provisioned
- This is not a performance compromise — it is the correct and required pattern for parent+child presence enforcement
# NOTE: This policy contains a cross-resource reference that will not resolve during # plan time, but the policy will run successfully during apply time. resource_policy "aws_s3_bucket" "s3_block_public_access" { locals { public_access_block = core::getresources("aws_s3_bucket_public_access_block", { bucket = attrs.id # filter depends on current resource — must be inline }) } enforce { condition = core::length(local.public_access_block) > 0 error_message = "S3 bucket must have a public access block resource." } } - Use when "every parent must have at least one compliant child" and the linking key is
-
Use
filterto reduce evaluation scope- Skip resources that don't need checking
- Significantly improves performance
See Advanced Patterns Guide for detailed performance guidance
Policy Types
1. resource_policy
Purpose: Validate Terraform resource configurations
resource_policy "aws_s3_bucket" "encryption_check" {
enforce {
condition = attrs.server_side_encryption_configuration != null
error_message = "S3 buckets must have encryption enabled"
}
}
Available attributes:
attrs.<attribute_name>- Resource attributes from configurationmeta.provider_type- Provider type (e.g.,aws)meta.tfe_stack.deployment_name,meta.tfe_stack.stack_name,meta.tfe_stack.deployment_group- Stack metadata for stack-scoped routing/exclusion workflows (tfpolicy 0.3.x+)- ⚠️
meta.addressis UNDEFINED forresource_policyin real plan evaluation — do not use it
⚠️ Understanding Provider Schema (Blocks vs Attributes):
Terraform providers expose their raw schema, where some attributes are blocks that require special handling:
# ❌ Wrong - blocks cannot be accessed directly
attrs.server_side_encryption_configuration.rules
# ✅ Correct - blocks are lists, use [0] index
attrs.server_side_encryption_configuration[0].rules
Common AWS provider blocks requiring [0] index:
default_tags[0].*(AWS provider configuration)assume_role[0].*(AWS provider configuration)versioning[0].enabled(S3 bucket)server_side_encryption_configuration[0].*(S3 bucket)metadata_options[0].*(EC2 instance)
Best practice: Always use core::length() checks before accessing blocks:
locals {
versioning_blocks = core::try(attrs.versioning, [])
versioning_enabled = core::length(local.versioning_blocks) > 0 ?
core::try(local.versioning_blocks[0].enabled, false) : false
}
See Verified Syntax Reference for complete details
Wildcards:
resource_policy "*" "all_resources" {
# Matches ALL resource types
}
2. module_policy
Purpose: Validate Terraform module sources and versions
# Check all modules use approved registry (prefix-based using core::regex)
module_policy "*" "module_source_check" {
filter = meta.source != null
locals {
# Prefix match: does source start with the approved namespace?
# core::contains() only does exact full-string matching — use core::regex() for prefix checks
is_approved = core::try(core::regex("^app\\.terraform\\.io/myorg/", meta.source), null) != null
}
enforce {
condition = local.is_approved
error_message = "Modules must use an approved registry source. Current source: ${meta.source}"
}
}
# Check specific module version with semver
module_policy "app.terraform.io/myorg/vpc/aws" "vpc_version" {
locals {
has_version = meta.version != null
meets_minimum = meta.version != null ? core::semverconstraint(meta.version, ">= 1.0.0") : false
}
enforce {
condition = local.meets_minimum
error_message = "VPC module must be >= 1.0.0, got ${meta.version != null ? meta.version : "no version"}"
}
}
Available attributes:
meta.source- Module source (e.g.,app.terraform.io/org/module/provider)meta.version- Module version (works withcore::semverconstraint()). Nullable on 0.5.0+:nullwhen no version is specified, so guard with a conditional (meta.version != null ? ... : false) and avoid interpolating it directly.meta.address- Module address (e.g.,module.vpc)
⚠️ Current Limitations (Private Beta):
- ❌
attrs.*(module inputs) NOT accessible yet - work in progress - ✅
meta.tfe_stackandmeta.tfe_workspace.tagsare available; Stack fields are empty strings outside Stack evaluations on 0.3.x/0.4.x andnullon 0.5.0+. - ❌
prior_attrsis a parse error inmodule_policy(0.5.0+); remove the reference.
Targeting:
- Use full module source to target specific module:
module_policy "app.terraform.io/myorg/vpc/aws" - Use
"*"wildcard to match all modules:module_policy "*" - ❌ Substring matching does NOT work:
module_policy "vpc"won't match modules with "vpc" in source
3. provider_policy
Purpose: Validate provider versions and configurations
provider_policy "aws" "version_check" {
locals {
minimum_version = "4.0.0"
}
enforce {
condition = meta.version != null ? core::semverconstraint(meta.version, ">= ${local.minimum_version}") : false
error_message = "AWS provider must be >= ${local.minimum_version}, got ${meta.version != null ? meta.version : "no version"}"
}
}
Available attributes:
meta.source- Full provider source (e.g.,registry.terraform.io/hashicorp/aws)meta.version- Provider version (e.g.,4.67.0)meta.alias- Provider alias.nullwhen no alias is configured on 0.5.0+ (empty string earlier);meta.alias == "x"comparisons are null-safe, but guard before passing it to functions or string templates.prior_attrsis a parse error inprovider_policy(0.5.0+); useattrs.attrs.*- Provider configuration attributes (region, profile, etc.)
Note:
meta.nameandmeta.typeare NOT confirmed available inreference/verified-syntax.md. Do not rely on them — usemeta.sourceto identify a provider andmeta.versionfor version checks.
Accessing provider configuration with attrs:
provider "aws" {
region = "us-west-2"
profile = "production"
}
provider_policy "aws" "region_check" {
locals {
aws_region = core::try(attrs.region, "")
allowed_regions = ["us-east-1", "us-west-2", "eu-west-1"]
}
enforce {
condition = core::contains(local.allowed_regions, local.aws_region)
error_message = "AWS provider must use approved region. Got: ${local.aws_region}"
}
}
⚠️ Provider configuration blocks require [0] index:
# AWS provider blocks (need [0] index)
attrs.default_tags[0].tags
attrs.assume_role[0].role_arn
attrs.endpoints[0].s3
Wildcards:
provider_policy "*" "all_providers" {
# Evaluates once per provider in configuration
}
Core Functions Reference
⚠️ String Function Limitations
Terraform Policy has VERY LIMITED string functions:
# ✅ Get string length
core::length(string)
# Example: core::length(attrs.description) > 0
# ✅ Join list into string
core::join(separator, list)
# Example: core::join(", ", local.allowed_versions)
✅ String functions available:
- ✅
core::startswith(string, prefix)- Returns bool; e.g.core::startswith(meta.version, ">")✅ - ✅
core::endswith(string, suffix)- Returns bool - ✅
core::contains_substring(string, substr)- Returns bool - ❌
core::contains(string, substring)- Does NOT work for strings (only lists!) - ✅
core::split(separator, string)- Splits string into list; e.g.core::split("-", "80-443")→["80", "443"]
✅ What IS Also Available — core::regex(pattern, string):
- Pattern and substring matching via
core::regex() - Important:
core::regex()throws on no match (does NOT return null) — always wrap withcore::try()
# Safe boolean pattern — use this idiom everywhere
locals {
# Substring check: does description contain "exception"?
has_exception = core::try(core::regex("NET-8 = exception", core::try(attrs.description, "")), null) != null
# Prefix check: does source start with approved namespace?
is_approved_source = core::try(core::regex("^app\\.terraform\\.io/myorg/", meta.source), null) != null
# Exact membership: still use core::contains() for lists
approved_types = ["gp3", "io1"]
is_approved_type = core::contains(local.approved_types, core::try(attrs.volume_type, ""))
}
Note: For prefix/suffix checking, prefer core::startswith() / core::endswith() over core::regex(). Use core::split() with core::parseint() for numeric string decomposition (e.g. port-range strings like "80-443").
List Functions
# Check if list contains value
core::contains(list, value)
# Example: core::contains(["dev", "staging", "prod"], attrs.environment)
# Get collection or string length (works on strings, lists, sets, maps!)
core::length(list_or_string_or_map)
# Example: core::length(local.violations) == 0
# Example: core::length(attrs.description) > 0 # String length!
# Example: core::length(attrs.tags) > 0 # Map key count
# Get map keys as list
core::keys(map)
# Example: core::keys(attrs.tags)
# Example: core::contains(core::keys(attrs.tags), "Environment")
# Check if any element is true — tfpolicy 0.3.0+: core::anytrue(list_of_booleans)
# On < 0.3.0: core::length([for b in list_of_booleans : b if b]) > 0
# Check if all elements are true — tfpolicy 0.3.0+: core::alltrue(list_of_booleans)
# On < 0.3.0: core::length([for b in list_of_booleans : b if !b]) == 0
Safe Access
# Try expression with fallback
core::try(expression, default_value)
# Example: core::try(attrs.encrypted, false)
# Example: core::try(meta.version, "0.0.0")
⚠️ CRITICAL: Cannot Check Attribute Existence Without try()
Direct attribute access fails when attributes don't exist, even with null checks:
# ❌ WRONG - Crashes with "This object does not have an attribute named 'region'"
has_region = attrs.region != null
# ✅ CORRECT - Two-step safe access pattern
region_value = core::try(attrs.region, null)
has_region = local.region_value != null
Why: Terraform Policy cannot test attribute existence before accessing (no "attr" in attrs syntax). Always use core::try() first, then check the result.
Semantic Versioning
# Compare version against constraint
core::semverconstraint(version, constraint_string)
# Example: core::semverconstraint(meta.version, ">= 4.0.0, < 5.0.0")
Resource Queries
# Query related resources
core::getresources(resource_type, filter_map)
# filter_map is REQUIRED. Pass {} to match everything, or { attr = value }
# for equality filtering. Caveat: candidates with unknown target
# attributes at plan time (e.g. references to to-be-created resource IDs)
# are conservatively included regardless of the filter value.
# Example: core::getresources("aws_security_group_rule", {})
⚠️ Filter caveat: core::getresources(type, { attr = value }) performs equality matching, but candidates whose target attribute is unknown at plan time (e.g. bucket = aws_s3_bucket.x.id for a resource being created in the same plan) are conservatively included. On first-time-create plans with cross-references you'll get every candidate back. Most reliable on update plans against existing infrastructure. See reference/verified-syntax.md.
CRITICAL: core::getresources() Attribute Access
Resources returned by core::getresources() have attributes at the top level (NOT through .attrs):
locals {
all_roles = core::getresources("aws_iam_role", {})
}
# ✅ CORRECT - Access attributes directly
role_names = [for role in local.all_roles : role.name]
filtered = [for role in local.all_roles : role if role.path == "/service/"]
# ❌ WRONG - Do NOT use .attrs
role_names = [for role in local.all_roles : role.attrs.name] # ERROR!
Why: This is DIFFERENT from current resource context where you use attrs.name. Returned resources have a different structure.
Pattern for Cross-Resource Validation:
resource_policy "aws_iam_role" "check" {
locals {
role_attachments = core::getresources("aws_iam_role_policy_attachment", {
role = attrs.name # filter depends on current resource — must be inline
})
has_attachment = core::length(local.role_attachments) > 0
}
}
Semantic Versioning
Constraint Operators
| Operator | Meaning | Example | Matches |
|----------|---------|---------|---------|
| = | Exact version | "= 4.67.0" | 4.67.0 only |
| != | Not equal | "!= 4.50.0" | Any except 4.50.0 |
| > | Greater than | "> 4.0.0" | 4.0.1, 4.1.0, 5.0.0, etc. |
| >= | Greater or equal | ">= 4.0.0" | 4.0.0, 4.0.1, 5.0.0, etc. |
| < | Less than | "< 5.0.0" | 4.99.99, 3.0.0, etc. |
| <= | Less or equal | "<= 5.0.0" | 5.0.0, 4.99.99, etc. |
| ~> | Pessimistic (patch) | "~> 4.67.0" | >= 4.67.0, < 4.68.0 |
| ~> | Pessimistic (minor) | "~> 4.0" | >= 4.0.0, < 5.0.0 |
Multiple Constraints (AND logic)
# Both constraints must be satisfied
core::semverconstraint(meta.version, ">= 4.0.0, < 5.0.0")
core::semverconstraint(meta.version, ">= 4.0.0, != 4.50.0")
OR Logic
locals {
# Version 4.x OR 5.x allowed
version_ok = core::semverconstraint(meta.version, "~> 4.0") ||
core::semverconstraint(meta.version, "~> 5.0")
}
Version Allowlist Pattern
locals {
allowed_versions = ["3.75.0", "3.80.0", "3.85.0"]
# Check if current version matches any allowed version
version_checks = [
for v in local.allowed_versions :
core::semverconstraint(meta.version, "= ${v}")
]
is_allowed = core::length([for b in local.version_checks : b if b]) > 0
}
enforce {
condition = local.is_allowed
error_message = "Version ${meta.version} not approved. Allowed: ${core::join(", ", local.allowed_versions)}"
}
Purpose: Common patterns for writing Terraform policies Status: All patterns verified during private beta (Updated: 2026-02-24)
Pattern 1: Required Attribute
resource_policy "aws_s3_bucket" "require_encryption" {
enforce {
condition = attrs.server_side_encryption_configuration != null
error_message = "S3 buckets must have encryption configured"
}
}
Pattern 2: Attribute Must Match Value
resource_policy "aws_ebs_volume" "encryption" {
enforce {
condition = core::try(attrs.encrypted, false) == true
error_message = "EBS volumes must be encrypted"
}
}
Pattern 3: Allowlist Check
resource_policy "aws_instance" "instance_type" {
locals {
allowed_types = ["t3.micro", "t3.small", "t3.medium"]
is_allowed = core::contains(local.allowed_types, attrs.instance_type)
}
enforce {
condition = local.is_allowed
error_message = "Instance type ${attrs.instance_type} not allowed. Use: ${core::join(", ", local.allowed_types)}"
}
}
Pattern 4: Tag Validation
resource_policy "*" "required_tags" {
filter = attrs.tags != null
locals {
required_tags = ["Environment", "Owner", "CostCenter"]
# Count tags that are MISSING; if zero, all required tags are present
missing_tags = [
for tag in local.required_tags :
tag if !core::contains(core::keys(attrs.tags), tag)
]
has_all_tags = core::length(local.missing_tags) == 0
}
enforce {
condition = local.has_all_tags
error_message = "Resources are missing required tags: ${core::join(", ", local.required_tags)}"
}
}
Pattern 5: Module Source Restriction
module_policy "*" "approved_sources" {
filter = meta.source != null
locals {
# Exact allowlist: use core::contains() for explicit full-source matching.
# For prefix matching use core::startswith(), for pattern matching use core::regex().
approved_sources = [
"app.terraform.io/myorg/vpc/aws",
"app.terraform.io/myorg/database/aws",
"app.terraform.io/myorg/network/aws",
"registry.terraform.io/hashicorp/vpc",
"registry.terraform.io/hashicorp/s3-bucket"
]
is_approved = core::contains(local.approved_sources, meta.source)
}
enforce {
condition = local.is_approved
error_message = "Module source not approved: ${meta.source}. Must be one of the explicitly allowed modules."
}
}
Note: core::contains() only supports exact full-string matching. For prefix or namespace matching, use core::regex():
# Prefix matching with core::regex() — matches any source under the approved namespace
locals {
is_approved_namespace = core::try(core::regex("^app\\.terraform\\.io/myorg/", meta.source), null) != null
}
enforce {
condition = local.is_approved_namespace
error_message = "Module source must be from app.terraform.io/myorg/ namespace. Got: ${meta.source}"
}
Pattern 6: Provider Version Range
provider_policy "aws" "version_range" {
locals {
min_version = "4.0.0"
max_version = "5.0.0"
version_ok = core::semverconstraint(meta.version, ">= ${local.min_version}, < ${local.max_version}")
}
enforce {
condition = local.version_ok
error_message = "AWS provider version ${meta.version} outside allowed range: >= ${local.min_version}, < ${local.max_version}"
}
}
Pattern 7: Conditional Enforcement
resource_policy "aws_s3_bucket" "conditional_encryption" {
locals {
# Only enforce encryption for production buckets
is_production = core::contains(core::keys(attrs.tags), "Environment") &&
attrs.tags["Environment"] == "production"
has_encryption = attrs.server_side_encryption_configuration != null
}
enforce {
# Skip check for non-production or enforce for production
condition = !local.is_production || local.has_encryption
error_message = "Production S3 buckets must have encryption enabled"
}
}
Pattern 8: Multiple Checks with Detailed Errors
resource_policy "aws_security_group" "security_checks" {
locals {
# tfpolicy 0.3.0+: core::anytrue([for rule in core::try(attrs.ingress, []) : (rule.from_port == 22 && core::contains(core::try(rule.cidr_blocks, []), "0.0.0.0/0"))]) works too.
# On < 0.3.0, use core::length() instead:
# Filter to SSH rules from internet; if list is non-empty, there's a violation
ssh_from_internet = [
for rule in core::try(attrs.ingress, []) :
rule if (rule.from_port == 22 && core::contains(core::try(rule.cidr_blocks, []), "0.0.0.0/0"))
]
has_ssh_ingress = core::length(local.ssh_from_internet) > 0
# Check for proper description
has_description = attrs.description != null && core::length(attrs.description) > 0
}
enforce {
condition = !local.has_ssh_ingress
error_message = "Security groups must not allow SSH from the internet (0.0.0.0/0)"
}
enforce {
condition = local.has_description
error_message = "Security groups must have a description"
}
}
Pattern 9: Provider Configuration Policies
Validate provider configuration attributes and blocks:
# Check provider region
provider_policy "aws" "approved_regions" {
locals {
aws_region = core::try(attrs.region, "")
allowed_regions = ["us-east-1", "us-west-2", "eu-west-1"]
}
enforce {
condition = core::contains(local.allowed_regions, local.aws_region)
error_message = "AWS provider must use approved region. Got: ${local.aws_region}"
}
}
# Check provider blocks (need [0] index)
provider_policy "aws" "enforce_default_tags" {
locals {
# Provider blocks are lists
default_tags = core::try(attrs.default_tags, [])
has_default_tags = core::length(local.default_tags) > 0
# Access block attributes with [0] index
tags = local.has_default_tags ?
core::try(local.default_tags[0].tags, {}) : {}
required_tags = ["Environment", "Owner", "CostCenter"]
tag_keys = core::keys(local.tags)
# tfpolicy 0.3.0+: core::alltrue([for tag in local.required_tags : core::contains(local.tag_keys, tag)]) works too.
# On < 0.3.0, use core::length() instead:
# Count required tags that are MISSING; if zero, all required tags are present
missing_required_tags = [
for tag in local.required_tags :
tag if !core::contains(local.tag_keys, tag)
]
has_all_required = core::length(local.missing_required_tags) == 0
}
enforce {
condition = local.has_default_tags
error_message = "AWS provider must configure default_tags block"
}
enforce {
condition = local.has_all_required
error_message = "AWS provider default_tags must include: ${core::join(", ", local.required_tags)}"
}
}
# Prevent hardcoded credentials
provider_policy "aws" "no_hardcoded_credentials" {
locals {
has_access_key = attrs.access_key != null
has_secret_key = attrs.secret_key != null
}
enforce {
condition = !local.has_access_key && !local.has_secret_key
error_message = "AWS provider must NOT use hardcoded credentials (access_key/secret_key). Use environment variables or IAM roles instead."
}
}
Key points:
attrs.*provides access to provider configuration- Provider blocks (default_tags, assume_role) require
[0]index - Version checking uses
meta.versionwithcore::semverconstraint() - Security checks (no hardcoded credentials) are important