references/tfpolicy-author.md
name: tfpolicy-author description: Expert agent for authoring Terraform Policies — from natural-language requirements or Sentinel source. Covers the full workflow write new policies, convert existing Sentinel policies, parameterize with inputs, structure cross-resource checks, apply operation scoping, and produce remediation-focused error messages. license: MPL-2.0 metadata: copyright: Copyright IBM Corp. 2026 version: "0.2.0"
tfpolicy-author
Description
Expert agent for writing Terraform Policies — from either a natural-language requirement or an existing Sentinel .sentinel source. Covers the full authoring and conversion workflow: translate requirements or Sentinel logic into resource_policy, module_policy, or provider_policy HCL with correct cross-resource patterns, operation scoping, core:: functions, parameterized inputs, and remediation-focused error messages.
Note: This skill supersedes
sentinel-to-tfpolicy. All Sentinel conversion knowledge is now consolidated here to ensure consistent behaviour when generating policies from Sentinel sources.
Use When
- The user describes an enforcement rule and wants a
.policy.hclfile ("block public RDS", "require encryption", "deny instance types outside an allowlist"). - The user has a Sentinel
.sentinelfile (or snippet) and wants the Terraform Policy equivalent. - The user is migrating a Sentinel policy library to tfpolicy and needs per-policy assessment.
- The user is writing a new
resource_policy,module_policy, orprovider_policyblock. - The user is asking about tfpolicy language features —
filter,locals,enforce,input,operations,prior_attrs,core::*functions, list comprehensions, version constraints, time/date functions. - The user is asking how to structure a policy that depends on related resources via
core::getresources()orcore::getdatasource(). - The user is comparing Sentinel and tfpolicy capabilities ("can I express X in tfpolicy?").
Do not use this skill when:
- The user is writing or debugging a
.policytest.hcltest file — usetfpolicy-test.
Capabilities
1. Write Policies from User Intent
Turn natural-language requirements into resource_policy, module_policy, or provider_policy blocks with appropriate filters, locals, enforce blocks, and remediation-focused error messages.
2. Convert Sentinel Policies to Terraform Policy
Translate Sentinel constructs into tfpolicy equivalents, flag non-convertible patterns with practical alternatives, produce idiomatic .policy.hcl from existing Sentinel sources, and apply a quality label to each conversion.
3. Apply Operation Scoping Correctly
Use operations = ["create", "update", "delete", "no-op"] ("no-op" requires tfpolicy 0.4.0+) and prior_attrs.<name> to scope policies to the right plan actions and read pre-change state when relevant.
4. Parameterize with input Blocks
Replace hardcoded allowlists, version constraints, and thresholds with input blocks so policy sets can override values per environment.
5. Structure Cross-Resource Checks Safely
Use core::getresources() at the top level for plan-time joins, with value-based filters when the filter is a known literal or existing ID. Use inline core::getresources() inside resource_policy for apply-time parent+child lookups, when the filter depends on the current resource's own attribute (e.g. {bucket = attrs.id}). Consult the decision table (line 232) to choose the correct pattern; both top-level and inline are first-class options for their respective scenarios. Understand when cross-references will be unresolved at plan time.
6. Surface Runtime Pitfalls Up Front
Steer the user away from documented runtime hazards — meta.address is undefined in resource_policy, core::try() defaults can silently mask non-compliant resources, sets must be converted to lists for indexing, multi-line boolean expressions break the parser, etc.
Knowledge Base
Policy Types
resource_policy "<resource_type>" "<policy_name>" { }
module_policy "<module_pattern>" "<policy_name>" { }
provider_policy "<provider_pattern>" "<policy_name>" { }
Required policy.required_providers Block
Every .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.
Use the same top-level policy scaffold shown in the Core Structure and Worked Example sections; only the provider source/version values should vary by policy.
Rules and limitations:
required_providersis mandatory for.policy.hclvalidation.- Validation is best effort for version ranges. When a range is declared, validation evaluates provider schemas at the lower and upper bounds of the range.
- Wildcard targets such as
resource_policy "*"are not schema-validated because they may match multiple resource types. required_providersdeclares provider source and version constraints for validation. This is distinct frommeta.versioninprovider_policy, which exposes the resolved provider version during policy evaluation.
Core Structure
policy {
required_providers {
# Declare provider source and version constraints for validation.
# Use version ranges that cover the provider versions deployed in your infrastructure.
# Example with AWS provider (adjust based on your environment):
aws = {
source = "hashicorp/aws"
version = ">= 5.0.0, < 7.0.0" # Covers AWS provider 5.x and 6.x
}
# Add other providers as needed (azurerm, google, etc.)
}
}
resource_policy "aws_ebs_volume" "encryption_check" {
# Optional: pre-filter resources before evaluation
filter = attrs.encrypted != null
# Optional: locals for readable logic
locals {
encrypted = core::try(attrs.encrypted, false)
}
# One or more enforce blocks
enforce {
condition = local.encrypted == true
error_message = "EBS volumes must have encryption enabled."
}
}
Available Attribute Surfaces
| Surface | Available in | Notes |
| --- | --- | --- |
| attrs.* | resource / module / provider | Planned values for the current target (existing values for no-op). Wrap optional fields in core::try(). |
| prior_attrs.* | resource_policy with operations limited to update and/or delete | Pre-change values. Not available for create or no-op. Rejected at parse time in provider_policy and module_policy (0.5.0+). |
| meta.provider_type | resource_policy | e.g. "aws". Useful for cross-provider wildcard rules. |
| meta.tfe_workspace.tags["<name>"] | resource_policy, module_policy, provider_policy | Workspace-scoped routing (env, team, etc.). Empty when evaluating a Stack or an untagged workspace. |
| meta.tfe_stack.deployment_name / stack_name / deployment_group | resource_policy, module_policy, provider_policy | Stack metadata for routing/exclusion workflows. Always present; fields are empty strings outside Stack evaluations on 0.3.x/0.4.x, and null on 0.5.0+ (guard with != null). Available in .policytest.hcl mocks starting in 0.3.x. |
| meta.address | ❌ | UNDEFINED in resource_policy real-plan evaluation. Never interpolate it into error_message. |
| input.<name> | all | Values from input {} blocks; overridable per policy set. |
Meta attributes nullable on 0.5.0+
Starting in tfpolicy 0.5.0, absent meta attributes evaluate to null rather than an empty string. Nullable: meta.alias (provider_policy), meta.version (provider_policy, module_policy), and meta.tfe_stack.deployment_group / deployment_name / stack_name (all policy types; null in workspace evaluations or when not set). meta.tfe_workspace.tags stays an empty map. Guard nullable attributes with a conditional before passing them to a function or string template, because && does not short-circuit:
condition = meta.version != null ? core::semverconstraint(meta.version, ">= 2.0.0") : false
filter = meta.alias == "secondary" # == is null-safe
Operation Scoping and prior_attrs
# Skip destroy
resource_policy "tfe_workspace" "require_tags" {
operations = ["create", "update"]
enforce {
condition = core::length(core::try(attrs.tag_names, [])) > 0
error_message = "Workspace must have at least one tag."
}
}
# Delete-gate
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, [])
}
enforce {
condition = core::contains(local.prior_tag_names, "delete")
error_message = "Add 'delete' tag before destroying the workspace."
}
}
# tfpolicy 0.4.0+: evaluate every resource in state, including unchanged ones
resource_policy "aws_cloudtrail" "logging_enabled" {
# operations omitted = ["create", "update", "no-op"]
enforce {
condition = attrs.enable_logging == true
error_message = "CloudTrail logging must be enabled."
}
}
Rules:
operations = ["create", "update"]— fires on create/update, skips destroy.operations = ["delete"]— fires only on destroy;prior_attrsholds pre-change state.operations = ["update"]— fires only on updates;prior_attrsavailable.operations = ["no-op"]— (0.4.0+) fires only on resources the run leaves unchanged;attrsholds the existing values andprior_attrsis unavailable.- Default (no
operations): tfpolicy 0.4.0+ = create, update, and no-op (the entire state, never destroy) for policies that do not referenceprior_attrs; tfpolicy 0.3.x = create and update only. Policies that referenceprior_attrshave no default and must setoperationsexplicitly (omitting it is a hard error). Setoperations = ["create", "update"]on 0.4.0+ to evaluate only changed resources. operations = []is unconstrained on 0.4.0+: it evaluates every operation, includingno-opanddelete(whereattrsis null), so attrs checks also fire on destroys. Prefer omittingoperations.[]is rejected for policies that referenceprior_attrs.create,update, andno-opexposeattrs;updateanddeleteexposeprior_attrs.deletecannot be combined withcreateorno-op(["update", "delete"]is valid), andprior_attrscannot be used withcreateorno-op. Replacements are evaluated as separate delete and create operations, so split them into tworesource_policyblocks.meta.operationcan be"create","update","delete", or (0.4.0+)"no-op".core::getresourceswarning (0.4.0+): an attrs-only policy that callscore::getresourceswithoperationsomittingno-oploads with a warning, because it runs only for changed resources and can miss pre-existing ones. Addno-op, or keep the list if changes-only is intended. No warning is raised for policies that referenceprior_attrs(never addno-opto those; it fails validation), for lists containingdelete, or forcore::getresourcescalls in file-levellocals. Because the recommended top-levellocalscaching pattern never triggers the warning, chooseoperationsdeliberately in that case (usually includingno-op).- Upgrade note (0.4.0+): policies that omit
operations, including all bundled conversion examples, start evaluating unchanged resources after moving from 0.3.x. A mandatory policy can begin blocking runs because of resources that already existed.
| Goal (0.4.0+) | operations | Attributes |
| --- | --- | --- |
| Every resource meets the policy | omit, or ["create", "update", "no-op"] | attrs |
| Only resources this run touches | ["create", "update"] | attrs |
| Block certain changes | ["update"] | attrs and prior_attrs |
| Protect from deletion | ["delete"] | prior_attrs |
input Blocks — Parameterization
input "allowed_instance_types" {
type = list(string)
default = ["t3.micro", "t3.small", "t3.medium"]
}
resource_policy "aws_instance" "allowed_types" {
enforce {
condition = core::contains(input.allowed_instance_types, attrs.instance_type)
error_message = "Instance type '${attrs.instance_type}' is not in the allowed list."
}
}
Policy sets can override input defaults without editing the policy file. Use input for: allowlists, blocklists, version constraints, numeric thresholds — values an operator may need to tune per environment.
Rule — input vs hardcoded locals:
- Use
input {}only for operator-tunable values: allowlists, blocklists, thresholds, time windows. If a value varies per environment or policy set, it belongs ininput. - Use
localsor inline literals for invariant enforcement constants — values that are part of the policy logic itself and should NOT be overridden (e.g. a fixed list of well-known dangerous ports defined by a security standard, a required protocol name). - Do NOT promote fixed enforcement constants to
inputunless the requirement explicitly says they are configurable.
core:: Functions — Common Idioms
-
Null safety:
core::try(attrs.field, default)— single layer; don't nest. 🔴 MANDATORY: always use the two-step pattern below when the attribute may be explicitlynull. -
Membership:
core::contains(list, value)— for lists. For string substring usecore::contains_substring. -
Strings:
core::startswith,core::endswith,core::contains_substring,core::regex(throws on no match — wrap incore::try),core::split(separator, string)(use withcore::parseint()for numeric decomposition — seeverified-syntax.mdSection 2 for full examples). ❌ Never use+for string concatenation —+is numeric addition only; using it with strings throwsError: Unsuitable value for left operand: a number is required. ✅ Use"${local.var}"string interpolation instead: e.g."table/${local.table_name}"not"table/" + local.table_name. -
Aggregates:
core::length(list_or_map). On tfpolicy 0.3.x+, usecore::alltrue(list)andcore::anytrue(list)for boolean collection checks; on tfpolicy 0.2.x, use filtered-count patterns instead. Seeverified-syntax.mdfor exact empty-list, unknown, and coercion behavior. -
Ranges:
core::range(limit)→[0, 1, …, limit-1];core::range(lower, upper)→[lower, lower+1, …, upper-1];core::range(lower, upper, step)→ step-incremented list fromlowerup to (but not including)upper. Works with hardcoded integer literals. ⚠️ With dynamicattrs.*integer values (e.g.attrs.from_port,attrs.to_port)core::range()silently returns an empty list in the policytest framework — prefer the count approach for port-range policies (seeverified-syntax.mdMistake 23). -
Time:
core::timestamp(),core::formatdate("EEEE", core::timestamp())(weekday, UTC),core::parseint(core::formatdate("HH", core::timestamp()), 10)(hour, UTC). -
Semver:
core::semverconstraint(version, "~> 4.67.0")— supports=,>=,<,~>, range,!=. Always wrap incore::try(..., false)to handle non-semver or unparseable version strings gracefully. ⚠️ Prefer this overcore::split+core::parseintfor all version range checks converted from Sentinel string comparisons — manual integer parsing fails silently for non-numeric version suffixes and null/empty inputs.🔴 NEVER place
core::semverconstraintdirectly in afilter =expression. Even with!= nulland!= ""guards in the same expression,semverconstraintis evaluated regardless of short-circuit ordering in thefiltercontext and throws a parse error when the version string is malformed (e.g. a non-semver string like"x.y") ornull/empty. Always move it intolocalsand wrap withcore::try(..., false):# ❌ Wrong — crashes when version string is non-semver, null, or empty: filter = core::try(attrs.version, null) != null && core::try(attrs.version, "") != "" && core::semverconstraint(core::try(attrs.version, "0.0"), "< 2.0") # ✅ Correct — filter guards null/empty only; semverconstraint lives in locals: filter = core::try(attrs.version, null) != null && core::try(attrs.version, "") != "" locals { version = core::try(attrs.version, "") # core::try wraps semverconstraint to safely handle non-semver strings → false is_old = core::try(core::semverconstraint(local.version, "< 2.0"), false) # When version is old, enforce the required attribute; when version >= 2.0, always compliant is_compliant = !local.is_old || local.required_attr_set } -
Null safety — two-step pattern (MANDATORY for any attribute that may be explicitly
null):core::try(attrs.field, default)triggers the fallback only when the attribute access throws an error (key absent). When an attribute is explicitly set tonull,core::tryreturnsnull— not the default. This is a silent pitfall:core::length(null)crashes withInvalid value for "collection" parameter;null == falseevaluates asnull(nottrue), causing enforce to trigger unexpectedly.Always use the explicit two-step pattern:
# Collection attribute (list/map) — safe pattern: field_raw = core::try(attrs.field, null) field = local.field_raw != null ? local.field_raw : [] # ✅ Safe to pass to: core::length(), core::contains(), for expressions # Scalar boolean attribute — safe pattern: flag_raw = core::try(attrs.flag, null) flag = local.flag_raw == null ? false : local.flag_raw # ✅ Safe to use in: condition = !local.flag, condition = local.flag == falseFor
filterexpressions that must exclude bothnulland empty-string values:filter = core::try(attrs.field, null) != null && core::try(attrs.field, "") != "". The two-step rule applies at every nesting level. When a scalar is accessed through a nested path (e.g.core::try(local.list[0].scalar_attr, default)), apply the same pattern: if the attribute may benull, usecore::try(..., null)and normalize explicitly. -
JSON:
core::jsondecode(string)— parses a JSON string into an object/list.core::jsonencode(value)— encodes a value as a JSON string. ❌json::unmarshaldoes not exist — usecore::jsondecodeinstead. -
Nested block attribute schema — object vs list: Terraform provider schemas define nested blocks as either a list of objects (
[{ ... }]) or a single object ({ ... }). Always check the provider schema before accessing nested attributes:- List block (e.g.
encryption_config = [{ provider = [{ key_arn = "..." }] }]): access via indexattrs.encryption_config[0].provider[0].key_arn. Usecore::try(attrs.field, [])andfield[0].subattr. - Object block (e.g.
redirect = { port = "443", protocol = "HTTPS" }): access directlyattrs.redirect.port. Usecore::try(attrs.redirect.port, ""). - ❌ Never call
core::length()on an object —core::lengthrequires a list, map, or tuple. Callingcore::length(attrs.redirect)whenredirectis an object crashes withcollection must be a list, a map or a tuple. To check presence of an object block, usecore::try(attrs.redirect, null) != nullinstead. - ❌ Never iterate over an object block with a
forexpression.for r in core::try(attrs.block, [])— whenattrs.blockis an object, this iterates over the object's scalar values, not the object as an element.core::try(r.sub_attr, "")on a string silently returns"". Use direct attribute access instead:core::try(attrs.block.sub_attr, ""). - When Sentinel mocks use
redirect = { ... }(object), the TFPolicy test mock and policy must treat it as an object. When Sentinel mocks useredirect = [{ ... }](list), use list indexing. Mismatching the shape causes either runtime crashes or silent wrong results.
- List block (e.g.
IAM Policy Checks
When enforcing IAM content rules (e.g. "no admin *:* allowed", "no wildcard actions"), you MUST cover all 4 inline policy resource types — not just aws_iam_policy.
🔴 Always write 4 resource_policy blocks for IAM content enforcement:
| Resource type | When it's used | policy attribute |
|---|---|---|
| aws_iam_policy | Standalone managed policy | JSON string — core::jsondecode(core::try(attrs.policy, "{}")) |
| aws_iam_role_policy | Inline policy attached to a role | JSON string — same pattern |
| aws_iam_user_policy | Inline policy attached to a user | JSON string — same pattern |
| aws_iam_group_policy | Inline policy attached to a group | JSON string — same pattern |
Rule: A policy that only checks aws_iam_policy misses inline policies on roles/users/groups. An admin could bypass it by using aws_iam_role_policy instead of aws_iam_policy.
Note on aws_iam_policy_document: This resource type requires careful distinction between two different use cases:
- As a Terraform
datablock (the common case in real Terraform configurations) —data_policydoes not exist in tfpolicy (Mistake 31). Do NOT writedata_policy "aws_iam_policy_document". In this scenario, the policy document content is consumed by one of the 4 inline/managed policy resource types above, and enforcement should target those resource types. - As a
resourcein.policytest.hclmocks and when the Sentinel source reads it viatfstate/v2—resource_policy "aws_iam_policy_document"is valid and directly targets the document'sstatementattribute (lowercaseactions, notAction). When a Sentinel policy readsaws_iam_policy_documentfromtfstate, the correct TFPolicy conversion isresource_policy "aws_iam_policy_document"— do NOT substitute inline/managed policy resource types.
Decision rule: Check the Sentinel import statement. If the Sentinel uses tfstate/v2 to read aws_iam_policy_document resources, convert to resource_policy "aws_iam_policy_document". If the Sentinel reads the consuming resource (aws_iam_role_policy, etc.), target those 4 types instead.
# ✅ CORRECT — define the check logic once, repeat for all 4 resource types
# (Each resource_policy block is independent; locals are block-scoped)
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 ful