references/tfpolicy-author.md · 48000
averse the Terraform resource graph by reference (e.g. "find all subnets that reference this VPC"). Only resolved attribute values are available. If the Sentinel policy traverses by resolved attribute value (e.g. bucket = attrs.id), convert using core::getresources() with a value-based filter and mark as an apply-time policy — see "Plan-Time vs Apply-Time Policies" above.
⚠️ Partial reference dependence — do not skip the whole policy. Items 8 and 10 apply to the specific check that uses reference metadata, not the entire policy. If only some checks in a Sentinel policy rely on
res.config.attribute["references"]or graph traversal, convert the remaining checks as normal, apply the Simplify label to the overall policy, and document each skipped check in the report with: "This check was omitted — tfpolicy does not expose reference metadata (res.config.attribute["references"])." Only label the entire policy as Not convertible if its core enforcement logic is wholly dependent on reference metadata with no convertible remainder.
❌ Do not approximate reference-metadata checks with cross-resource JSON value matching. A common workaround is to retrieve all instances of a related resource via
core::getresources()and compare their serialized attribute values (e.g.attrs.policy == doc.json) as a proxy for "this resource references that data source." This is not a faithful conversion — it produces false negatives when the referenced resource is already deployed and absent from the current plan, and enforces a different semantic (value equality) than the original (structural reference). When the only check IS reference metadata, generate a stub policy instead:# <policy_name> — Non-Convertible (Reference Metadata) resource_policy "<resource_type>" "<policy_name>_stub" { enforce { condition = true info_message = "Automated enforcement not available: this policy requires reference metadata inspection which tfpolicy does not support. Manual compliance review required." } }
⚠️ Partial exception — direct content inspection via the parent bucket. The cross-resource approximation prohibition applies to comparing JSON across resources (e.g. fetching all
aws_iam_policy_documentoutputs and matching against a bucket policy). It does not prohibit inspecting a bucket's own policy content. When the Sentinel reference-metadata check is really enforcing content (e.g. "the bucket policy must not grant public read access"), convert it by anchoring onresource_policy "aws_s3_bucket", fetching the childaws_s3_bucket_policyviacore::getresources("aws_s3_bucket_policy", { bucket = attrs.id }), and inspecting itspolicyattribute viacore::jsondecode()inside the parent block. This follows the standard dependent-child pattern —aws_s3_bucket_policyalways requires a parent bucket. Label the overall policy Simplify (because the reference-path check is omitted) and add a# NOTE:that the content-based check achieves a similar security outcome.# ✅ Content-based alternative to reference-metadata check on bucket policies # 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" "no_public_read_policy" { locals { bucket_policy = core::getresources("aws_s3_bucket_policy", { bucket = attrs.id }) policy_doc = core::try(core::jsondecode(core::try(local.bucket_policy[0].policy, "{}")), { Statement = [] }) statements_enriched = [for s in core::try(local.policy_doc.Statement, []) : { effect = core::lower(core::try(s.Effect, "Allow")), action = core::try(s.Action, []), principal_str = core::try(s.Principal, ""), principal_aws = core::try(core::try(s.Principal, {}).AWS, "") }] public_read_stmts = [for s in local.statements_enriched : s if s.effect == "allow" && (core::contains(s.action, "s3:GetObject") || core::contains(s.action, "s3:*") || core::contains(s.action, "*")) && (s.principal_str == "*" || s.principal_aws == "*")] } enforce { condition = core::length(local.public_read_stmts) == 0 error_message = "S3 bucket policy must not grant public read access (Principal: * with s3:GetObject or s3:*)." } }
Conversion quality labels
- Perfect — Same enforcement intent and behavior expressed directly in tfpolicy with no known semantic gap.
- Good — Preserves the important enforcement outcome using idiomatic tfpolicy structure (not a one-to-one translation).
- Simplify — Only part of the original Sentinel behavior can be reproduced; document the missing checks explicitly.
- Not convertible — tfpolicy lacks the runtime data or language features required for a safe translation.
Conversion Strategy
| Tier | Pattern | Examples | Approach |
| --- | --- | --- | --- |
| ✅ Easy | Single resource, direct attribute check | EBS encryption, RDS public access, ECS container insights, EKS audit logging, Lambda runtime, CloudTrail logging | Direct 1:1 conversion |
| ✅ Good | Cross-resource value-based lookup (resolved attribute IDs) | S3 + public-access-block, S3 + versioning, EventBridge + resource policy | Use inline core::getresources() with direct filter inside resource_policy; mark as apply-time policy if filter value is a newly-created resource ID |
| ⚠️ Simplify | Cross-resource logic with partial reference dependence | EC2 IMDSv2, security group coverage | Check explicit configuration only; document what is not checked; prefer known literal attributes over inferred relationships |
| ❌ Avoid | rc.change.before outside update/delete; reference-metadata navigation; data-source content inspection by address; complex graph traversal; mutable external state; strings.split() decomposition | — | Recommend a redesign or treat as non-convertible |
Steps to Convert a Sentinel Policy
Step 1 — Parse the Sentinel Structure
Identify imports (tfplan, tfconfig, tfstate, custom), filter logic and resource selection, main and sub-rules, and enforcement level (advisory vs mandatory). Ask: What resources are being checked? Which attributes are validated? Does the policy depend on before/after diff? Are there cross-resource dependencies? Are data sources inspected? Does it rely on reference metadata or graph traversal?
Identify the enforcement target and the parent type: For any policy involving cross-resource dependencies, first perform the registry check (Steps A and B in "Cross-Resource Lookups" above) to identify which resource types are dependent children and which are parent types. Then use the Sentinel's violations expression to confirm the parent type — this is the type your resource_policy targets. Write resource_policy on the parent type. Every dependent child type is accessed exclusively via core::getresources() inside that parent block; all conditions on child resources are evaluated there, and all violations are reported on the parent. Do not write a standalone resource_policy on any resource type that the registry identifies as a dependent child — this rule holds regardless of whether the Sentinel's violations iterated the child or the parent, and regardless of whether the check is about a missing child or a misconfigured one.
Cross-resource policies — use the Terraform Registry to identify the parent, linking attribute, and filter value. For any child resource type involved in a cross-resource lookup, fetch its documentation at
https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/website/docs/r/{resource_name_without_aws_prefix}.html.markdown. Look for a(Required)argument referencing a parent resource in "Argument Reference" and confirm with the usage examples (.idvs.arn). The required argument name is the linking attribute; use the correspondingattrs.idorattrs.arnin thecore::getresources()filter. This applies to all resource families — not just S3.
Do not over-constrain the enforcement condition beyond the Sentinel intent. When the Sentinel checks "at least one item in a collection satisfies condition X", the correct tfpolicy translation is core::length([for item in local.items : item if <condition>]) > 0. Do NOT translate this to "every item must satisfy X" (i.e. core::length([for item in local.items : item if !<condition>]) == 0) unless the Sentinel explicitly enforces ALL items. Over-constraining the condition creates false violations for valid configurations that the Sentinel would pass.
Distinguish enforcement intent from Sentinel implementation detail. Sentinel code often accesses a collection element by index (e.g. origins[0]) as a traversal shortcut rather than an intentional "only check the first item" rule. Before encoding an index access as a scope restriction, ask:
- Is the indexed access repeated for all resources in a filter loop? (If so, it is a loop artifact, not a one-item intent.)
- Does the policy name or comment indicate intent that applies to "all" items?
- Would checking only the first item leave a real security gap?
- Is this collection a structurally singleton block in the provider schema (e.g.
max_items = 1) — in which case[0]is intentional?
When the answer to any of the first three questions is "yes" and the fourth is "no", convert the check to iterate all items in the collection, not just [0]. Document the interpretation in the requirements as: "Sentinel source accesses collection[0]; interpreted as checking all items to preserve full enforcement intent."
Step 2 — Assess Convertibility
Check for non-convertible patterns above. Document what cannot be converted and assign a quality label.
Step 3 — Map to tfpolicy Constructs
Use the mapping table above. In practice, focus on (in order): matching resource scope, translating attribute access and null handling, replacing collection helpers with list comprehensions, and splitting compound logic into locals + multiple enforce blocks.
Step 4 — Generate the policy
Follow the authoring guidance in the Knowledge Base sections above. Apply the cross-resource decision table and companion-anchor rules.
Error-message rules:
- ✅ Static strings, or safe
${attrs.fieldname}interpolation. - ❌ Never interpolate
${meta.address}— it is UNDEFINED inresource_policyand throwsError: Unsupported attributeat runtime for every evaluated resource.tfpolicy testwill not catch this; only a realterraform plan --policies=run will.
Step 5 — Document the Conversion
Include the quality label, test success rate (if tests written), any limitations or simplifications made, behavioral differences from Sentinel, and references to related documentation.
tfpolicy-author.md— guided first-policy walkthrough.tfpolicy-author.md— reusable patterns (attribute checks, allowlists, cross-resource enforcement, etc.).verified-syntax.md— verified syntax tables, runtime limitations, common-mistake corrections. Source of truth — defer to this file when this SKILL.md disagrees.
Usage Instructions — Write a New Policy from User Intent
Step 1 — Clarify requirements
- Which resources / modules / providers to target.
- The specific condition to enforce.
- Whether create, update, and/or destroy should be in scope (
operations). - Whether any value should be tunable per policy set (→
inputblock). - The desired error message and whether
attrs.*interpolation is helpful.
Step 2 — Design the structure
- Choose the policy type (resource / module / provider).
- Decide whether a wildcard label (
"*") is appropriate. - Plan the
filterfor performance and to exclude resources where the attribute is meaningfully absent. Two cases:- Attribute absent = resource out of scope (e.g. no
aclblock set at all → resource doesn't configure ACLs → skip it): usefilter = core::try(attrs.field, null) != null. - Attribute absent = AWS provider default applies (e.g.
encryptedabsent → AWS defaults tofalse→ resource is still in scope and may violate the policy): do not filter on null. Usecore::try(attrs.field, <aws_provider_default>)in theconditioninstead so absent resources are evaluated against the effective default.
- Attribute absent = resource out of scope (e.g. no
- Move complex predicates into
localsfor readability.
Step 3 — Generate the policy
- Start
.policy.hclfiles containing resource or provider policies with a top-levelpolicy { required_providers { ... } }block. - Use provider sources and version constraints that match the resource types referenced by the policy.
- Run
tfpolicy validateafter authoring to confirm the policy parses and the referenced provider schemas can be resolved. - See Required
policy.required_providersBlock for validation limitations such as version-range best-effort checks and wildcard-target behavior. - Wrap optional attributes in
core::try(). - Keep each boolean expression on a single line.
- Use multiple
enforceblocks when you want independent diagnostics. - Never interpolate
${meta.address}inerror_message.
Step 4 — Document the policy
- Header comment with description, resources checked, and any compliance reference.
- Note operation scope and any parameterization.
Worked Example
User request: "Ensure all S3 buckets have versioning enabled."
Include the top-level policy { required_providers { ... } } block shown in Core Structure.
# Ensure S3 Bucket Versioning is Enabled
#
# Enforces that all AWS S3 buckets have versioning enabled to protect
# against accidental deletion and enable recovery.
#
# Resources checked:
# - aws_s3_bucket with inline versioning configuration
# - aws_s3_bucket_versioning (standalone resource pattern)
resource_policy "aws_s3_bucket" "versioning_enabled" {
filter = attrs.versioning != null
locals {
versioning_enabled = core::try(attrs.versioning[0].enabled, false)
}
enforce {
condition = local.versioning_enabled == true
error_message = "S3 buckets must set versioning.enabled = true to protect against accidental deletion."
}
}
resource_policy "aws_s3_bucket_versioning" "versioning_enabled" {
locals {
versioning_status = core::try(attrs.versioning_configuration[0].status, "Disabled")
}
enforce {
condition = local.versioning_status == "Enabled"
error_message = "S3 bucket versioning resources must have status 'Enabled'. Current status: '${local.versioning_status}'."
}
}
Best Practices
Policy Writing
- Use descriptive policy names.
- Add a comprehensive header comment with description, resources checked, and compliance references.
- Always use
core::try()for optional attributes. - Break down complex logic with
locals. - Provide actionable, remediation-focused error messages.
- Cover all variations of a resource family (e.g. AWS security groups:
aws_security_group,aws_security_group_rule,aws_vpc_security_group_ingress_rule,aws_default_security_group). - Use
filterto skip resources that don't apply (saves work and avoids false positives). - Cache
core::getresources()results in top-level locals when the filter is a known literal or an existing resource ID — this avoids O(N) overhead per resource. Exception: when the filter depends on the current resource's own attribute (e.g.{bucket = attrs.id},{event_bus_name = attrs.name}), the call cannot be pre-computed at top level becauseattrsis only available insideresource_policy— use the inline pattern instead (see item 15). ❌ Do NOT work around this by fetching all child resources at the top level with{}and building a lookup map — that is the same anti-pattern restructured. - Avoid
core::getdatasource()insideresource_policy— it calls provider APIs. - Build lookup maps once for O(1) matching when iterating many resources.
- Keep each boolean expression on a single line (HCL parser limitation in beta).
- Use clear variable names (
scanning_config, notsc). - Convert sets to lists before indexing:
[for item in set : item][0]. - Don't use
core::try()defaults to mask missing values that should fail the policy — usefilterinstead. - For cross-resource lookups where the filter value is the current resource's own attribute: use an inline
core::getresources()with the direct filter insideresource_policy. To find the correct linking attribute name and filter value, fetch the child resource's Terraform Registry documentation athttps://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/website/docs/r/{resource_name_without_aws_prefix}.html.markdownand look for the(Required)or(Optional)argument that references the parent resource. Check whether the usage examples assign it.id,.arn, or.name— useattrs.id,attrs.arn, orattrs.nameaccordingly. ⚠️ Some linking attributes are(Optional)in the schema (e.g.event_bus_nameonaws_cloudwatch_event_bus_policydefaults to the default bus) but still represent a parent-child link — treat them the same way. Always add this comment in the policy: "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 use a top-level cache + for-loop for this pattern. - Cross-resource enforcement — registry check determines the structure unconditionally:
- First, verify every resource type via the Terraform Registry. For any resource type involved in a cross-resource check, fetch
https://raw.githubusercontent.com/hashicorp/terraform-provider-aws/main/website/docs/r/{resource_name_without_aws_prefix}.html.markdown. A resource is a dependent child if it has a(Required)argument whose description or usage examples reference another AWS resource by.id,.arn, or.name. The argument name is the linking attribute; the assignment in examples tells you whether to useattrs.id,attrs.arn, orattrs.name. The resource that the linking attribute points to is the parent type. - When the enforcement goal is to ensure every parent has a compliant child, the dependent child must NEVER have a standalone
resource_policyblock. Write theresource_policyblock on the parent type. Fetch the dependent child inside the parent block viacore::getresources("<child_type>", {<linking_attr> = attrs.id_or_arn_or_name}). Evaluate all attribute checks on those lookup results. Report all violations on the parent. When the goal is only to check every existing child's own attributes, a standaloneresource_policyon the child type is valid — see Self-check above. - Concrete examples:
aws_s3_bucket_public_access_block,aws_s3_bucket_policy,aws_s3_bucket_acl(all requirebucket) → never standalone for any enforcement goal; always fetched insideresource_policy "aws_s3_bucket".aws_lb_listener→ standaloneresource_policy "aws_lb_listener"is valid when checking every listener's own attributes (e.g., protocol, ssl_policy); useresource_policy "aws_lb"with inline lookup only when the goal is "every LB must have at least one compliant listener". - Always add this comment when using this pattern: "This policy contains a cross-resource reference that will not resolve during plan time, but the policy will run successfully during apply time."
- First, verify every resource type via the Terraform Registry. For any resource type involved in a cross-resource check, fetch
Communication
- Ask clarifying questions; don't assume requirements.
- Show sample passing and failing resources alongside the policy.
- Explain enforcement-level trade-offs.
- Offer simplifications when an exact rule isn't expressible.
See Also
tfpolicy-test— write.policytest.hclfiles to validate the policies authored here.../../examples/README.md— side-by-side Sentinel +.policy.hclexamples with quality labels and per-example READMEs.verified-syntax.md— shared source-of-truth syntax reference.
Purpose: Quick reference for AI agents to start writing Terraform Policy (tfpolicy) Status: All behaviors verified during private beta (2026-02-19) Compatible with: Any AI system capable of reading markdown and generating HCL code
Quick Start for AI Agents
When a user asks you to write a Terraform Policy:
- Identify the policy type: resource_policy, module_policy, or provider_policy
- Use the correct structure: filter (optional), locals (optional), enforce (required)
- Remember: ALL built-in functions need
core::prefix - For versions: Always use
core::semverconstraint(), never direct comparison - Validate: Check examples in this guide for patterns
Table of Contents
See Also:
- Common Patterns - Common policy patterns and examples
- tfpolicy-author - Complete authoring reference for this sub-skill
Critical Rules
✅ Rule 1: ALL Functions Need core:: Prefix
ALWAYS use core:: prefix for built-in Terraform functions
# ✅ CORRECT
filter = core::try(attrs.encrypted, false) == true
is_valid = core::length([for b in local.checks : b if b]) > 0
message = "Allowed: ${core::join(", ", local.versions)}"
# ❌ WRONG - Will fail with "Unknown function" error
filter = try(attrs.encrypted, false) == true # Missing core:: prefix
# ❌ WRONG - missing core:: prefix (tfpolicy 0.3.0+ does have core::anytrue, but bare anytrue() is never valid)
# is_valid = anytrue(local.checks)
# ✅ CORRECT on tfpolicy 0.3.0+; on < 0.3.0 use core::length([for b in local.checks : b if b]) > 0 instead
# is_valid = core::anytrue(local.checks)
✅ Rule 2: Use Semantic Versioning for ALL Version Comparisons
NEVER use direct comparison operators for versions
# ✅ CORRECT
condition = core::semverconstraint(meta.version, ">= 4.0.0, < 5.0.0")
# ❌ WRONG - Direct comparison doesn't work properly
condition = meta.version >= 4.0 && meta.version < 5.0
✅ Rule 3: ALL Policy Types Support locals and filter
Don't avoid using locals or filter - they work in all policy types
# ✅ All three policy types support this structure
resource_policy "aws_s3_bucket" "example" {
filter = <condition> # ✅ Supported
locals { ... } # ✅ Supported
enforce { ... } # ✅ Required
}
module_policy "example" "check" {
filter = <condition> # ✅ Supported
locals { ... } # ✅ Supported
enforce { ... } # ✅ Required
}
provider_policy "aws" "check" {
filter = <condition> # ✅ Supported
locals { ... } # ✅ Supported
enforce { ... } # ✅ Required
}
Note: Language servers during private beta may show false errors for locals in provider_policy. These are safe to ignore.
Policy Structure
Basic Template
<policy_type> "<target>" "<policy_name>" {
# Optional: Pre-filter resources/modules/providers
filter = <boolean_expression>
# Optional: Local variables for complex logic
locals {
variable_name = <expression>
}
# Required: One or more enforcement rules
enforce {
condition = <boolean_expression>
error_message = "<user-facing message>"
}
# Optional: Additional enforce blocks
enforce {
condition = <another_condition>
error_message = "<another message>"
}
}
Execution Flow
- filter - Applied first, determine