references/verified-syntax.md
Terraform Policy - Verified Syntax Reference
Shared reference used by all sibling skills in
references/: tfpolicy-author | tfpolicy-test
Last Updated: 2026-02-24 Status: All patterns user-verified during private beta Purpose: Source-of-truth quick reference. Sub-skills link here rather than duplicating facts.
Critical Rules
1. ✅ Semantic Versioning (VERIFIED)
Rule: Use core::semverconstraint() for ALL version comparisons
# ✅ Correct
condition = core::semverconstraint(meta.version, ">= 4.0.0, < 5.0.0")
# ❌ Wrong
condition = meta.version >= 4.0 # Don't use direct comparison
Constraint syntax:
"= 4.67.0"- Exact version">= 4.0.0"- Minimum"< 5.0.0"- Maximum"~> 4.67.0"- Pessimistic patch (>= 4.67.0, < 4.68.0)"~> 4.0"- Pessimistic minor (>= 4.0.0, < 5.0.0)">= 4.0.0, < 5.0.0"- Multiple constraints (AND)"!= 4.50.0"- Exclude version
2. ✅ Core Function Prefix (VERIFIED)
Rule: ALL built-in Terraform functions require core:: prefix
# ✅ Correct
filter = core::try(attrs.encrypted, false) == true
is_allowed = core::length([for v in local.version_checks : v if v]) > 0
error_message = "Allowed: ${core::join(", ", local.allowed_versions)}"
# ❌ Wrong
filter = try(attrs.encrypted, false) == true # Missing core:: prefix
Common functions:
core::try(expr, default)- Safe access with fallbackcore::contains(list, value)- List membership (lists only, NOT strings!)core::length(list_or_string)- List/string/map length (✅ works on all!)core::keys(map)- Get map keys as list (✅ requires core:: prefix)core::join(separator, list)- Join list elementscore::semverconstraint(version, constraint)- Version comparisoncore::getresources(type, filter_map)- Query related resourcescore::alltrue(list)/core::anytrue(list)- Boolean collection helpers, available starting in tfpolicy 0.3.0. Seecore::alltrue()andcore::anytrue()for exact empty-list, unknown, and coercion behavior.
⚠️ IMPORTANT: core::getresources() filter behavior with unknown attribute values.
- The
filter_mapargument is required by the function signature (omitting it → "Not enough function arguments"). Passing{}matches everything; passing{ attr = value }performs equality matching. - Caveat: when the target attribute on a candidate resource is unknown at plan time (e.g.
bucket = aws_s3_bucket.x.idwhereaws_s3_bucket.xis being created in the same plan), the equality comparison evaluates to unknown and the engine conservatively includes that candidate in the result set. The filter is not "ignored" — but it cannot narrow results past any candidate whose target attribute is computed. - Verified on terraform 1.15.0-policy20261105 / tfpolicy 0.0.2-beta20260513 / tfpolicy-plugin 0.0.2-beta20260422.
- Production impact: any cross-resource policy on a first-time-create plan (where related resources reference each other via
.id) will see every candidate, not the matching one. Update plans against existing infrastructure (where target attributes are already known) filter correctly. - Pattern choice — constant filter vs.
attrs.*filter:- When the filter value is a known constant AND no secondary
attrs.*filtering is needed insideresource_policy: you MAY callcore::getresources()once in a top-levellocalsblock. A valid example is a truly account-level resource with no per-parent link:# ✅ CORRECT — aws_s3_account_public_access_block is account-level; no per-bucket link locals { account_pab = core::getresources("aws_s3_account_public_access_block", {}) } resource_policy "aws_s3_bucket" "account_block_required" { locals { pab = core::length(local.account_pab) > 0 ? local.account_pab[0] : null block_public_acls = local.pab != null ? core::try(local.pab.block_public_acls, false) : false } } - When the filter value comes from
attrs.*(e.g.attrs.id,attrs.name,attrs.arn) OR when any secondary filtering insideresource_policyis byattrs.*: use an inlinecore::getresources()call with the specific per-resource filter insideresource_policy. The top-level cache with a{}empty filter plus HCL-sideattrs.*filtering is the wrong pattern — see Mistake 13 CRITICAL note below.# ✅ CORRECT — filter value "table/${attrs.name}" comes from attrs.* — must be inline resource_policy "aws_dynamodb_table" "autoscaling_required" { locals { table_resource_id = "table/${attrs.name}" scaling_targets = core::getresources("aws_appautoscaling_target", { resource_id = local.table_resource_id }) } } # ❌ WRONG — top-level {} cache + HCL filter by attrs.* is the anti-pattern # locals { all_targets = core::getresources("aws_appautoscaling_target", {}) } # resource_policy "aws_dynamodb_table" { locals { filtered = [for t in local.all_targets : t if t.resource_id == "table/${attrs.name}"] } } -
⚠️ DynamoDB autoscaling is ALWAYS the inline pattern (Pattern B). Even pre-filtering at the top level by a constant
scalable_dimensiondoes not make it Pattern A — the secondaryresource_id == "table/${attrs.name}"filter insideresource_policyis still derived fromattrs.name, so the correct approach is an inlinecore::getresources()call filtered byresource_id. Pre-filtering byscalable_dimensionat the top level forces you to add theattrs.*-derivedresource_idfilter insideresource_policy, which is the anti-pattern. Use the inline call and apply the constantscalable_dimensioncheck as a simple HCL filter after the inline fetch.
- When the filter value is a known constant AND no secondary
- ⚠️ When the filter value is derived from
attrs.*and that attribute is unknown at plan time (e.g.bucket = aws_s3_bucket.x.idfor a newly-created resource), the equality comparison evaluates to unknown — the engine conservatively includes that candidate in the result set, so first-time-create plans with cross-references are unreliable. Most reliable on updates and existing infrastructure where target values are known. -
⛔ All dependent child resources — always use the inline filter pattern, NOT the top-level
{}cache. This applies toaws_s3_bucket_public_access_block,aws_s3_bucket_acl,aws_s3_bucket_server_side_encryption_configuration,aws_s3_bucket_policy,aws_appautoscaling_target,aws_appautoscaling_policy, and any resource type that has a(Required)or(Optional)argument referencing a parent resource. Callcore::getresources()inline inside the parentresource_policywith the specific filter (e.g.{bucket = attrs.id},{resource_id = local.table_resource_id}). Do NOT use the top-level cache{}+ HCL for-loop pattern for these types. See Mistake 13.
CRITICAL: core::getresources() Attribute Access:
- Resources returned have attributes at top level (NOT through
.attrs) - Example:
resource.name✅ NOTresource.attrs.name❌ - This is DIFFERENT from current resource context where you use
attrs.name - Pattern: For dependent child resources (any type with a
(Required)or(Optional)argument referencing a parent by.id,.arn, or.name): use inlinecore::getresources()insideresource_policywith the specific per-parent filter; access returned attributes directly at top level (NOT through.attrs). For truly independent/account-level resources: cache in top-levellocalswith a constant filter (if any), and access returned attributes directly.
✅ String functions available:
- ✅
core::startswith(string, prefix)- Returns bool. Arg order: full string first, prefix second (same as Sentinel'sstrings.has_prefix). e.g.core::startswith(meta.version, ">")✅ - ✅
core::endswith(string, suffix)- Returns bool - ✅
core::contains_substring(string, substr)- Returns bool - ✅
core::regex(pattern, string)- Pattern/substring matching. Throws on no match — wrap withcore::try():core::try(core::regex("pattern", string), null) != null - ✅
core::split(separator, string)- Splits a string into a list of substrings at each occurrence ofseparator. Example:core::split("-", "1-100")returns["1", "100"];core::split("-", "22")returns["22"]. Use withcore::parseint()to parse port ranges like"start-end"without regex:
Note: ternary short-circuits, so# ✅ Parsing a port range "start-end" using core::split (preferred over regex) port_parts = core::split("-", local.dest_port_range) range_start = core::length(local.port_parts) == 2 ? core::try(core::parseint(local.port_parts[0], 10), -1) : -1 range_end = core::length(local.port_parts) == 2 ? core::try(core::parseint(local.port_parts[1], 10), -1) : -1 # Range covers port 22 if start < 22 AND end > 22 (exclusive, matching Sentinel logic) is_range_ssh = local.range_start < 22 && local.range_end > 22core::parseintis only called whencore::length == 2. When the port string is not a range (e.g."22"or"*"),range_startandrange_enddefault to-1, making the range check false without any index-out-of-bounds risk. - ❌ Substring matching via
core::contains()— only works for lists, NOT strings# Prefix check using core::startswith() starts_with_open = core::startswith(local.version_value, ">") # Substring check using core::regex() has_exception = core::try(core::regex("exception", core::try(attrs.description, "")), null) != null
policy.required_providers is mandatory for resource and provider policy validation: A .policy.hcl file containing resource or provider policies must declare a top-level policy { required_providers { ... } } block. tfpolicy validate uses this block to resolve provider schemas for schema-aware validation, and validation fails when the block is omitted. See tfpolicy-author.md for concrete authoring examples.
Starting in tfpolicy 0.3.0, tfpolicy test reuses this same .policy.hcl declaration to validate provider, resource, and data-source policies, plus arguments used by core::getdatasource() and core::getresources(). It checks mocked values, including skip = true resource mocks, against the lowest and highest matching provider versions before evaluation. .policytest.hcl does not declare its own required_providers block — there is no policytest { required_providers { ... } } construct. See tfpolicy-test.md for details.
Validation limitations:
- Validation is best effort for version ranges. When a range is declared, provider schemas at the lower and upper bounds of the range are evaluated.
- Wildcard targets such as
resource_policy "*"are not schema-validated because they may match multiple resource types.
Provider version constraint checks: In provider_policy, meta.version is the resolved provider version (e.g. "6.50.0"), not the constraint string from required_providers. There is no tfpolicy surface that exposes the constraint string.
⚠️
providers-require-version-style Sentinel policies that checkstrings.has_prefix(p.version_constraint, ">")inspect the version constraint format string, which tfpolicy does not expose. This check is non-convertible. The closest tfpolicy equivalent enforces that the resolved provider version is within an approved range:
# Sentinel: strings.has_prefix(p.version_constraint, ">") → non-convertible
# TFPolicy nearest equivalent — enforce resolved version range instead:
provider_policy "*" "provider_version_range" {
enforce {
condition = core::semverconstraint(meta.version, ">= 4.0.0, < 5.0.0")
error_message = "Provider version '${meta.version}' must satisfy '>= 4.0.0, < 5.0.0'. Pin the provider to a tested version range to prevent major version upgrades."
}
}
⚠️ Arg order:
core::startswith(string, prefix)— the full string is the first argument, the prefix is the second. Do not reverse them.
✅ JSON functions available:
- ✅
core::jsondecode(string)— parses a JSON string into an HCL object/list. Use when an attribute contains a serialised JSON value (e.g. an inline IAM policy document). - ✅
core::jsonencode(value)— encodes an HCL object/list as a JSON string. - ❌
json::unmarshal— does not exist. There is nojson::namespace. Always usecore::jsondecodeinstead.locals { policy_doc = core::try(core::jsondecode(core::try(attrs.policy, "{}")), {}) statements = core::try(local.policy_doc.Statement, []) }
3. ✅ Policy Type Features (VERIFIED)
Rule: ALL policy types support the same features
| Feature | resource_policy | module_policy | provider_policy |
|---------|----------------|---------------|-----------------|
| locals {} | ✅ Yes | ✅ Yes | ✅ Yes |
| filter clause | ✅ Yes | ✅ Yes | ✅ Yes |
| Multiple enforce | ✅ Yes | ✅ Yes | ✅ Yes |
IMPORTANT: Language server shows FALSE ERRORS for locals in provider_policy
- Error: "No declaration found for local.variable"
- These are safe to ignore - syntax is valid
- Runtime evaluation works correctly
4. ✅ CRITICAL: Blocks vs Attributes Schema Distinction
Rule: Provider schema representation determines how you access nested configuration
Blocks vs Attributes:
- BLOCKS → Represented as lists of maps (even if only one allowed)
- Require array indexing:
attrs.block_name[0].field - Examples:
default_tags,assume_role,lifecycle
- Require array indexing:
- ATTRIBUTES → Represented as direct values (maps, strings, numbers, etc.)
- Direct access:
attrs.attribute_name - Examples:
region,tags,instance_type
- Direct access:
Examples:
# ✅ BLOCK access (default_tags in AWS provider)
# Schema: default_tags = [ { tags = { "Env" = "Dev" } } ]
default_tags_map = core::try(attrs.default_tags[0].tags, {}) # Need [0] index
# ✅ ATTRIBUTE access (tags on resources)
# Schema: tags = { "Env" = "Dev" }
has_tags = attrs.tags != null && core::length(attrs.tags) > 0 # Direct access, no [0]
# Note: core::length() works directly on maps, no need for core::keys()
How to determine Block vs Attribute:
- Check provider schema documentation
- Use
terraform consoleto inspect structure - If accessing nested field fails without
[0], it's a Block
5. ✅ Input Blocks — Runtime Parameterization (VERIFIED)
Rule: Use input blocks instead of hardcoded locals for values that vary per policy set. Never claim Sentinel param cannot be replicated — input is the direct equivalent.
# ✅ Correct — parameterized, overridable per policy set
input "allowed_providers" {
type = list(string)
default = ["registry.terraform.io/hashicorp/aws"]
}
provider_policy "*" "providers_allowlist" {
enforce {
condition = core::contains(input.allowed_providers, meta.source)
error_message = "Provider '${meta.source}' not allowed. Permitted: ${core::join(", ", input.allowed_providers)}."
}
}
# ❌ Wrong — hardcoding what should be configurable
locals {
allowed_providers = ["registry.terraform.io/hashicorp/aws"] # Never override without editing policy file
}
Supported types: string, number, bool, list(string), list(number), map(string)
Override mechanism: .tfpolicy.metadata.json at policy-set scope, or per-evaluation overrides.
Use for: allowlists, blocklists, version constraints, limits, thresholds — any value the operator may want to tune.
6. ✅ Operations Scoping + prior_attrs (VERIFIED)
Rule: Use operations = [...] to restrict when a policy fires. Use prior_attrs to read pre-change state on delete/update. (tfpolicy 0.4.0+ adds the "no-op" operation.)
# ✅ Fires only on create and update — never on destroy
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."
}
}
# ✅ Delete-gate: check prior state before workspace is destroyed
resource_policy "tfe_workspace" "deny_delete_without_tag" {
operations = ["delete"] # prior_attrs requires operations limited to update and/or delete
locals {
prior_tag_names = core::try(prior_attrs.tag_names, [])
had_delete_tag = core::contains(local.prior_tag_names, "delete")
}
enforce {
condition = local.had_delete_tag
error_message = "Add 'delete' tag before destroying a workspace."
}
}
Key rules:
operations = ["create", "update"]— skips destroy and, on 0.4.0+, unchanged resources; on 0.3.x it is equivalent to Sentinelrc.change.actions is not ["delete"], but on 0.4.0+ omitoperationsto match it, since Sentinel'sresource_changesalso includes unchanged resourcesoperations = ["delete"]— fires only on destroy;prior_attrsholds the before-stateoperations = ["no-op"](0.4.0+) — fires only on resources the run leaves unchanged;attrsholds the existing values andprior_attrsis unavailableprior_attrsis only available whenoperationsis limited to"update"and/or"delete"; it is never available for"create"or"no-op"- Default (no
operations): 0.4.0+ = fires on create, update, and no-op for policies that do not referenceprior_attrs(policies that referenceprior_attrsmust setoperationsexplicitly); 0.3.x = create and update. On 0.4.0+, useoperations = ["create", "update"]to skip unchanged resources - A policy cannot list
"delete"together with"create"or"no-op"inoperations. Replacement plans are evaluated as separate delete and create operations, so split policies targeting both operations into separateresource_policyblocks. - On 0.4.0+, an attrs-only policy that calls
core::getresourcesand omitsno-opfromoperationsloads with a warning; addno-opunless changes-only is intended
7. ✅ Time Functions (VERIFIED)
Rule: core::timestamp(), core::formatdate(), and core::parseint() exist. Never generate placeholder policies claiming time functions are unavailable.
# ✅ Day-of-week restriction
input "restricted_weekdays_utc" {
type = list(string)
default = ["Friday", "Saturday", "Sunday"]
}
resource_policy "tfe_workspace" "deny_apply_day_of_week" {
locals {
current_weekday = core::formatdate("EEEE", core::timestamp()) # "Monday", "Friday", etc.
is_restricted = core::contains(input.restricted_weekdays_utc, local.current_weekday)
}
enforce {
condition = !local.is_restricted
error_message = "Apply blocked on ${local.current_weekday} (UTC). Restricted days: ${core::join(", ", input.restricted_weekdays_utc)}."
}
}
# ✅ Hour-of-day restriction
input "restricted_hours_utc" {
type = list(number)
default = [8, 9, 10, 11, 12]
}
resource_policy "tfe_workspace" "deny_apply_hour_of_day" {
locals {
current_hour = core::parseint(core::formatdate("HH", core::timestamp()), 10)
is_restricted = core::contains(input.restricted_hours_utc, local.current_hour)
}
enforce {
condition = !local.is_restricted
error_message = "Apply blocked during hour ${local.current_hour} UTC."
}
}
Available time functions:
core::timestamp()— current UTC time as RFC3339 stringcore::formatdate(spec, timestamp)— format specifiers:"EEEE"(weekday name),"HH"(hour 00-23),"DD"(day),"MM"(month),"YYYY"(year)core::timeadd(timestamp, duration)— add duration (e.g."24h","-1h")core::timecmp(ts1, ts2)— compare two timestampscore::parseint(string, base)— parse string to integer (e.g.core::parseint("08", 10)→8)- Note: All times are UTC. Express restricted windows in UTC.
8. ✅ Naming Conventions (VERIFIED)
resource_policy block names — use snake_case derived from the enforcement requirement:
# ✅ Correct — descriptive snake_case
resource_policy "aws_s3_bucket" "versioning_required" { }
resource_policy "aws_iam_policy" "no_admin_privileges" { }
resource_policy "aws_ecs_task_definition" "secure_networking_mode_and_user" { }
# ❌ Wrong — generic names that don't describe the check
resource_policy "aws_s3_bucket" "check" { }
resource_policy "aws_s3_bucket" "all_checks" { }
resource_policy "aws_s3_bucket" "policy" { }
Rules:
- Use
snake_case(underscores, lowercase). Never use kebab-case (hyphens) in block names. - Name should reflect the enforcement requirement, not the resource type (the type is already in the first argument).
- When a single resource type has multiple enforce blocks (the correct pattern), choose one name that describes the combined requirement rather than the individual checks.
- For IAM 4-type rules, use the same
policy_nameacross all 4 blocks (e.g.no_admin_privileges) — the resource type in the first argument differentiates them.
9. ✅ core::try() Default Type Selection (VERIFIED)
Choose the default value based on the semantic type of the attribute — do NOT mix defaults for the same attribute across related checks:
| Attribute type | Correct default | Rationale |
|---|---|---|
| Boolean | false | Absent boolean = permissive default (fails the check correctly) |
| Required string | "" | Absent string = empty = fails non-empty checks correctly |
| List / set | [] | Absent list = empty = length checks correctly return 0 |
| Map / object | {} | Absent map = empty = key lookups return null |
| "Must detect unset separately from empty" | null | When "" and null must be treated differently by the condition |
# ✅ Correct defaults by type
encrypted = core::try(attrs.encrypted, false) # boolean
bucket_name = core::try(attrs.bucket, "") # string
tag_names = core::try(attrs.tag_names, []) # list
tags = core::try(attrs.tags, {}) # map
optional_config = core::try(attrs.config, null) != null # detect presence
⚠️ Using the wrong default silently masks violations:
core::try(attrs.encrypted, true)— absent = treated as encrypted = violation missedcore::try(attrs.tag_names, ["compliant"])— absent = treated as tagged = violation missed
Common Mistakes to Avoid
❌ Mistake 1: Direct Version Comparison
# Wrong
condition = meta.version < 5.0
Fix: Use core::semverconstraint(meta.version, "< 5.0.0")
❌ Mistake 2: Direct Attribute Access Without try()
# Wrong - Crashes when attribute doesn't exist
has_region = attrs.region != null
# Wrong - Still crashes even with double check!
condition = attrs.encrypted != null && attrs.encrypted == true
Fix: Use two-step safe access pattern:
# Correct
region_value = core::try(attrs.region, null)
has_region = local.region_value != null
Why: Cannot test attribute existence before accessing (no "attr" in attrs syntax). Must use core::try() first.
❌ Mistake 4: Trusting Language Server Errors
# Language server shows error, but syntax is valid:
provider_policy "aws" "example" {
locals { # ❌ False error: "No declaration found"
version_check = ...
}
}
Fix: Ignore language server errors for locals in provider_policy - they're false positives
❌ Mistake 6: Filter Without Length Check
# Suboptimal - doesn't filter empty collections
filter = attrs.ingress != null
# Better - filters both null and empty
filter = attrs.ingress != null && core::length(attrs.ingress) > 0
Fix: Check both null and length for better performance
❌ Mistake 7: Multi-line Boolean Expressions
# Wrong - causes syntax errors
is_exact = local.has_version &&
!core::contains(meta.version, "~