references/tfpolicy-author.md · 24000
l 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 *)." } }
### Cross-Resource Lookups
**🛑 Self-check — run this BEFORE writing any `resource_policy` involving a companion/child resource:**
> "What is the enforcement goal?"
> - **"Every existing instance of `<child_type>` must have correct attributes"** (e.g., "every `aws_lb_listener` must use HTTPS") → anchor `resource_policy` directly on the child type
> - **"Every parent must have at least one compliant child"** (e.g., "every S3 bucket must have a `public_access_block` with all four flags set") → anchor `resource_policy` on the **parent**; a child-only policy silently misses parents with no child in the plan
**Decision table — choose the correct pattern first:**
| Enforcement goal | Who gets the `resource_policy`? | Pattern |
|---|---|---|
| "Every existing instance of `<child_type>` must have correct attributes" (e.g., "every `aws_lb_listener` must use HTTPS") | Child type directly | Direct child `resource_policy` |
| "Every parent must have at least one compliant child" (e.g., "every S3 bucket must have a `public_access_block` with all four flags set") | **Parent** resource | Apply-time: inline `core::getresources("child", {bucket = attrs.id})` inside `resource_policy` |
| "Parent has a companion identified by a known literal / stable attribute" (e.g., versioning bucket name matches `attrs.bucket`) | Parent resource | Plan-time: top-level `core::getresources("companion", {})` + HCL for-loop filter inside `resource_policy` |
**⚠️ Critical:** Never write a `resource_policy "child_type"` to enforce "every parent must have a child" — if the child resource is absent entirely, the policy never fires for that parent and the violation is silently missed.
**🔴 Named companion resources — ALWAYS use the parent as `resource_policy` anchor when the goal is presence enforcement:**
The following Terraform resource types are **companion-only** — a parent resource can exist in a plan without them. NEVER anchor a standalone `resource_policy` on these types when checking for their presence:
| ❌ Never use as standalone `resource_policy` anchor (for presence) | ✅ Always anchor on | Lookup key |
|---|---|---|
| `aws_s3_bucket_public_access_block` | `aws_s3_bucket` | `{ bucket = attrs.id }` (apply-time inline) |
| `aws_s3_bucket_acl` | `aws_s3_bucket` | `{ bucket = attrs.id }` (apply-time inline) |
| `aws_s3_bucket_logging` | `aws_s3_bucket` | `{ bucket = attrs.id }` (apply-time inline) |
| `aws_s3_bucket_server_side_encryption_configuration` | `aws_s3_bucket` | `{ bucket = attrs.id }` (apply-time inline) |
| `aws_s3_bucket_versioning` | `aws_s3_bucket` | plan-time top-level + `v.bucket == attrs.bucket` filter |
| `aws_s3_bucket_policy` | `aws_s3_bucket` | `{ bucket = attrs.id }` (apply-time inline) — even for content enforcement (e.g., checking `Principal: "*"`), inspect the child's `policy` attr via `core::jsondecode()` inside the parent block |
> This pattern applies to all resource families, not just S3. Non-S3 examples: when checking "every VPC has a flow log" → anchor on `aws_vpc` with inline `core::getresources("aws_flow_log", {vpc_id = attrs.id})`; when checking "every LB has at least one compliant listener" → anchor on `aws_lb` with inline `core::getresources("aws_lb_listener", {load_balancer_arn = attrs.arn})`.
> **Why this matters:** Even if the Sentinel source iterates over the companion type, TFPolicy must anchor on the parent. A Terraform plan can declare an `aws_s3_bucket` with NO companion resource — anchoring on the companion silently misses that bucket entirely.
**⚠️ Parent-anchor means parent-ONLY:** Once the decision table says "parent resource" is the anchor, generate `resource_policy` blocks **exclusively** on the parent type. Do NOT also generate standalone `resource_policy` blocks for companion types alongside the parent blocks. Adding companion blocks in parallel:
- still silently misses parents that have no companion
- double-reports violations
All enforcement logic — including every companion check — must live inside the parent `resource_policy` block, using inline or top-level lookups.
---
**Plan-time pattern** — use `core::getresources()` at the **top level** only when the filter value is a **known constant** (not derived from `attrs.*`). When the filter depends on the current resource's own attribute, use the inline pattern below instead. ❌ Top-level `{}` (empty filter) + for-loop or lookup map filtered by `attrs.*` inside `resource_policy` is the prohibited anti-pattern — see verified-syntax.md Mistake 13 for both variants.
**⚠️ Exception — "companion absence is itself a violation":** When the goal is to enforce that a companion resource **exists AND has matching attributes** (e.g. a parent resource must have a linked companion with a specific qualifying attribute set), the inline filter pattern produces false negatives: if the companion is absent or has a mismatching linking key, `core::getresources()` returns `[]`, and `!has_companion` is `true` → a condition like `!has_companion || check_attr == "VALUE"` incorrectly passes. Use the **top-level collect-then-filter pattern** instead:
```hcl
# Top-level: collect ALL companions globally, filter to those with the qualifying attribute,
# then check membership inside resource_policy.
locals {
all_companions = core::getresources("aws_companion_resource", {})
# Filter to companions that have the qualifying attribute set (e.g. non-empty elb)
qualifying_companions = [for c in local.all_companions : c
if core::try(c.qualifying_attr, null) != null && core::try(c.qualifying_attr, "") != ""]
# Collect the linking attribute values from qualifying companions only
companion_names = [for c in local.qualifying_companions : core::try(c.linking_attr, "")]
# Use qualifying companions (not all) to decide whether to evaluate
has_qualifying = core::length(local.qualifying_companions) > 0
}
resource_policy "aws_parent_resource" "example" {
# Only evaluate when qualifying companions exist in the plan
filter = local.has_qualifying
locals {
parent_name = core::try(attrs.name, "")
is_linked = core::length([for n in local.companion_names : n if n == local.parent_name]) > 0
# 🔴 Condition must be POSITIVE: both linked AND check_attr correct
# Do NOT use: !is_linked || check_attr == "EXPECTED" ← this passes when companion absent
is_compliant = local.is_linked && core::try(attrs.check_attr, "") == "EXPECTED"
}
enforce {
condition = local.is_compliant
error_message = "..."
}
}
This pattern correctly detects:
- Companion absent entirely →
has_qualifying = false→filter = false→ parent skipped ✓ - Companion present but with no qualifying attribute →
qualifying_companions = []→has_qualifying = false→ parent skipped ✓ - Companion with wrong
linking_attrvalue →is_linked = false→is_compliant = false→ violation ✓ - Companion with correct linking and correct
check_attr→is_compliant = true→ passes ✓
⚠️ Choose filter scope carefully: filter = local.has_qualifying (qualifying companions only) skips all parents when no qualifying companions exist — this matches a Sentinel that returns early when no qualifying companions are found. If the Sentinel does NOT skip when non-qualifying companions exist (e.g. it evaluates parents even when only ALB/NLB attachments are present), use filter = core::length(local.all_companions) > 0 instead. With this broader filter, unlinked parents (is_linked = false) are evaluated and correctly fail is_linked && check_attr == VALUE.
🔴 Condition polarity rule: When using the top-level collect-then-filter pattern, always use a positive condition (is_linked && check_attr == VALUE), not a negative condition (!is_linked || check_attr == VALUE). The negative form silently passes any parent that is not linked — which is the opposite of the intended enforcement. With the positive form: unlinked parent → is_linked = false → is_compliant = false → violation (correct). With the negative form: unlinked parent → !false || any = true → is_compliant = true → passes (incorrect).
Apply-time pattern — when the filter value is the current resource's own attribute (e.g. bucket = attrs.id, or event_bus_name = attrs.name), use an inline core::getresources() call with the direct filter inside resource_policy. The filter cannot resolve at plan time (the attribute value is unknown until apply), but fully resolves once the resource is provisioned. The linking attribute may reference attrs.id, attrs.arn, or attrs.name — check the child resource's Terraform Registry docs to determine which one.
S3 cross-resource note: Always use
attrs.id(notattrs.bucket) when filtering S3 child resources such asaws_s3_bucket_public_access_block,aws_s3_bucket_acl,aws_s3_bucket_server_side_encryption_configuration, andaws_s3_bucket_policy. Terraform providers set the child resource's linking attribute (bucket) to the parent bucket's.id. Usingattrs.idensures the filter matches the actual value stored in the child resource's plan.
# 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
})
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 does not have all public access block settings enabled."
}
}
Error Message Rules
- ✅ Static strings:
"S3 buckets must enable versioning." - ✅ Safe interpolation:
"Instance type '${attrs.instance_type}' is not allowed." - ❌ Never interpolate
${meta.address}— it is UNDEFINED inresource_policyand crashes at runtime.tfpolicy testwill NOT catch this; only a realterraform planwill. - Use
error_messagefor all enforceable violations (condition can be false). - Use
info_messageonly in non-convertible stub blocks wherecondition = trueand no real enforcement is possible. Never useinfo_messagein a block that can actually fail a resource.
Comment Conventions — # LIMITATION: vs # NOTE:
These two markers have distinct meanings — do not interchange them:
# LIMITATION:— tfpolicy cannot fully express or enforce the requirement. Part of the original Sentinel logic had to be omitted or approximated. Always accompanies aSimplifyorNot convertiblequality label.- Example: "LIMITATION: The bucket policy IAM document check is non-convertible — tfpolicy does not expose reference metadata."
# NOTE:— The enforcement is complete but has a runtime caveat that does not reduce coverage.- Example: "NOTE: This policy contains a cross-resource reference that will not resolve during plan time, but will run successfully during apply time."
Output Structure Rules — Consistency-Critical
These rules eliminate the most common sources of non-deterministic output between runs:
Rule 1 — One resource_policy block per resource type.
Multiple checks on the same resource type MUST be combined into a single resource_policy block using separate locals and multiple enforce blocks. Never split checks into two resource_policy blocks for the same type.
# ✅ Correct — two checks, one block
resource_policy "aws_ecs_task_definition" "secure_networking" {
filter = core::try(attrs.network_mode, "") == "host"
locals {
containers = core::try(core::jsondecode(attrs.container_definitions), [])
non_privileged = [for c in local.containers : c if core::try(c.privileged, false) != true]
insecure_user = [for c in local.containers : c if core::try(c.user, "") == "" || core::try(c.user, "") == "root"]
}
enforcement_level = "advisory"
enforce {
condition = core::length(local.non_privileged) == core::length(local.containers)
error_message = "ECS task definition containers must not run as privileged."
}
enforce {
condition = core::length(local.insecure_user) == 0
error_message = "ECS task definition containers must define a non-root user."
}
}
# ❌ Wrong — same resource type split across two blocks
resource_policy "aws_ecs_task_definition" "check_privileged" { ... }
resource_policy "aws_ecs_task_definition" "check_user" { ... }
Rule 2 — Non-convertible checks are comments, not stub blocks.
When a specific check cannot be converted (reference metadata, etc.), document it as a # LIMITATION: comment inside the existing resource_policy block — do NOT create a separate resource_policy block of the same type as a stub. A dedicated stub block (with condition = true) is only appropriate when the entire policy has no convertible checks at all.
Rule 3 — Per-resource enforcement for all checks.
Do NOT aggregate across all resources of a type at the plan level (e.g. "at least one trail in the whole plan is compliant = pass all"). Each resource_policy must evaluate each individual resource independently. tfpolicy's evaluation model is per-resource — plan-level aggregation via top-level core::getresources() to pass/fail based on a count across all resources is not idiomatic and produces non-deterministic results.
# ✅ Correct — each aws_cloudtrail resource evaluated independently
resource_policy "aws_cloudtrail" "s3_dataevents_enabled" {
locals { ... }
enforce {
condition = local.is_compliant
error_message = "This CloudTrail trail must log S3 data events."
}
}
# ❌ Wrong — plan-level aggregation ("at least one compliant trail")
locals {
all_trails = core::getresources("aws_cloudtrail", {})
num_compliant = core::length([for t in local.all_trails : t if ...])
any_compliant = local.num_compliant > 0
}
resource_policy "aws_cloudtrail" "s3_dataevents_enabled" {
enforce {
condition = local.any_compliant # Wrong: passes every trail if any one trail is compliant
error_message = "..."
}
}
Sentinel → Terraform Policy Conversion
Use this section when the input is an existing Sentinel .sentinel file. Follow Steps 1–5 below; apply the authoring guidance above when generating the policy HCL.
Sentinel → Terraform Policy construct mapping
| Sentinel | Terraform Policy |
|----------|-----------------|
| import "tfplan/v2" | Native policy context — no import needed |
| tfplan.resource_changes loops | Usually one resource_policy per resource type; split multi-type Sentinel rules when needed |
| filter tfplan.resource_changes | Resource type in the policy declaration plus optional filter for attribute-based preconditions |
| as address, rc | attrs.* and meta.provider_type for the current resource. ⚠️ meta.address is UNDEFINED — do not use it. |
| rc.change.after.<attr> | attrs.<attr> |
| rc.change.before.<attr> | prior_attrs.<attr> — available when operations is limited to "update" and/or "delete" |
| rc.change.actions is ["delete"] | operations = ["delete"] — fires only on destroy |
| rc.change.actions is not ["delete"] | 0.4.0+: omit operations (default ["create", "update", "no-op"]), since Sentinel's resource_changes also includes unchanged resources. 0.3.x: operations = ["create", "update"] plus a # LIMITATION: noting unchanged resources aren't evaluated |
| contains "create" or is ["update"] | operations = ["create", "update"] |
| param allowed_list default [...] | input "allowed_list" { type = list(string); default = [...] } |
| time.now.weekday_name | core::formatdate("EEEE", core::timestamp()) — UTC weekday name |
| time.now.hour | core::parseint(core::formatdate("HH", core::timestamp()), 10) — UTC hour as int |
| strings.has_prefix(s, p) | core::startswith(s, p) — arg order: full string first, prefix second (same as Sentinel). Note: meta.version in provider_policy is the resolved version (e.g. "6.50.0"), NOT the constraint string. Sentinel's strings.has_prefix(p.version_constraint, ">") is non-convertible — tfpolicy does not expose the constraint string. Use core::semverconstraint(meta.version, ...) instead. |
| strings.has_suffix(s, suffix) | core::endswith(s, suffix) |
| rc.provider_name | meta.provider_type |
| all/any expressions | core::alltrue(list) / core::anytrue(list) on tfpolicy 0.3.0+. On < 0.3.0, use list comprehensions with filtered counts instead: core::length([for x in list : x if !x]) == 0 for "all true" and core::length([for x in list : x if x]) > 0 for "any true". |
| else clause | Multiple enforce blocks |
| maps.get(obj, key, default) | core::try(obj.key, default) |
| collection.reject(items, predicate) | List comprehension with if — [for item in items : item if !<predicate>] |
| collection.reject(items, predicate) is empty | 🔴 ALL condition — every element satisfies the predicate. ⚠️ Do NOT convert this to an ANY condition (length([for item in items : item if <predicate>]) > 0) — that inverts the semantics. The correct pattern is: non_compliant = [for item in items : item if !<predicate>] / is_compliant = core::length(local.non_compliant) == 0. Example: collection.reject(log_opts, func(o) { o.enabled and o.log_type is "AUDIT_LOGS" }) is empty → non_compliant = [for o in local.log_opts : o if !(core::try(o.enabled, false) && core::try(o.log_type,"") == "AUDIT_LOGS")] / condition = core::length(local.log_opts) > 0 && core::length(local.non_compliant) == 0. When the predicate tests a boolean flag, verify the Sentinel default value and match it in core::try(attr, <same_default>). |
| collection.filter(items, predicate) | List comprehension with if — [for item in items : item if <predicate>] |
| strings.split(sep, str) | core::split(separator, string) — splits a string into a list of substrings at each occurrence of separator. Example: core::split("-", "80-443") → ["80","443"]. ⚠️ For version range checks, prefer core::semverconstraint() over core::split + core::parseint — see the Semver note in the core:: Functions section. |
When converting Sentinel
summary {}output orprint()statements, do not reproduce address-listing behavior. Terraform Policy diagnostics already identify the failing resource — prefer remediation-focused messages instead.
Sentinel features that ARE convertible
- Time-based rules —
core::timestamp()+core::formatdate()+core::parseint()cover Sentinel'stimeimport. All values are UTC; document that assumption in policy comments. paramblocks — direct equivalent:inputblocks withtypeanddefault.rc.change.beforefor update/delete —prior_attrsis available whenoperationsis limited to"update"and/or"delete".- Integer range checks — Sentinel policies that check whether all ports within
[from_port, to_port]are authorized CAN be converted. Use the count approach: filterauthorized_portsto those within the range and compare the count toto_port - from_port + 1. Do not usecore::range()with dynamicattrs.*values. Seeverified-syntax.mdMistake 23. tfconfig/v2reference count — each resource reference is stored twice in.references(once asresource.name, once asresource.name.id). When simplifying a reference-count check to a directcore::length(attrs.attribute)check, halve the threshold:references > 2→core::length(attrs.attribute) >= 2.
Plan-Time vs Apply-Time Policies
Terraform Policy can enforce controls at plan time (before terraform apply) or apply time (during terraform apply). Most policies are plan-time, but cross-resource lookups that depend on newly-created resource IDs only fully resolve at apply time.
| Scenario | Enforcement time | Quality label |
|----------|-----------------|---------------|
| Single-resource attribute checks | Plan time | Perfect / Good |
| Cross-resource lookup where the filter value is a known literal or existing resource ID | Plan time | Good |
| Cross-resource lookup where the filter value is a newly-created resource ID (e.g. bucket = attrs.id for a bucket created in the same plan) | Apply time | Good |
| Reference metadata / graph traversal (res.config.attribute["references"]) | Not convertible | — |
When a Sentinel policy uses cross-resource references with a value-based filter from a newly-created resource:
- Generate the policy using an inline
core::getresources()call with the direct filter insideresource_policy. - Add this note in the conversion report (not a limitation label): "This policy contains a cross-resource reference that will not resolve during plan time, but the policy will run successfully during apply time."
- Do not label this as Simplify or Not convertible — it is a valid Good conversion.
For cross-resource patterns, apply the registry check (Steps A and B) described in "Cross-Resource Lookups" above. The registry check fully determines the policy structure, regardless of whether the Sentinel's violations iterated the parent or the child type. Dependent child resource types must never have a standalone resource_policy block.
Cannot Convert (Explain the Alternative)
- Mocking/testing infrastructure (
import "tfconfig-functions") — tfpolicy uses.policytest.hcl. See the tfpolicy-test skill. - Custom Sentinel imports — limited plugin support; use HTTP plugins or native functions if available.
- Sentinel simulator / built-in test framework — replace with
.policytest.hcltest files. - Cross-workspace data access — tfpolicy evaluates a single plan. Use workspace tags (
meta.tfe_workspace.tags) or external plugins. print()/ debug statements — no debug output mechanism; rely on conciseerror_message/info_messagetext only when it adds remediation context.- Stateful logic across evaluations — policies are stateless; use external systems via plugins if state is required.
rc.change.beforeoutside delete/update — for first-time creates there is no pre-state.- Cross-resource reference navigation via reference metadata (
res.config.attribute["references"],res.config.to) — tfpolicy does not expose which Terraform resource a value points to. When the Sentinel policy uses the resolved value of an attribute (not the reference path itself), convert usingcore::getresources()with a value-based filter — see "Plan-Time vs Apply-Time Policies" above. - Data source content inspection by address —
core::getdatasource()requires filter attributes and cannot query by Terraform address. - Complex resource-graph traversal via reference metadata — cannot tr