references/verified-syntax.md · 24000
") && !core::contains(meta.version, ">")
Correct - all on one line
is_exact = local.has_version && !core::contains(meta.version, "~>") && !core::contains(meta.version, ">")
**Fix:** Put entire boolean expression on a single line
### ❌ Mistake 8: Trying to Access Module Inputs
```hcl
# Wrong - module inputs not accessible yet
module_policy "*" "check" {
locals {
dns_enabled = attrs.enable_dns_hostnames # ❌ Not supported
}
}
Fix: Module inputs via attrs.* are work in progress. You can only check meta.source, meta.version, meta.address
❌ Mistake 9: Using Substring for Module Targeting
# Wrong - substring matching doesn't work
module_policy "vpc" "check" { } # Won't match modules with "vpc" in source
# Correct - use full source path or wildcard
module_policy "app.terraform.io/myorg/vpc/aws" "check" { }
module_policy "*" "check" { } # For all modules
Fix: Module targeting requires FULL source path, not substring
❌ Mistake 10: Confusing Blocks with Attributes
# Wrong - default_tags is a Block, needs [0]
provider_policy "aws" "check" {
locals {
tags = attrs.default_tags.tags # ❌ Error: no indices
}
}
# Correct - use [0] for Blocks
provider_policy "aws" "check" {
locals {
tags = attrs.default_tags[0].tags # ✅ Works!
}
}
Fix: Check provider schema - Blocks need [0] index, Attributes don't
❌ Mistake 11: Using Source for Provider Targeting
# Wrong - can't use source in first label
provider_policy "hashicorp/aws" "check" { } # Doesn't work
# Correct - use provider TYPE
provider_policy "aws" "check" {
# meta.source available inside policy
# Example: meta.source = "registry.terraform.io/hashicorp/aws"
}
Fix: provider_policy first label = TYPE ("aws"), not source ("hashicorp/aws")
❌ Mistake 12: Unnecessary core::keys() for Length
# Unnecessarily complex
has_tags = core::try(core::length(core::keys(attrs.tags)), 0) > 0
# Simpler - core::length() works directly on maps
has_tags = core::try(core::length(attrs.tags), 0) > 0
# Most readable
has_tags = attrs.tags != null && core::length(attrs.tags) > 0
Fix: core::length() works directly on maps - no need for core::keys() wrapper
❌ Mistake 13: Using core::getresources()
# ❌ WRONG — null or empty filter inside resource_policy runs for EVERY resource (O(N) cost)
resource_policy "aws_s3_bucket" "check" {
locals {
all_policies = core::getresources("aws_s3_bucket_policy", null) # unscoped
}
}
# ❌ ALSO WRONG — empty filter {} is equally unscoped inside resource_policy
resource_policy "aws_s3_bucket" "check" {
locals {
all_policies = core::getresources("aws_s3_bucket_policy", {})
}
}
# ✅ CORRECT — cache at top-level locals for plan-time join (runs once total)
locals {
all_policies = core::getresources("aws_s3_bucket_policy", {})
}
Why: Calling core::getresources() with an empty ({}) or null filter inside resource_policy fetches ALL resources of that type once per evaluated resource — O(N) calls for N resources. Cache in top-level locals to run once.
Exception — per-resource attribute filter (parent+child pattern): When the filter value depends on the current resource's own attribute (e.g. attrs.id), the call cannot be pre-computed at the top level because attrs is only available inside resource_policy. In that case, an inline core::getresources() call with a specific per-resource filter is the correct pattern. Always use a specific filter — never pass {} or null inside a resource_policy.
Dependent child resources — use inline filter, verify via Terraform Registry. Before writing a direct
resource_policy "child_type"block or a top-level cache for a cross-resource lookup, fetch the Terraform Registry documentation for the child resource type to determine whether it is structurally dependent on a parent resource:
- URL pattern:
https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/website/docs/r/{resource_name_without_aws_prefix}.html.markdown- Look for a
(Required)argument in "Argument Reference" whose description references another AWS resource (e.g. "Bucket to which to apply the ACL", "ARN of the load balancer"). Check the usage examples — if they showsome_attr = aws_parent.name.idor.arn, that confirms the dependency.- If the child IS dependent: use
resource_policy "aws_parent_type"with an inlinecore::getresources("aws_child_type", {linking_attr = attrs.id_or_arn})when the enforcement goal is detecting a missing child. The linking attribute name comes from the required argument (e.g.bucket); useattrs.idif the examples assign.id,attrs.arnif they assign.arn.- If the enforcement goal is checking the child's own properties and the child can exist independently (its absence is not a violation by itself), write
resource_policy "aws_child_type"directly — do not look it up inside the parent's policy.- If a resource type has no linking attribute in either direction — neither it nor the "parent" type references the other via
.id,.arn,.name, or similar in the Terraform config — it is a truly independent resource. Write a separateresource_policyblock for it. Never usecore::getresources()inside anotherresource_policyto look up independent resources.- Never use a top-level empty-filter cache for dependent child resource types when doing per-parent enforcement — it fetches all resources globally and requires a manual HCL for-loop to re-associate them with the parent.
⛔ CRITICAL: This prohibition extends to ALL cases where the filter value comes from attrs.* — not just structurally-dependent child resources. If you find yourself writing [for r in local.all_X : r if r.link_attr == attrs.Y] inside a resource_policy, that is the wrong pattern whenever an inline call with a specific filter would work. The top-level {} cache is only appropriate when the filter value is a constant (not derived from attrs.*) — for example, pre-fetching all autoscaling policies to filter by a constant scalable_dimension value inside resource_policy. For truly independent resources (no linking attribute in either direction), a top-level {} cache must NOT be used to implement cross-resource fallback logic between them — each independent resource type gets its own resource_policy block (see rule below).
For truly independent resources — those with NO linking attribute in either direction in the Terraform config — write a separate resource_policy block for each type. Do NOT use core::getresources() to check an independent resource inside another resource_policy.
The key test: look at the Terraform Registry documentation for both resource types. If neither resource has an attribute whose value is set to the other resource's .id, .arn, .name, or similar reference in example usage (e.g. bucket = aws_s3_bucket.x.id, security_configuration = aws_emr_security_configuration.x.name), the resources are independent — each gets its own resource_policy block.
# Example of a LINKING attribute (makes inline core::getresources() correct):
# aws_emr_cluster has: security_configuration = aws_emr_security_configuration.x.name
# → The cluster references the security config by name → inline lookup is valid.
# Example of NO linking attribute (makes inline core::getresources() WRONG):
# aws_instance has NO attribute that references aws_ec2_instance_metadata_defaults.
# aws_ec2_instance_metadata_defaults has NO attribute that references aws_instance.
# → They are independent → each gets its own separate resource_policy block.
⛔ Sentinel fallback pattern between independent resources — never use core::getresources() as a fallback.
When a Sentinel policy has logic like: "if resource A does not have attribute X configured, then check if independent resource B has Y as a fallback" — TFPolicy cannot express this cross-resource fallback because A and B share no linking attribute.
Correct TFPolicy conversion:
- Use
filteron resource A to skip instances where X is absent (they are out of scope for A's check).- Enforce Y directly on resource B via its own separate
resource_policyblock.- Document the limitation in the policy file with a
# LIMITATION:comment.Never implement the fallback by calling
core::getresources("B", {})at the top level and using the result inside A'sresource_policylocals. That is a cross-resource check between independent resources — it is incorrect regardless of whether the filter is{}or a constant value.Concrete example — aws_instance + aws_ec2_instance_metadata_defaults:
# ❌ WRONG — top-level {} cache used to implement Sentinel fallback between independent resources locals { all_defaults = core::getresources("aws_ec2_instance_metadata_defaults", {}) defaults_compliant = core::length([for d in local.all_defaults : d if core::try(d.http_tokens, "") == "required"]) > 0 } resource_policy "aws_instance" "imdsv2" { locals { # ❌ Wrong: cross-resource fallback using independent resource is_compliant = local.has_metadata_options ? (local.http_tokens == "required") : local.defaults_compliant } enforce { condition = local.is_compliant ... } } # ✅ CORRECT — filter skips instances without metadata_options; independent resource checked separately resource_policy "aws_instance" "imdsv2" { filter = core::try(attrs.metadata_options, null) != null && core::try(core::length(attrs.metadata_options), 0) > 0 locals { http_tokens = core::try([for m in attrs.metadata_options : m][0].http_tokens, "") } enforcement_level = "advisory" enforce { condition = local.http_tokens == "required" ... } } resource_policy "aws_ec2_instance_metadata_defaults" "imdsv2" { locals { http_tokens = core::try(attrs.http_tokens, "") } enforcement_level = "advisory" enforce { condition = local.http_tokens == "required" ... } }
# ❌ WRONG — top-level {} cache, then HCL-filtered by attrs.* value inside resource_policy
locals {
all_sec_configs = core::getresources("aws_emr_security_configuration", {})
}
resource_policy "aws_emr_cluster" "check" {
locals {
# ❌ Wrong pattern: fetches all globally and re-filters per cluster
matching = [for sc in local.all_sec_configs : sc if sc.name == attrs.security_configuration]
}
}
# ❌ ALSO WRONG — same anti-pattern restructured as a top-level lookup map.
# Building { name => value } at the top level and indexing by an attrs.*-derived key
# inside resource_policy is semantically equivalent to the {} cache + HCL for-loop above.
# The lookup key (local.security_config_name = core::try(attrs.security_configuration, ""))
# is still derived from attrs.*, so this violates the same rule.
locals {
all_security_configs = core::getresources("aws_emr_security_configuration", {})
security_config_map = {
for sc in local.all_security_configs :
core::try(sc.name, "") => core::try(sc.configuration, "")
}
}
resource_policy "aws_emr_cluster" "check" {
locals {
security_config_name = core::try(attrs.security_configuration, "")
# ❌ Wrong: map lookup by attrs.*-derived key is an attrs.* filter in disguise
security_config_json = core::try(local.security_config_map[local.security_config_name], "")
}
}
# ✅ CORRECT — inline call with filter derived from attrs.*
resource_policy "aws_emr_cluster" "check" {
locals {
matching = core::getresources("aws_emr_security_configuration", {
name = attrs.security_configuration
})
}
}
# ✅ CORRECT — inline call with per-resource filter using attrs.id
# 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" "public_access_required" {
locals {
public_access_block = core::getresources("aws_s3_bucket_public_access_block", {
bucket = attrs.id # Use attrs.id: Terraform sets child.bucket = parent.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 must have all public access block settings enabled."
}
}
See the core::getresources() decision guide in Critical Rule 2 above for the full pattern guidance.
❌ Mistake 14: Using core::getdatasource() Inside resource_policy
# ❌ WRONG - Makes API calls for EVERY resource!
resource_policy "aws_s3_bucket" "check" {
locals {
account_id = core::getdatasource("aws_caller_identity", {})
}
}
# ✅ CORRECT - Cache in top-level locals
locals {
account_id = core::getdatasource("aws_caller_identity", {})
}
Why: Makes real provider API calls (not cached). Never use inside resource policies.
❌ Mistake 15: Using .attrs with core::getresources()
# ❌ WRONG
locals {
all_roles = core::getresources("aws_iam_role", {})
}
resource_policy "aws_iam_role" "check" {
locals {
name = local.all_roles[0].attrs.name # ERROR!
}
}
# ✅ CORRECT
resource_policy "aws_iam_role" "check" {
locals {
name = local.all_roles[0].name # Works!
}
}
Fix: Resources from core::getresources() have attributes at top level, not through .attrs.
❌ Mistake 16: Not Converting Sets to Lists for Indexing
# ❌ WRONG - rule is a SET, cannot index
resource_policy "aws_s3_bucket_server_side_encryption_configuration" "check" {
locals {
sse_algo = attrs.rule[0].sse_algorithm # ERROR!
}
}
# ✅ CORRECT - Convert set to list using for loop
resource_policy "aws_s3_bucket_server_side_encryption_configuration" "check" {
locals {
sse_algo = [for rule in attrs.rule : rule][0].sse_algorithm
}
}
Fix: Sets cannot be indexed with [0]. Use [for item in set : item][0] to convert.
❌ Mistake 17: Redundant Length Checks — and When to Keep Them
core::try() catches index-out-of-range errors, so a bare length check before [0] inside a condition = expression is technically redundant:
# ❌ Redundant in condition = expressions (core::try catches the out-of-range error)
condition = core::length(local.list) > 0 && core::try(local.list[0].value, "") == "expected"
# ✅ Simpler — safe in condition = expressions
condition = core::try(local.list[0].value, "") == "expected"
However, when the list comes from core::getresources() (a child-resource lookup), always use an explicit length guard in locals before indexing with [0]. This makes the intent clear, is consistent with policies that inspect nested attribute blocks, and avoids relying on core::try to silently swallow a structural absence:
# ✅ PREFERRED for core::getresources() results — explicit guard before [0]
locals {
bucket_acl_resources = core::getresources("aws_s3_bucket_acl", { bucket = attrs.id })
has_acl = core::length(local.bucket_acl_resources) > 0
acl_value = local.has_acl ? core::try(local.bucket_acl_resources[0].acl, "") : ""
}
# ✅ PREFERRED for nested block lists from getresources() — guard each level
locals {
sse_configs = core::getresources("aws_s3_bucket_server_side_encryption_configuration", { bucket = attrs.id })
has_sse_config = core::length(local.sse_configs) > 0
sse_rules = local.has_sse_config ? core::try([for r in local.sse_configs[0].rule : r], []) : []
has_sse_rule = core::length(local.sse_rules) > 0
sse_apply_block = local.has_sse_rule ? core::try([for a in local.sse_rules[0].apply_server_side_encryption_by_default : a], []) : []
has_apply_block = core::length(local.sse_apply_block) > 0
sse_algorithm = local.has_apply_block ? core::try(local.sse_apply_block[0].sse_algorithm, "") : ""
}
# ❌ AVOID for getresources() results — relies on core::try to mask absent child resource
locals {
sse_configs = core::getresources("aws_s3_bucket_server_side_encryption_configuration", { bucket = attrs.id })
sse_rules = core::try([for r in local.sse_configs[0].rule : r], []) # no guard: absence silently swallowed
sse_algorithm = core::try(local.sse_rules[0].apply_server_side_encryption_by_default[0].sse_algorithm, "")
}
Rule summary:
- In a
condition =expression:core::try(list[0].attr, default)without a length guard is acceptable. - In a
localsblock withcore::getresources()results: usehas_X = core::length(local.X) > 0and guard each[0]access withlocal.has_X ? ... : default. This is the established pattern in all S3 child-resource policies and makes the "no child resource found" case explicit.
❌ Mistake 18: Expecting Cross-Resource References to Resolve at Plan Time
# ❌ Won't match during initial creation
resource "aws_s3_bucket_server_side_encryption_configuration" "example" {
bucket = aws_s3_bucket.example.id # Reference not resolved at policy time
}
# ✅ For testing, use literals
resource "aws_s3_bucket_server_side_encryption_configuration" "example" {
bucket = "my-bucket" # Literal value
}
Fix: Cross-resource references aren't resolved at policy evaluation. Works best on existing infrastructure updates.
❌ Mistake 19: Using meta.address in resource_policy
# ❌ WRONG — meta.address is UNDEFINED in resource_policy real-plan evaluation
resource_policy "aws_s3_bucket" "check" {
enforce {
condition = !local.has_public_acl
error_message = "S3 bucket '${meta.address}' has a public ACL." # ERROR!
}
}
# ✅ CORRECT — use static strings or safe attrs interpolation
resource_policy "aws_s3_bucket" "check" {
enforce {
condition = !local.has_public_acl
error_message = "S3 bucket has a prohibited public ACL. Set acl to 'private' or remove it."
# Or with dynamic context using a known attribute:
# error_message = "S3 bucket '${attrs.bucket}' has a prohibited public ACL."
}
}
Fix: meta.address is UNDEFINED for resource_policy in real plan evaluation. It throws Error: Unsupported attribute for every resource evaluated, including compliant ones. tfpolicy test silently passes this bug — only terraform plan --policies= catches it.
❌ Mistake 20: Incomplete Security Group Resource Coverage
# ❌ WRONG — Only covers 2 of 4 SG resource types; misses modern VPC API
resource_policy "aws_security_group" "check" { ... }
resource_policy "aws_security_group_rule" "check" { ... }
# ✅ CORRECT — Cover all 4 AWS security group resource types
resource_policy "aws_security_group" "check" {
# inline ingress/egress blocks; cidr_blocks in rule.cidr_blocks
}
resource_policy "aws_security_group_rule" "check" {
# standalone rules; cidr_blocks in attrs.cidr_blocks, type in attrs.type
}
resource_policy "aws_vpc_security_group_ingress_rule" "check" {
# modern VPC API (recommended); uses attrs.cidr_ipv4 NOT cidr_blocks
locals {
has_public_cidr = core::try(attrs.cidr_ipv4, "") == "0.0.0.0/0"
}
}
resource_policy "aws_default_security_group" "check" {
# default SG; same inline structure as aws_security_group
}
Key difference: aws_vpc_security_group_ingress_rule uses cidr_ipv4 (string) and cidr_ipv6 (string), NOT cidr_blocks (list). Always include all 4 types for complete SG enforcement.
ELB family — 3 resource types required for complete listener/SSL enforcement:
# ❌ WRONG — Only covers Classic ELB; ALB/NLB (the modern standard) are silently skipped
resource_policy "aws_elb" "ssl_policy_check" { ... }
# ✅ CORRECT — Cover all 3 ELB resource types
resource_policy "aws_elb" "ssl_policy_check" {
# Classic ELB: check aws_load_balancer_policy + aws_load_balancer_listener_policy
# listeners use attrs.listener[*].lb_protocol
}
resource_policy "aws_lb_listener" "ssl_policy_check" {
# ALB/NLB: ssl_policy is a direct attribute on the listener
filter = core::contains(["HTTPS", "TLS"], core::try(attrs.protocol, ""))
locals {
ssl_policy = core::try(attrs.ssl_policy, "")
}
enforce {
condition = core::contains(local.allowed_policies, local.ssl_policy)
error_message = "ALB/NLB listener must use an approved SSL/TLS security policy."
}
}
resource_policy "aws_alb_listener" "ssl_policy_check" {
# aws_alb_listener is an alias for aws_lb_listener — same attributes, same checks
filter = core::contains(["HTTPS", "TLS"], core::try(attrs.protocol, ""))
locals {
ssl_policy = core::try(attrs.ssl_policy, "")
}
enforce {
condition = core::contains(local.allowed_policies, local.ssl_policy)
error_message = "ALB/NLB listener must use an approved SSL/TLS security policy."
}
}
Key difference: aws_lb_listener/aws_alb_listener has ssl_policy as a direct attribute; aws_elb requires cross-resource checks via aws_load_balancer_policy. Always cover all 3 types for complete ELB enforcement.
❌ Mistake 21: Using core::try Default to Mask Missing Attributes
# ❌ WRONG — resources where acl is NOT SET get defaulted to "private" and silently pass.
# This does NOT affect resources where acl IS set to "public-read" — those still fail correctly.
# The problem is resources with no acl configured are treated as compliant when they may not be.
resource_policy "aws_s3_bucket" "check" {
locals {
acl_value = core::try(attrs.acl, "private") # missing acl → "private" → passes silently
is_violation = core::contains(["public-read", "public-read-write"], local.acl_value)
}
enforce {
condition = !local.is_violation
}
}
# ✅ CORRECT — use filter to only evaluate resources that have the attribute set
resource_policy "aws_s3_bucket" "check" {
filter = core::try(attrs.acl, null) != null # skip resources with no acl configured
locals {
acl_value = attrs.acl # safe after filter
is_violation = core::contains(["public-read", "public-read-write"], local.acl_value)
}
enforce {
condition = !local.is_violation
}
}
Fix — two cases:
- Attribute absent = resource out of scope (resource doesn't configure the feature at all → skip it): use
filter = core::try(attrs.field, null) != nullto exclude those resources. - Attribute absent = AWS provider default applies (e.g.
encryptedabsent → AWS defaults tofalse,enabledabsent → AWS defaults totrue): the resource is in scope and should be evaluated. Do not filter on null — usecore::try(attrs.field, <aws_default>)in theconditionso the effective default is checked. Filtering out these resources would silently pass non-compliant configurations.
Deciding which case applies: check the Terraform provider documentation for the attribute. If it says "Default:
false" or "Default:true", the absence carries a meaningful value → usecore::trywith the provider default in condition. If the attribute is truly optional with no provider default (its absence means "this block is not configured"), usefilterto exclude it.
❌ Mistake 22: Using expect_failure on data source blocks
# ❌ WRONG — tfpolicy test does not support expect_failure on data blocks
data "aws_iam_policy_document" "test" {
expect_failure = true # ERROR: unsupported argument
attrs = { ... }
}
# ✅ CORRECT — expect_failure i