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/verified-syntax.md

Terraform Policy - Verified Syntax Reference

Shared reference used by all sibling skills in references/: tfpolicy-author | tfpolicy-test

Last Updated: 2026-02-24 Status: All patterns user-verified during private beta Purpose: Source-of-truth quick reference. Sub-skills link here rather than duplicating facts.


Critical Rules

1. ✅ Semantic Versioning (VERIFIED)

Rule: Use core::semverconstraint() for ALL version comparisons

# ✅ Correct
condition = core::semverconstraint(meta.version, ">= 4.0.0, < 5.0.0")

# ❌ Wrong
condition = meta.version >= 4.0  # Don't use direct comparison

Constraint syntax:

  • "= 4.67.0" - Exact version
  • ">= 4.0.0" - Minimum
  • "< 5.0.0" - Maximum
  • "~> 4.67.0" - Pessimistic patch (>= 4.67.0, < 4.68.0)
  • "~> 4.0" - Pessimistic minor (>= 4.0.0, < 5.0.0)
  • ">= 4.0.0, < 5.0.0" - Multiple constraints (AND)
  • "!= 4.50.0" - Exclude version

2. ✅ Core Function Prefix (VERIFIED)

Rule: ALL built-in Terraform functions require core:: prefix

# ✅ Correct
filter = core::try(attrs.encrypted, false) == true
is_allowed = core::length([for v in local.version_checks : v if v]) > 0
error_message = "Allowed: ${core::join(", ", local.allowed_versions)}"

# ❌ Wrong
filter = try(attrs.encrypted, false) == true  # Missing core:: prefix

Common functions:

  • core::try(expr, default) - Safe access with fallback
  • core::contains(list, value) - List membership (lists only, NOT strings!)
  • core::length(list_or_string) - List/string/map length (✅ works on all!)
  • core::keys(map) - Get map keys as list (✅ requires core:: prefix)
  • core::join(separator, list) - Join list elements
  • core::semverconstraint(version, constraint) - Version comparison
  • core::getresources(type, filter_map) - Query related resources
  • core::alltrue(list) / core::anytrue(list) - Boolean collection helpers, available starting in tfpolicy 0.3.0. See core::alltrue() and core::anytrue() for exact empty-list, unknown, and coercion behavior.

⚠️ IMPORTANT: core::getresources() filter behavior with unknown attribute values.

  • The filter_map argument is required by the function signature (omitting it → "Not enough function arguments"). Passing {} matches everything; passing { attr = value } performs equality matching.
  • Caveat: when the target attribute on a candidate resource is unknown at plan time (e.g. bucket = aws_s3_bucket.x.id where aws_s3_bucket.x is being created in the same plan), the equality comparison evaluates to unknown and the engine conservatively includes that candidate in the result set. The filter is not "ignored" — but it cannot narrow results past any candidate whose target attribute is computed.
  • Verified on terraform 1.15.0-policy20261105 / tfpolicy 0.0.2-beta20260513 / tfpolicy-plugin 0.0.2-beta20260422.
  • Production impact: any cross-resource policy on a first-time-create plan (where related resources reference each other via .id) will see every candidate, not the matching one. Update plans against existing infrastructure (where target attributes are already known) filter correctly.
  • Pattern choice — constant filter vs. attrs.* filter:
    • When the filter value is a known constant AND no secondary attrs.* filtering is needed inside resource_policy: you MAY call core::getresources() once in a top-level locals block. A valid example is a truly account-level resource with no per-parent link:
      # ✅ CORRECT — aws_s3_account_public_access_block is account-level; no per-bucket link
      locals {
        account_pab = core::getresources("aws_s3_account_public_access_block", {})
      }
      resource_policy "aws_s3_bucket" "account_block_required" {
        locals {
          pab               = core::length(local.account_pab) > 0 ? local.account_pab[0] : null
          block_public_acls = local.pab != null ? core::try(local.pab.block_public_acls, false) : false
        }
      }
      
    • When the filter value comes from attrs.* (e.g. attrs.id, attrs.name, attrs.arn) OR when any secondary filtering inside resource_policy is by attrs.*: use an inline core::getresources() call with the specific per-resource filter inside resource_policy. The top-level cache with a {} empty filter plus HCL-side attrs.* filtering is the wrong pattern — see Mistake 13 CRITICAL note below.
      # ✅ CORRECT — filter value "table/${attrs.name}" comes from attrs.* — must be inline
      resource_policy "aws_dynamodb_table" "autoscaling_required" {
        locals {
          table_resource_id = "table/${attrs.name}"
          scaling_targets   = core::getresources("aws_appautoscaling_target", {
            resource_id = local.table_resource_id
          })
        }
      }
      # ❌ WRONG — top-level {} cache + HCL filter by attrs.* is the anti-pattern
      # locals { all_targets = core::getresources("aws_appautoscaling_target", {}) }
      # resource_policy "aws_dynamodb_table" { locals { filtered = [for t in local.all_targets : t if t.resource_id == "table/${attrs.name}"] } }
      
    • ⚠️ DynamoDB autoscaling is ALWAYS the inline pattern (Pattern B). Even pre-filtering at the top level by a constant scalable_dimension does not make it Pattern A — the secondary resource_id == "table/${attrs.name}" filter inside resource_policy is still derived from attrs.name, so the correct approach is an inline core::getresources() call filtered by resource_id. Pre-filtering by scalable_dimension at the top level forces you to add the attrs.*-derived resource_id filter inside resource_policy, which is the anti-pattern. Use the inline call and apply the constant scalable_dimension check as a simple HCL filter after the inline fetch.

  • ⚠️ When the filter value is derived from attrs.* and that attribute is unknown at plan time (e.g. bucket = aws_s3_bucket.x.id for a newly-created resource), the equality comparison evaluates to unknown — the engine conservatively includes that candidate in the result set, so first-time-create plans with cross-references are unreliable. Most reliable on updates and existing infrastructure where target values are known.
  • ⛔ All dependent child resources — always use the inline filter pattern, NOT the top-level {} cache. This applies to aws_s3_bucket_public_access_block, aws_s3_bucket_acl, aws_s3_bucket_server_side_encryption_configuration, aws_s3_bucket_policy, aws_appautoscaling_target, aws_appautoscaling_policy, and any resource type that has a (Required) or (Optional) argument referencing a parent resource. Call core::getresources() inline inside the parent resource_policy with the specific filter (e.g. {bucket = attrs.id}, {resource_id = local.table_resource_id}). Do NOT use the top-level cache {} + HCL for-loop pattern for these types. See Mistake 13.

CRITICAL: core::getresources() Attribute Access:

  • Resources returned have attributes at top level (NOT through .attrs)
  • Example: resource.name ✅ NOT resource.attrs.name ❌
  • This is DIFFERENT from current resource context where you use attrs.name
  • Pattern: For dependent child resources (any type with a (Required) or (Optional) argument referencing a parent by .id, .arn, or .name): use inline core::getresources() inside resource_policy with the specific per-parent filter; access returned attributes directly at top level (NOT through .attrs). For truly independent/account-level resources: cache in top-level locals with a constant filter (if any), and access returned attributes directly.

✅ String functions available:

  • ✅ core::startswith(string, prefix) - Returns bool. Arg order: full string first, prefix second (same as Sentinel's strings.has_prefix). e.g. core::startswith(meta.version, ">") ✅
  • ✅ core::endswith(string, suffix) - Returns bool
  • ✅ core::contains_substring(string, substr) - Returns bool
  • ✅ core::regex(pattern, string) - Pattern/substring matching. Throws on no match — wrap with core::try(): core::try(core::regex("pattern", string), null) != null
  • ✅ core::split(separator, string) - Splits a string into a list of substrings at each occurrence of separator. Example: core::split("-", "1-100") returns ["1", "100"]; core::split("-", "22") returns ["22"]. Use with core::parseint() to parse port ranges like "start-end" without regex:
    # ✅ Parsing a port range "start-end" using core::split (preferred over regex)
    port_parts  = core::split("-", local.dest_port_range)
    range_start = core::length(local.port_parts) == 2 ? core::try(core::parseint(local.port_parts[0], 10), -1) : -1
    range_end   = core::length(local.port_parts) == 2 ? core::try(core::parseint(local.port_parts[1], 10), -1) : -1
    # Range covers port 22 if start < 22 AND end > 22 (exclusive, matching Sentinel logic)
    is_range_ssh = local.range_start < 22 && local.range_end > 22
    
    Note: ternary short-circuits, so core::parseint is only called when core::length == 2. When the port string is not a range (e.g. "22" or "*"), range_start and range_end default to -1, making the range check false without any index-out-of-bounds risk.
  • ❌ Substring matching via core::contains() — only works for lists, NOT strings
    # Prefix check using core::startswith()
    starts_with_open = core::startswith(local.version_value, ">")
    # Substring check using core::regex()
    has_exception = core::try(core::regex("exception", core::try(attrs.description, "")), null) != null
    

policy.required_providers is mandatory for resource and provider policy validation: A .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. See tfpolicy-author.md for concrete authoring examples.

Starting in tfpolicy 0.3.0, tfpolicy test reuses this same .policy.hcl declaration to validate provider, resource, and data-source policies, plus arguments used by core::getdatasource() and core::getresources(). It checks mocked values, including skip = true resource mocks, against the lowest and highest matching provider versions before evaluation. .policytest.hcl does not declare its own required_providers block — there is no policytest { required_providers { ... } } construct. See tfpolicy-test.md for details.

Validation limitations:

  • Validation is best effort for version ranges. When a range is declared, provider schemas at the lower and upper bounds of the range are evaluated.
  • Wildcard targets such as resource_policy "*" are not schema-validated because they may match multiple resource types.

Provider version constraint checks: In provider_policy, meta.version is the resolved provider version (e.g. "6.50.0"), not the constraint string from required_providers. There is no tfpolicy surface that exposes the constraint string.

⚠️ providers-require-version-style Sentinel policies that check strings.has_prefix(p.version_constraint, ">") inspect the version constraint format string, which tfpolicy does not expose. This check is non-convertible. The closest tfpolicy equivalent enforces that the resolved provider version is within an approved range:

# Sentinel: strings.has_prefix(p.version_constraint, ">")   →  non-convertible
# TFPolicy nearest equivalent — enforce resolved version range instead:
provider_policy "*" "provider_version_range" {
  enforce {
    condition     = core::semverconstraint(meta.version, ">= 4.0.0, < 5.0.0")
    error_message = "Provider version '${meta.version}' must satisfy '>= 4.0.0, < 5.0.0'. Pin the provider to a tested version range to prevent major version upgrades."
  }
}

⚠️ Arg order: core::startswith(string, prefix) — the full string is the first argument, the prefix is the second. Do not reverse them.

✅ JSON functions available:

  • ✅ core::jsondecode(string) — parses a JSON string into an HCL object/list. Use when an attribute contains a serialised JSON value (e.g. an inline IAM policy document).
  • ✅ core::jsonencode(value) — encodes an HCL object/list as a JSON string.
  • ❌ json::unmarshal — does not exist. There is no json:: namespace. Always use core::jsondecode instead.
    locals {
      policy_doc = core::try(core::jsondecode(core::try(attrs.policy, "{}")), {})
      statements = core::try(local.policy_doc.Statement, [])
    }
    

3. ✅ Policy Type Features (VERIFIED)

Rule: ALL policy types support the same features

| Feature | resource_policy | module_policy | provider_policy | |---------|----------------|---------------|-----------------| | locals {} | ✅ Yes | ✅ Yes | ✅ Yes | | filter clause | ✅ Yes | ✅ Yes | ✅ Yes | | Multiple enforce | ✅ Yes | ✅ Yes | ✅ Yes |

IMPORTANT: Language server shows FALSE ERRORS for locals in provider_policy

  • Error: "No declaration found for local.variable"
  • These are safe to ignore - syntax is valid
  • Runtime evaluation works correctly

4. ✅ CRITICAL: Blocks vs Attributes Schema Distinction

Rule: Provider schema representation determines how you access nested configuration

Blocks vs Attributes:

  • BLOCKS → Represented as lists of maps (even if only one allowed)
    • Require array indexing: attrs.block_name[0].field
    • Examples: default_tags, assume_role, lifecycle
  • ATTRIBUTES → Represented as direct values (maps, strings, numbers, etc.)
    • Direct access: attrs.attribute_name
    • Examples: region, tags, instance_type

Examples:

# ✅ BLOCK access (default_tags in AWS provider)
# Schema: default_tags = [ { tags = { "Env" = "Dev" } } ]
default_tags_map = core::try(attrs.default_tags[0].tags, {})  # Need [0] index

# ✅ ATTRIBUTE access (tags on resources)
# Schema: tags = { "Env" = "Dev" }
has_tags = attrs.tags != null && core::length(attrs.tags) > 0  # Direct access, no [0]

# Note: core::length() works directly on maps, no need for core::keys()

How to determine Block vs Attribute:

  1. Check provider schema documentation
  2. Use terraform console to inspect structure
  3. If accessing nested field fails without [0], it's a Block

5. ✅ Input Blocks — Runtime Parameterization (VERIFIED)

Rule: Use input blocks instead of hardcoded locals for values that vary per policy set. Never claim Sentinel param cannot be replicated — input is the direct equivalent.

# ✅ Correct — parameterized, overridable per policy set
input "allowed_providers" {
  type    = list(string)
  default = ["registry.terraform.io/hashicorp/aws"]
}

provider_policy "*" "providers_allowlist" {
  enforce {
    condition     = core::contains(input.allowed_providers, meta.source)
    error_message = "Provider '${meta.source}' not allowed. Permitted: ${core::join(", ", input.allowed_providers)}."
  }
}

# ❌ Wrong — hardcoding what should be configurable
locals {
  allowed_providers = ["registry.terraform.io/hashicorp/aws"]  # Never override without editing policy file
}

Supported types: string, number, bool, list(string), list(number), map(string) Override mechanism: .tfpolicy.metadata.json at policy-set scope, or per-evaluation overrides. Use for: allowlists, blocklists, version constraints, limits, thresholds — any value the operator may want to tune.


6. ✅ Operations Scoping + prior_attrs (VERIFIED)

Rule: Use operations = [...] to restrict when a policy fires. Use prior_attrs to read pre-change state on delete/update. (tfpolicy 0.4.0+ adds the "no-op" operation.)

# ✅ Fires only on create and update — never on destroy
resource_policy "tfe_workspace" "require_project" {
  operations = ["create", "update"]
  enforce {
    condition     = core::try(attrs.project_id, "") != ""
    error_message = "tfe_workspace must have project_id set."
  }
}

# ✅ Delete-gate: check prior state before workspace is destroyed
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, [])
    had_delete_tag  = core::contains(local.prior_tag_names, "delete")
  }
  enforce {
    condition     = local.had_delete_tag
    error_message = "Add 'delete' tag before destroying a workspace."
  }
}

Key rules:

  • operations = ["create", "update"] — skips destroy and, on 0.4.0+, unchanged resources; on 0.3.x it is equivalent to Sentinel rc.change.actions is not ["delete"], but on 0.4.0+ omit operations to match it, since Sentinel's resource_changes also includes unchanged resources
  • operations = ["delete"] — fires only on destroy; prior_attrs holds the before-state
  • operations = ["no-op"] (0.4.0+) — fires only on resources the run leaves unchanged; attrs holds the existing values and prior_attrs is unavailable
  • prior_attrs is only available when operations is limited to "update" and/or "delete"; it is never available for "create" or "no-op"
  • Default (no operations): 0.4.0+ = fires on create, update, and no-op for policies that do not reference prior_attrs (policies that reference prior_attrs must set operations explicitly); 0.3.x = create and update. On 0.4.0+, use operations = ["create", "update"] to skip unchanged resources
  • A policy cannot list "delete" together with "create" or "no-op" in operations. Replacement plans are evaluated as separate delete and create operations, so split policies targeting both operations into separate resource_policy blocks.
  • On 0.4.0+, an attrs-only policy that calls core::getresources and omits no-op from operations loads with a warning; add no-op unless changes-only is intended

7. ✅ Time Functions (VERIFIED)

Rule: core::timestamp(), core::formatdate(), and core::parseint() exist. Never generate placeholder policies claiming time functions are unavailable.

# ✅ Day-of-week restriction
input "restricted_weekdays_utc" {
  type    = list(string)
  default = ["Friday", "Saturday", "Sunday"]
}

resource_policy "tfe_workspace" "deny_apply_day_of_week" {
  locals {
    current_weekday = core::formatdate("EEEE", core::timestamp())  # "Monday", "Friday", etc.
    is_restricted   = core::contains(input.restricted_weekdays_utc, local.current_weekday)
  }
  enforce {
    condition     = !local.is_restricted
    error_message = "Apply blocked on ${local.current_weekday} (UTC). Restricted days: ${core::join(", ", input.restricted_weekdays_utc)}."
  }
}

# ✅ Hour-of-day restriction
input "restricted_hours_utc" {
  type    = list(number)
  default = [8, 9, 10, 11, 12]
}

resource_policy "tfe_workspace" "deny_apply_hour_of_day" {
  locals {
    current_hour = core::parseint(core::formatdate("HH", core::timestamp()), 10)
    is_restricted = core::contains(input.restricted_hours_utc, local.current_hour)
  }
  enforce {
    condition     = !local.is_restricted
    error_message = "Apply blocked during hour ${local.current_hour} UTC."
  }
}

Available time functions:

  • core::timestamp() — current UTC time as RFC3339 string
  • core::formatdate(spec, timestamp) — format specifiers: "EEEE" (weekday name), "HH" (hour 00-23), "DD" (day), "MM" (month), "YYYY" (year)
  • core::timeadd(timestamp, duration) — add duration (e.g. "24h", "-1h")
  • core::timecmp(ts1, ts2) — compare two timestamps
  • core::parseint(string, base) — parse string to integer (e.g. core::parseint("08", 10) → 8)
  • Note: All times are UTC. Express restricted windows in UTC.

8. ✅ Naming Conventions (VERIFIED)

resource_policy block names — use snake_case derived from the enforcement requirement:

# ✅ Correct — descriptive snake_case
resource_policy "aws_s3_bucket" "versioning_required" { }
resource_policy "aws_iam_policy" "no_admin_privileges" { }
resource_policy "aws_ecs_task_definition" "secure_networking_mode_and_user" { }

# ❌ Wrong — generic names that don't describe the check
resource_policy "aws_s3_bucket" "check" { }
resource_policy "aws_s3_bucket" "all_checks" { }
resource_policy "aws_s3_bucket" "policy" { }

Rules:

  • Use snake_case (underscores, lowercase). Never use kebab-case (hyphens) in block names.
  • Name should reflect the enforcement requirement, not the resource type (the type is already in the first argument).
  • When a single resource type has multiple enforce blocks (the correct pattern), choose one name that describes the combined requirement rather than the individual checks.
  • For IAM 4-type rules, use the same policy_name across all 4 blocks (e.g. no_admin_privileges) — the resource type in the first argument differentiates them.

9. ✅ core::try() Default Type Selection (VERIFIED)

Choose the default value based on the semantic type of the attribute — do NOT mix defaults for the same attribute across related checks:

| Attribute type | Correct default | Rationale | |---|---|---| | Boolean | false | Absent boolean = permissive default (fails the check correctly) | | Required string | "" | Absent string = empty = fails non-empty checks correctly | | List / set | [] | Absent list = empty = length checks correctly return 0 | | Map / object | {} | Absent map = empty = key lookups return null | | "Must detect unset separately from empty" | null | When "" and null must be treated differently by the condition |

# ✅ Correct defaults by type
encrypted        = core::try(attrs.encrypted, false)          # boolean
bucket_name      = core::try(attrs.bucket, "")                 # string
tag_names        = core::try(attrs.tag_names, [])              # list
tags             = core::try(attrs.tags, {})                   # map
optional_config  = core::try(attrs.config, null) != null       # detect presence

⚠️ Using the wrong default silently masks violations:

  • core::try(attrs.encrypted, true) — absent = treated as encrypted = violation missed
  • core::try(attrs.tag_names, ["compliant"]) — absent = treated as tagged = violation missed

Common Mistakes to Avoid

❌ Mistake 1: Direct Version Comparison

# Wrong
condition = meta.version < 5.0

Fix: Use core::semverconstraint(meta.version, "< 5.0.0")

❌ Mistake 2: Direct Attribute Access Without try()

# Wrong - Crashes when attribute doesn't exist
has_region = attrs.region != null

# Wrong - Still crashes even with double check!
condition = attrs.encrypted != null && attrs.encrypted == true

Fix: Use two-step safe access pattern:

# Correct
region_value = core::try(attrs.region, null)
has_region = local.region_value != null

Why: Cannot test attribute existence before accessing (no "attr" in attrs syntax). Must use core::try() first.

❌ Mistake 4: Trusting Language Server Errors

# Language server shows error, but syntax is valid:
provider_policy "aws" "example" {
    locals {  # ❌ False error: "No declaration found"
        version_check = ...
    }
}

Fix: Ignore language server errors for locals in provider_policy - they're false positives

❌ Mistake 6: Filter Without Length Check

# Suboptimal - doesn't filter empty collections
filter = attrs.ingress != null

# Better - filters both null and empty
filter = attrs.ingress != null && core::length(attrs.ingress) > 0

Fix: Check both null and length for better performance

❌ Mistake 7: Multi-line Boolean Expressions

# Wrong - causes syntax errors
is_exact = local.has_version &&
           !core::contains(meta.version, "~