references/verified-syntax.md · 72000
is especially important for objects: if the true branch returns an object with key K, the false branch must also include key K with a compatible type. Mismatched object shapes cause a compile-time type error. Use a consistent fallback object (e.g. { Statement = [] }) or avoid the ternary by using core::try directly on the full expression.
❌ Mistake 32: inputs Block Inside a Resource Test Block
Error: An argument named "inputs" is not expected here. Did you mean to define a block of type "inputs"?
# ❌ WRONG — inputs block placed INSIDE a resource test block
resource "aws_db_instance" "pass_instance" {
inputs = { # ❌ inputs is not valid inside resource {}
resource_type = "aws_db_instance"
source_type = "db-instance"
}
attrs = { ... }
}
# ✅ CORRECT — inputs is a TOP-LEVEL block in the policytest file,
# and it applies to ALL test cases in that file
policytest {
targets = ["my-policy.policy.hcl"]
}
inputs { # ✅ top-level block, applies to all resources below
resource_type = "aws_db_instance"
source_type = "db-instance"
}
resource "aws_db_instance" "pass_instance" {
attrs = { ... }
}
Rule: The inputs {} block is a top-level construct in a .policytest.hcl file. It overrides input block defaults for every test case in that file. It is not an attribute or a nested block inside resource, data, or module test blocks. If you need different input values for different test resources, put them in separate .policytest.hcl files, each with its own top-level inputs {} block.
❌ Mistake 33: data_policy Block Type Does Not Exist
Error: Blocks of type "data_policy" are not expected here.
# ❌ WRONG — data_policy is NOT a valid policy block type
data_policy "aws_iam_policy_document" "permissive_actions_denied" {
enforce {
condition = local.no_star_actions
error_message = "IAM policy documents must not use wildcard actions."
}
}
# ✅ CORRECT — use resource_policy for actual Terraform resources
# To check IAM policy content, parse the inline_policy or the policy document
# that is attached to an actual resource (aws_iam_policy, aws_iam_role, etc.)
resource_policy "aws_iam_policy" "permissive_actions_denied" {
locals {
policy_doc = core::try(core::jsondecode(core::try(attrs.policy, "{}")), { Statement = [] })
statements = core::try(local.policy_doc.Statement, [])
star_stmts = [for s in local.statements : s if core::contains(core::try(s.Action, []), "*")]
no_star_actions = core::length(local.star_stmts) == 0
}
enforce {
condition = local.no_star_actions
error_message = "IAM managed policies must not use wildcard (*) actions."
}
}
Rule: The only valid top-level policy block types are:
resource_policy "<resource_type>" "<name>"— evaluates Terraform-managed resourcesmodule_policy "<source_path>" "<name>"— evaluates Terraform modulesprovider_policy "<provider_type>" "<name>"— evaluates provider configuration
data_policy does not exist. Data sources (e.g. aws_iam_policy_document, aws_caller_identity) are not evaluated via policy blocks. To enforce content constraints on IAM documents, write a resource_policy that targets the resource (aws_iam_policy, aws_iam_role, etc.) and parses the policy attribute using core::jsondecode.
❌ Mistake 34: Duplicate Local Variable or Policy Block Definitions
Error (duplicate local): The local expression "..." is already defined. Each local expression must have a unique name.
Error (duplicate policy block): The resource block "..." is already defined. Each resource_policy block must have a unique resource type + name combination.
# ❌ WRONG — same local variable name defined twice in the same locals {} block
resource_policy "aws_vpc" "flow_logging_enabled" {
locals {
flow_logs = core::getresources("aws_flow_log", {})
matching_logs = [for fl in local.flow_logs : fl if fl.vpc_id == attrs.id]
flow_logs = core::try(attrs.enable_dns_support, false) # ❌ duplicate name!
}
enforce { ... }
}
# ❌ WRONG — same resource_policy block defined twice (same type + name)
resource_policy "aws_vpc" "flow_logging_enabled" {
locals { ... }
enforce { condition = ... }
}
resource_policy "aws_vpc" "flow_logging_enabled" { # ❌ duplicate!
locals { ... }
enforce { condition = ... }
}
# ✅ CORRECT — unique local names + all checks in a single resource_policy block
# Fixes both mistakes above:
# 1. Each local has a distinct name (flow_logs vs dns_support) — no duplicate-name error.
# 2. Both checks live in one "aws_vpc" / "flow_logging_enabled" block with two enforce
# blocks — no duplicate-policy-block error.
# NOTE: aws_flow_log.vpc_id links to the parent VPC — filter inline by attrs.id; never use
# a top-level core::getresources("aws_flow_log", {}) + HCL for-loop filter (Mistake 13).
resource_policy "aws_vpc" "flow_logging_enabled" {
locals {
flow_logs = core::getresources("aws_flow_log", { vpc_id = attrs.id })
dns_support = core::try(attrs.enable_dns_support, false) # unique name — no conflict
has_flow_log = core::length(local.flow_logs) > 0
}
enforce {
condition = local.has_flow_log
error_message = "VPC must have at least one flow log configured."
}
enforce {
condition = local.dns_support
error_message = "VPC must have DNS support enabled."
}
}
Rules:
- Within a single
locals {}block, every local variable name must be unique. If you copy-paste or refactor, check for accidental name reuse. - Within a single policy file, every
resource_policy "type" "name"combination must be unique. To add multiple checks on the same resource type, either add moreenforceblocks to the existing policy block, or use a differentnamelabel (e.g."flow_logging_enabled"vs"flow_logging_destination").
❌ Mistake 35: Using || Chains for Enum/Allowlist Checks Instead of core::contains()
Problem: When checking if an attribute value belongs to a set of allowed values, chaining || comparisons is verbose, harder to maintain, and doesn't match idiomatic TF Policy style.
# ❌ WRONG — verbose chain, hard to maintain
locals {
ssl_mode = core::try(attrs.ssl_mode, null)
is_valid = local.ssl_mode == "require" || local.ssl_mode == "verify-ca" || local.ssl_mode == "verify-full"
}
# ✅ CORRECT — core::contains() with a named list local
locals {
ssl_mode = core::try(attrs.ssl_mode, "none")
valid_modes = ["require", "verify-ca", "verify-full"]
is_valid = core::contains(local.valid_modes, local.ssl_mode)
}
enforce {
condition = local.is_valid
error_message = "Attribute 'ssl_mode' must be one of: require, verify-ca, verify-full."
}
Rules:
- Whenever a Sentinel policy uses
value in [list]orvalue in set([...]), always translate tocore::contains(allowed_list, value)in TF Policy. - Store the allowed list in a named local variable (e.g.,
valid_modes) for readability. core::contains(list, null)is safe — it returnsfalsewhen value isnull. No extra null guard is needed before callingcore::contains().- Use a non-null default in
core::try()(e.g.,core::try(attrs.ssl_mode, "none")) sonullattribute values map to a clearly non-compliant default.
❌ Mistake 36: Using Multiple core::startswith() Calls for Version Range Matching Instead of core::regex()
Problem: When a Sentinel policy checks a version string with >= or < (e.g., engine_version < "6.0"), HCL does not support string comparison operators. Using multiple core::startswith() calls for each major version is verbose and brittle — it will break if a new major version prefix appears (e.g., "0.x" or "10.x").
# ❌ WRONG — 5 separate startswith calls for versions 1.x through 5.x
locals {
is_version_lt_6 = (
core::startswith(local.engine_version, "1.") ||
core::startswith(local.engine_version, "2.") ||
core::startswith(local.engine_version, "3.") ||
core::startswith(local.engine_version, "4.") ||
core::startswith(local.engine_version, "5.")
)
}
# ✅ CORRECT — core::regex() matches all versions with major version 1–5 in one expression
# Use in filter to skip resources where engine_version is >= 6.0 or unset
filter = core::try(attrs.engine_version, "") != "" &&
core::try(core::regex("^[1-5]\\.", core::try(attrs.engine_version, "")), null) != null
locals {
auth_token = core::try(attrs.auth_token, "")
}
enforce {
condition = local.auth_token != null && local.auth_token != ""
error_message = "Attribute 'auth_token' must be set when 'engine_version' < 6.0."
}
Rules:
- When a Sentinel policy compares a version string with
<or>=, identify the version boundary and translate tocore::regex(). - Always wrap in
core::try(..., null)—core::regex()returnsnullon no match (notfalse), and calling it on a null input causes an error. - Common patterns:
- Versions
< 6.0(major 1–5):core::regex("^[1-5]\\.", version) - Versions
>= 2.xand< 10.x:core::regex("^[2-9]\\.", version) - Patch versions like
"5.0.6"or"6.x"are handled correctly by the major-version prefix pattern.
- Versions
- Prefer
core::semverconstraint()if the version string is a proper SemVer (e.g.,"6.2.0"); usecore::regex()only for non-standard version strings (e.g.,"6.x","5.0.6"from AWS ElastiCache engine versions). - Never use
>,<,>=,<=on strings in HCL — HCL string comparison is lexicographic and unreliable for version ordering.
❌ Mistake 37: Anchoring resource_policy on an Optional Companion Resource Instead of the Parent
Problem: When a Sentinel policy checks an S3 companion resource (e.g., aws_s3_bucket_public_access_block), it is tempting to write resource_policy "aws_s3_bucket_public_access_block". However, this companion resource is optional — a bucket can exist in a Terraform plan with no aws_s3_bucket_public_access_block at all. Anchoring on the companion means buckets with no companion resource silently pass the policy.
# ❌ WRONG — anchored on the companion type; buckets with no public_access_block resource silently pass
resource_policy "aws_s3_bucket_public_access_block" "block_public_access" {
locals {
block_public_acls = core::try(attrs.block_public_acls, false)
}
enforce {
condition = local.block_public_acls == true
error_message = "S3 bucket must block public ACLs."
}
}
# ✅ CORRECT — anchored on the parent; a missing companion resource = false → violation is caught
# NOTE: apply-time cross-resource reference; resolves correctly at apply time.
resource_policy "aws_s3_bucket" "block_public_access" {
locals {
public_access_block = core::getresources("aws_s3_bucket_public_access_block", {
bucket = attrs.id
})
block_public_acls = core::try(local.public_access_block[0].block_public_acls, false)
block_public_policy = core::try(local.public_access_block[0].block_public_policy, false)
ignore_public_acls = core::try(local.public_access_block[0].ignore_public_acls, false)
restrict_public_buckets = core::try(local.public_access_block[0].restrict_public_buckets, false)
}
enforce {
condition = local.block_public_acls && local.block_public_policy && local.ignore_public_acls && local.restrict_public_buckets
error_message = "S3 bucket '${attrs.bucket}' must have all four public access block settings enabled."
}
}
Rules:
- Always ask: "Can the parent (
aws_s3_bucket) exist in a Terraform plan WITHOUT this companion?" If YES → anchor on the parent, not the companion. - The following S3 companions MUST always be checked via
resource_policy "aws_s3_bucket":aws_s3_bucket_public_access_block— lookup:{ bucket = attrs.id }(apply-time inline)aws_s3_bucket_acl— use parent anchor when enforcing that every bucket has a compliant ACL; use directresource_policy "aws_s3_bucket_acl"only when checking ACL's own attribute values on ACLs that already existaws_s3_bucket_logging— lookup:{ bucket = attrs.id }(apply-time inline)aws_s3_bucket_server_side_encryption_configuration— lookup:{ bucket = attrs.id }(apply-time inline)aws_s3_bucket_versioning— plan-time: top-levelcore::getresources, filter byv.bucket == attrs.bucket
- The Sentinel source pattern does not matter. Even if the original Sentinel iterates over companion resource types, the TFPolicy MUST anchor on the parent.
- Requirement translation: If requirement.txt says "every
aws_s3_bucket_public_access_blockmust have X = true", reframe it as "everyaws_s3_bucketmust have a companionaws_s3_bucket_public_access_blockwith X = true; a missing companion is a violation." This reframing is mandatory before writing HCL. - Use apply-time inline
core::getresources("companion", { bucket = attrs.id })inside theresource_policy "aws_s3_bucket"block.
❌ Mistake 38: Checking Only aws_iam_policy for IAM Content Rules — Missing Inline Policy Resource Types
Symptom: Policy only checks aws_iam_policy for privilege conditions (e.g. "no admin *:*") but misses inline policies attached directly to roles, users, and groups.
# ❌ INCOMPLETE — only catches standalone managed policies
resource_policy "aws_iam_policy" "no_admin_privileges" {
locals {
statements = core::try(core::jsondecode(core::try(attrs.policy, "{}")).Statement, [])
admin_stmts = [for s in local.statements : s if ...]
}
enforce { condition = core::length(local.admin_stmts) == 0 ... }
}
# Missing: aws_iam_role_policy, aws_iam_user_policy, aws_iam_group_policy
# ✅ CORRECT — cover all 4 inline policy resource types; each has attrs.policy (JSON string)
# Each resource_policy block is fully self-contained — attrs is only available inside a
# resource_policy, module_policy, or provider_policy block, not in top-level locals.
resource_policy "aws_iam_policy" "no_admin_privileges" {
locals {
statements = core::try(core::jsondecode(core::try(attrs.policy, "{}")).Statement, [])
admin_stmts = [for s in local.statements : s if core::lower(core::try(s.Effect, "Allow")) == "allow" && core::contains(core::try(s.Action, []), "*") && core::contains(core::try(s.Resource, []), "*")]
}
enforce {
condition = core::length(local.admin_stmts) == 0
error_message = "IAM policies must not grant full admin privileges (*:* on *)."
}
}
resource_policy "aws_iam_role_policy" "no_admin_privileges" {
locals {
statements = core::try(core::jsondecode(core::try(attrs.policy, "{}")).Statement, [])
admin_stmts = [for s in local.statements : s if core::lower(core::try(s.Effect, "Allow")) == "allow" && core::contains(core::try(s.Action, []), "*") && core::contains(core::try(s.Resource, []), "*")]
}
enforce {
condition = core::length(local.admin_stmts) == 0
error_message = "IAM role inline policies must not grant full admin privileges (*:* on *)."
}
}
resource_policy "aws_iam_user_policy" "no_admin_privileges" {
locals {
statements = core::try(core::jsondecode(core::try(attrs.policy, "{}")).Statement, [])
admin_stmts = [for s in local.statements : s if core::lower(core::try(s.Effect, "Allow")) == "allow" && core::contains(core::try(s.Action, []), "*") && core::contains(core::try(s.Resource, []), "*")]
}
enforce {
condition = core::length(local.admin_stmts) == 0
error_message = "IAM user inline policies must not grant full admin privileges (*:* on *)."
}
}
resource_policy "aws_iam_group_policy" "no_admin_privileges" {
locals {
statements = core::try(core::jsondecode(core::try(attrs.policy, "{}")).Statement, [])
admin_stmts = [for s in local.statements : s if core::lower(core::try(s.Effect, "Allow")) == "allow" && core::contains(core::try(s.Action, []), "*") && core::contains(core::try(s.Resource, []), "*")]
}
enforce {
condition = core::length(local.admin_stmts) == 0
error_message = "IAM group inline policies must not grant full admin privileges (*:* on *)."
}
}
Rule: Any IAM content enforcement (wildcard actions, admin privileges, etc.) MUST cover all 4 inline policy resource types:
| Resource type | When it's used | policy attribute |
|---|---|---|
| aws_iam_policy | Standalone managed policy | JSON string |
| aws_iam_role_policy | Inline policy attached to a role | JSON string |
| aws_iam_user_policy | Inline policy attached to a user | JSON string |
| aws_iam_group_policy | Inline policy attached to a group | JSON string |
All 4 have the same attrs.policy JSON string — use core::jsondecode(core::try(attrs.policy, "{}")) on each.
Note on aws_iam_policy_document: This is a Terraform DATA SOURCE. data_policy does not exist in tfpolicy (see Mistake 31). Do NOT write a resource_policy "aws_iam_policy_document" to enforce IAM content — use the 4 managed/inline resource types above instead.
❌ Mistake 39: Repeating core::try() Calls in Complex For-Loop Predicates
Problem: When a for...if list comprehension has a complex filter predicate that references the same attribute multiple times via core::try() (e.g. core::try(rule.from_port, 0), core::try(rule.to_port, 0), core::try(rule.protocol, "") each appearing 3–5 times), the expression becomes an unreadable single line that is hard to maintain and verify.
# ❌ WRONG — core::try(rule.from_port, 0) appears 4 times; core::try(rule.to_port, 0) appears
# 4 times; core::try(rule.protocol, "") appears 5 times in one predicate.
violating_rules = [for rule in local.ingress_rules : rule if (core::contains(core::try(rule.cidr_blocks, []), "0.0.0.0/0") || core::contains(core::try(rule.ipv6_cidr_blocks, []), "::/0")) && (core::try(rule.protocol, "") == "all" || core::try(rule.protocol, "") == "-1" || (core::try(rule.protocol, "") == "tcp" && core::length([for p in input.authorized_tcp_ports : p if p >= core::try(rule.from_port, 0) && p <= core::try(rule.to_port, 0)]) != (core::try(rule.to_port, 0) - core::try(rule.from_port, 0) + 1)) || (core::try(rule.protocol, "") == "udp" && core::length([for p in input.authorized_udp_ports : p if p >= core::try(rule.from_port, 0) && p <= core::try(rule.to_port, 0)]) != (core::try(rule.to_port, 0) - core::try(rule.from_port, 0) + 1)))]
# ✅ CORRECT — two-phase approach: map items to enriched objects (extract sub-expressions
# into named fields), then filter on those named fields.
locals {
enriched_rules = [for rule in local.ingress_rules : {
rule = rule
has_public_ip = core::contains(core::try(rule.cidr_blocks, []), "0.0.0.0/0") || core::contains(core::try(rule.ipv6_cidr_blocks, []), "::/0")
protocol = core::try(rule.protocol, "")
from_port = core::try(rule.from_port, 0)
to_port = core::try(rule.to_port, 0)
}]
violating_rules = [for r in local.enriched_rules : r.rule if r.has_public_ip && (r.protocol == "all" || r.protocol == "-1" || (r.protocol != "tcp" && r.protocol != "udp") || (r.protocol == "tcp" && core::length([for p in input.authorized_tcp_ports : p if p >= r.from_port && p <= r.to_port]) != (r.to_port - r.from_port + 1)) || (r.protocol == "udp" && core::length([for p in input.authorized_udp_ports : p if p >= r.from_port && p <= r.to_port]) != (r.to_port - r.from_port + 1)))]
}
When to use the two-phase pattern:
- A single field is referenced 3 or more times in the predicate via
core::try()(each call is a repeated sub-expression). - The predicate contains a nested for-loop that re-accesses the same outer-loop variable.
- The resulting predicate is too long to comfortably fit on a single line (required by Mistake 7).
Benefits:
- Each
core::try()call is written exactly once — no repeated accesses. - Named fields (
r.from_port,r.protocol) are self-documenting. - The filter predicate is shorter and the structure matches the original Sentinel logic.
- Easier to debug: inspect
local.enriched_rulesdirectly to see computed intermediate values.
Rule summary: When a for-loop predicate repeats the same core::try(rule.field, default) call more than twice, split into two steps: (1) map items to enriched objects with computed fields, (2) filter on those fields. See also the "Multi-Stage Filtering for Readability" best practice below.
Best Practices
✅ Provider Schema Awareness
Rule: tfpolicy exposes raw provider schemas without transformation
Implication: You need to understand the actual provider schema:
- Sets remain sets (not converted to lists)
- Know whether attributes are optional
- Understand nested object structures
Example:
# attrs.ingress is a SET (per AWS provider), but iteration works the same
for rule in attrs.ingress : rule.from_port
Tip: Use terraform console or provider docs to inspect schemas
✅ Filter Pattern: Null + Length Check
Rule: Always check both null and length for collection filters; wrap both accesses when the attribute may be absent from policytest mocks
# ✅ Best practice — safe in real plans AND policytest mocks that omit the attribute
filter = core::try(attrs.ingress, null) != null && core::try(core::length(attrs.ingress), 0) > 0
# ✅ Also correct — pre-capture ensures the second operand references a local (never absent)
# local.ingress_raw = core::try(attrs.ingress, null)
# filter = local.ingress_raw != null && core::length(local.ingress_raw) > 0
# ⚠️ Works but less efficient (doesn't filter empty collections)
filter = core::try(attrs.ingress, null) != null
# ❌ RISKY — second attrs.ingress access is not wrapped; fails in policytest mocks
# that completely omit the attribute (where attrs is a strict HCL object without the key)
filter = core::try(attrs.ingress, null) != null && core::length(attrs.ingress) > 0
Why: In real Terraform plan evaluation, absent optional attributes are represented as null in the resource schema, and filter && short-circuits after null != null = false. In policytest mocks however, if the mock omits an attribute, attrs is a strict HCL literal — the attribute genuinely does not exist, and the bare second access throws an error that && does not protect against. Always wrap the second access with core::try.
✅ Multi-Stage Filtering for Readability
Rule: Break complex logic into multiple local variables
# ✅ Good: Multi-stage filtering
locals {
# Stage 1: Filter to relevant items
ssh_rules = [
for rule in attrs.ingress :
rule if rule.from_port <= 22 && rule.to_port >= 22
]
# Stage 2: Filter to violations
public_ssh_rules = [
for rule in local.ssh_rules :
rule if core::contains(core::try(rule.cidr_blocks, []), "0.0.0.0/0")
]
# Stage 3: Check compliance
is_compliant = core::length(local.public_ssh_rules) == 0
}
Benefits:
- More readable and maintainable
- Easier to debug (inspect intermediate lists)
- Can reuse filtered lists for multiple checks
- Better error messages possible
✅ Multiple Focused Policies
Rule: Use multiple enforce blocks within a single resource_policy block to separate concerns — do NOT split checks on the same resource type into multiple resource_policy blocks (SKILL.md Output Structure Rule 1).
# ✅ Correct — separate concerns via multiple enforce blocks in one block
resource_policy "aws_security_group" "security_group_checks" {
enforce {
condition = !local.has_public_ssh
error_message = "Security group must not allow public SSH ingress."
}
enforce {
condition = !local.has_public_rdp
error_message = "Security group must not allow public RDP