AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

terraform-policy

Write, test, or convert Terraform Policy files (.policy.hcl, .policytest.hcl, Sentinel→tfpolicy). Triggers: policy.hcl, policytest, convert sentinel, tfpolicy, write a policy.

Original source
hashicorp
License
MPL-2.0
Pinned revision
bc6b14b77481c3cbfbb06a0166be7245ed45798c

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

This skill also requires local files or dependencies. Remote reading alone may not be enough.

Ask your assistant

Use Agentic Memory skills to read hashicorp--terraform-policy at revision bc6b14b77481c3cbfbb06a0166be7245ed45798c, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 22

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.hcl file ("block public RDS", "require encryption", "deny instance types outside an allowlist").
  • The user has a Sentinel .sentinel file (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, or provider_policy block.
  • 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() or core::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.hcl test file — use tfpolicy-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_providers is mandatory for .policy.hcl validation.
  • 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_providers declares provider source and version constraints for validation. This is distinct from meta.version in provider_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_attrs holds pre-change state.
  • operations = ["update"] — fires only on updates; prior_attrs available.
  • operations = ["no-op"] — (0.4.0+) fires only on resources the run leaves unchanged; attrs holds the existing values and prior_attrs is unavailable.
  • Default (no operations): tfpolicy 0.4.0+ = create, update, and no-op (the entire state, never destroy) for policies that do not reference prior_attrs; tfpolicy 0.3.x = create and update only. Policies that reference prior_attrs have no default and must set operations explicitly (omitting it is a hard error). Set operations = ["create", "update"] on 0.4.0+ to evaluate only changed resources.
  • operations = [] is unconstrained on 0.4.0+: it evaluates every operation, including no-op and delete (where attrs is null), so attrs checks also fire on destroys. Prefer omitting operations. [] is rejected for policies that reference prior_attrs.
  • create, update, and no-op expose attrs; update and delete expose prior_attrs. delete cannot be combined with create or no-op (["update", "delete"] is valid), and prior_attrs cannot be used with create or no-op. Replacements are evaluated as separate delete and create operations, so split them into two resource_policy blocks.
  • meta.operation can be "create", "update", "delete", or (0.4.0+) "no-op".
  • core::getresources warning (0.4.0+): an attrs-only policy that calls core::getresources with operations omitting no-op loads with a warning, because it runs only for changed resources and can miss pre-existing ones. Add no-op, or keep the list if changes-only is intended. No warning is raised for policies that reference prior_attrs (never add no-op to those; it fails validation), for lists containing delete, or for core::getresources calls in file-level locals. Because the recommended top-level locals caching pattern never triggers the warning, choose operations deliberately in that case (usually including no-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 in input.
  • Use locals or 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 input unless 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 explicitly null.

  • Membership: core::contains(list, value) — for lists. For string substring use core::contains_substring.

  • Strings: core::startswith, core::endswith, core::contains_substring, core::regex (throws on no match — wrap in core::try), core::split(separator, string) (use with core::parseint() for numeric decomposition — see verified-syntax.md Section 2 for full examples). ❌ Never use + for string concatenation — + is numeric addition only; using it with strings throws Error: 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+, use core::alltrue(list) and core::anytrue(list) for boolean collection checks; on tfpolicy 0.2.x, use filtered-count patterns instead. See verified-syntax.md for 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 from lower up to (but not including) upper. Works with hardcoded integer literals. ⚠️ With dynamic attrs.* 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 (see verified-syntax.md Mistake 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 in core::try(..., false) to handle non-semver or unparseable version strings gracefully. ⚠️ Prefer this over core::split + core::parseint for 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::semverconstraint directly in a filter = expression. Even with != null and != "" guards in the same expression, semverconstraint is evaluated regardless of short-circuit ordering in the filter context and throws a parse error when the version string is malformed (e.g. a non-semver string like "x.y") or null/empty. Always move it into locals and wrap with core::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 to null, core::try returns null — not the default. This is a silent pitfall: core::length(null) crashes with Invalid value for "collection" parameter; null == false evaluates as null (not true), 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 == false
    

    For filter expressions that must exclude both null and 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 be null, use core::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::unmarshal does not exist — use core::jsondecode instead.

  • 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 index attrs.encryption_config[0].provider[0].key_arn. Use core::try(attrs.field, []) and field[0].subattr.
    • Object block (e.g. redirect = { port = "443", protocol = "HTTPS" }): access directly attrs.redirect.port. Use core::try(attrs.redirect.port, "").
    • ❌ Never call core::length() on an object — core::length requires a list, map, or tuple. Calling core::length(attrs.redirect) when redirect is an object crashes with collection must be a list, a map or a tuple. To check presence of an object block, use core::try(attrs.redirect, null) != null instead.
    • ❌ Never iterate over an object block with a for expression. for r in core::try(attrs.block, []) — when attrs.block is 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 use redirect = [{ ... }] (list), use list indexing. Mismatching the shape causes either runtime crashes or silent wrong results.

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 data block (the common case in real Terraform configurations) — data_policy does not exist in tfpolicy (Mistake 31). Do NOT write data_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 resource in .policytest.hcl mocks and when the Sentinel source reads it via tfstate/v2 — resource_policy "aws_iam_policy_document" is valid and directly targets the document's statement attribute (lowercase actions, not Action). When a Sentinel policy reads aws_iam_policy_document from tfstate, the correct TFPolicy conversion is resource_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