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 · 48000

s only valid on resource blocks resource "aws_s3_bucket" "test_violation" { expect_failure = true attrs = { acl = "public-read" } }

**Fix:** `expect_failure` is only supported on `resource` test blocks, not `data` blocks.

### ❌ Mistake 23: Assuming TFPolicy Cannot Check Integer Port Ranges
```hcl
# ❌ WRONG — Adds a false limitation and requires from_port == to_port,
# which incorrectly rejects valid port-range rules.
locals {
  # LIMITATION: TF Policy cannot dynamically iterate integer ranges.
  # This implementation requires from_port == to_port (single-port rule only).
  is_single_port  = local.from_port == local.to_port
  port_authorized = core::contains(local.authorized_ports, local.from_port)
  is_compliant    = local.is_single_port && local.port_authorized
}

# ❌ ALSO WRONG (tfpolicy < 0.3.0) — core::range() with dynamic attrs.* values silently returns
# an empty list in the policytest framework (policytest limitation only), and core::alltrue()
# does not exist before 0.3.0.
locals {
  ports_in_range   = core::range(local.from_port, local.to_port + 1)  # empty in policytest!
  all_authorized   = core::alltrue([for p in local.ports_in_range : core::contains(local.authorized_ports, p)])
}

# ✅ CORRECT — count how many authorized ports fall inside [from_port, to_port].
# If the count equals the total number of ports in the range, all are authorized.
# Works with dynamic attrs.* values at both plan time and in policytest.
locals {
  authorized_ports     = [80, 443]   # or from input block
  from_port            = core::try(attrs.from_port, 0)
  to_port              = core::try(attrs.to_port, 0)
  authorized_in_range  = [for p in local.authorized_ports : p if p >= local.from_port && p <= local.to_port]
  all_ports_authorized = core::length(local.authorized_in_range) == (local.to_port - local.from_port + 1)
}

Rule: TFPolicy CAN check whether all ports within a dynamic integer range [from_port, to_port] are authorized. Never add a "cannot iterate integer ranges" limitation — it is false.

Why the count approach works:

  • Filter authorized_ports to those within [from_port, to_port]
  • If every port in the range is authorized, the filtered count equals to_port - from_port + 1
  • No range iteration needed — avoids the core::range() + dynamic value policytest issue entirely
  • Verified working with dynamic attrs.from_port / attrs.to_port values

Caution with core::range(): core::range(start, end) works correctly with hardcoded literals. With dynamic attrs.* integer values, it silently returns an empty list in the policytest framework (policytest limitation). Prefer the count approach for port-range policies to guarantee consistent behaviour in both tests and runtime.


❌ Mistake 24: Accessing Optional Nested Blocks Without Null Safety ("unknown condition" error)

# ❌ WRONG — ebs_block_device is optional; absent on instances without EBS.
# If the block is missing, attrs.ebs_block_device[0] is null,
# local.ebs.encrypted is unknown, and condition = unknown throws:
#   Error: unknown condition
resource_policy "aws_instance" "ebs_encrypted" {
  locals {
    ebs          = attrs.ebs_block_device[0]     # ❌ null if block absent
    is_encrypted = local.ebs.encrypted           # ❌ unknown propagation
  }
  enforce {
    condition     = local.is_encrypted == true   # ❌ "unknown condition" ERROR
    error_message = "EBS block devices must be encrypted."
  }
}

# ❌ ALSO WRONG — Multiple optional nested blocks combined without null guards.
# If either block is absent, the condition evaluates to unknown.
resource_policy "aws_instance" "check" {
  locals {
    ebs_encrypted = attrs.ebs_block_device[0].encrypted        # ❌ crashes if absent
    nic_sg        = attrs.network_interface[0].security_groups  # ❌ crashes if absent
  }
  enforce {
    condition = local.ebs_encrypted == true && core::length(local.nic_sg) > 0
  }
}

# ✅ CORRECT — Use filter to scope to resources with the block,
# convert set to list, then use core::try for safe attribute access.
resource_policy "aws_instance" "ebs_encrypted" {
  # Only evaluate instances that have at least one EBS block device configured
  filter = core::try(attrs.ebs_block_device, null) != null && core::try(core::length(attrs.ebs_block_device), 0) > 0

  locals {
    ebs_devices   = [for d in attrs.ebs_block_device : d]  # set → list
    # Count devices that are NOT encrypted; if zero, all are encrypted
    unencrypted   = [for d in local.ebs_devices : d if !core::try(d.encrypted, false)]
    all_encrypted = core::length(local.unencrypted) == 0
  }

  enforce {
    condition     = local.all_encrypted
    error_message = "All EBS block devices on the instance must have encryption enabled."
  }
}

# ✅ CORRECT — Multiple optional nested blocks: guard each independently.
resource_policy "aws_instance" "check" {
  locals {
    ebs_raw       = core::try(attrs.ebs_block_device, null)
    has_ebs       = local.ebs_raw != null ? core::length(local.ebs_raw) > 0 : false
    ebs_devices   = local.has_ebs ? [for d in local.ebs_raw : d] : []
    # ✅ "no unencrypted devices" pattern — works on any tfpolicy version.
    # On 0.3.0+, core::alltrue([for d in local.ebs_devices : core::try(d.encrypted, false)]) is equivalent.
    unencrypted   = [for d in local.ebs_devices : d if core::try(d.encrypted, false) != true]
    all_encrypted = !local.has_ebs || core::length(local.unencrypted) == 0
  }

  enforce {
    condition     = local.all_encrypted
    error_message = "All EBS block devices must be encrypted."
  }
}

Rule: Optional nested blocks (those that may be absent on some resource instances) must always be guarded with filter or core::try before indexing. Accessing attrs.block[0] on an absent block propagates null through every dependent local, eventually reaching the condition expression as an unknown value — which tfpolicy cannot reduce to a boolean, causing Error: unknown condition at runtime. This error does not appear in tfpolicy test (mocked data always has the block present) — it only surfaces against real plans.

Pattern summary:

  1. Add filter = core::try(attrs.block, null) != null && core::try(core::length(attrs.block), 0) > 0 to skip resources without the block. The double-core::try form is safe in both real plan evaluation and policytest mocks that omit the attribute.
  2. Convert the block set to a list: [for item in attrs.block : item].
  3. Use core::try(item.attr, <safe_default>) on individual attributes inside the loop.
  4. When a block is truly optional and its absence means "compliant", use !local.has_block || <check> so resources without the block pass automatically.

core::alltrue(list) and core::anytrue(list) — tfpolicy 0.3.0+ Only

core::anytrue(list) and core::alltrue(list) are available starting in tfpolicy 0.3.0. On tfpolicy < 0.3.0 these functions do not exist, and using them anywhere — including in locals, in for...if filter expressions, or in enforce conditions — produces:

Error: Call to unknown function
There is no function named "anytrue" in namespace core::.

or

Error: Call to unknown function
There is no function named "alltrue" in namespace core::.

Semantics (0.3.0+):

  • core::alltrue(list) — true if every element is true. Empty list → true (vacuous truth). false or null found → false; unknown with no false or null present → unknown.
  • core::anytrue(list) — true if any element is true. Empty list → false. null elements are ignored. true found → true even if other elements are unknown; no true found but an unknown element is present → unknown.
  • Parameter type is list(bool): null, booleans, and boolean-like strings ("true", "false", "1", "0") are accepted/coerced; numbers, nested lists, and other strings error with all elements must be boolean values.
# ✅ tfpolicy 0.3.0+ — direct use
locals {
  all_encrypted = core::alltrue([for d in local.devices : core::try(d.encrypted, false)])
  any_public    = core::anytrue([for r in local.rules : r.cidr == "0.0.0.0/0"])
}

# ✅ tfpolicy < 0.3.0 — use core::length() with list comprehension instead
locals {
  # "all encrypted" = no unencrypted devices exist
  unencrypted   = [for d in local.devices : d if !core::try(d.encrypted, false)]
  all_encrypted = core::length(local.unencrypted) == 0

  # "any public" = at least one public rule exists
  public_rules = [for r in local.rules : r if r.cidr == "0.0.0.0/0"]
  any_public   = core::length(local.public_rules) > 0
}

# ✅ CORRECT on any version — boolean conditions in for...if: use plain && / || operators
locals {
  bad_rules = [
    for rule in attrs.ingress : rule
    if (rule.protocol == "tcp" && rule.from_port == 22)  # ✅ plain boolean — safe
  ]

  wide_open_rules = [
    for rule in attrs.ingress : rule
    if (rule.cidr_blocks == ["0.0.0.0/0"] || rule.ipv6_cidr_blocks == ["::/0"])  # ✅ safe
  ]
}

# ✅ ALSO CORRECT — two-pass pattern for complex conditions
locals {
  ingress_with_flags = [
    for rule in attrs.ingress : {
      rule        = rule
      is_ssh_tcp  = rule.protocol == "tcp" && rule.from_port == 22
    }
  ]
  ssh_tcp_rules = [for r in local.ingress_with_flags : r.rule if r.is_ssh_tcp]  # ✅ safe
}

Rule: On tfpolicy 0.3.0+, prefer core::alltrue() / core::anytrue() directly for readability. On tfpolicy < 0.3.0, replace them with core::length() patterns:

  • Instead of core::anytrue(list_of_bools) → core::length([for b in list_of_bools : b if b]) > 0
  • Instead of core::alltrue(list_of_bools) → core::length([for b in list_of_bools : b if !b]) == 0
  • For filtering: use plain && / || boolean operators in for...if clauses instead (works on any version).
  • Both functions accept list(bool) coercions (null, booleans, "true", "false", "1", "0"). Numbers, nested lists, and other strings error — keep list comprehensions producing plain booleans when possible.

❌ Mistake 26: Assuming core::try() Returns the Default When an Attribute Is Explicitly null

# ❌ WRONG — destination_ranges exists but is null; core::try() does NOT catch null values.
# core::try() only catches attribute-access errors (missing attributes / index-out-of-bounds).
# When the attribute is present but set to null, core::try() returns null — NOT the default [].
# Passing null to core::length(), core::contains(), or a for-loop then causes:
#   "Invalid value for "list" parameter: argument must not be null"
resource_policy "google_compute_firewall" "check" {
  locals {
    dest_ranges = core::try(attrs.destination_ranges, [])            # ❌ returns null, not []
    bad_ranges  = [for r in local.dest_ranges : r if r == "0.0.0.0/0"]  # ❌ crashes
  }
}

# ❌ ALSO WRONG — looks safe but crashes in `locals`! TFPolicy does NOT short-circuit `&&` in locals.
# Both sides of `&&` are always evaluated, so core::length(null) is called even when
# logging_raw is null, causing: "Invalid value for 'collection': argument must not be null"
resource_policy "google_storage_bucket" "check" {
  locals {
    logging_raw     = core::try(attrs.logging, null)
    logging_present = local.logging_raw != null && core::length(local.logging_raw) > 0  # ❌ crashes when null!
  }
}

# ✅ CORRECT — explicitly check for null after core::try(), then fall back to [].
resource_policy "google_compute_firewall" "check" {
  locals {
    dest_ranges_raw = core::try(attrs.destination_ranges, null)
    dest_ranges     = local.dest_ranges_raw != null ? local.dest_ranges_raw : []
    bad_ranges      = [for r in local.dest_ranges : r if r == "0.0.0.0/0"]
  }
}

# ✅ CORRECT — use ternary to guard core::length() call; ternary DOES short-circuit.
resource_policy "google_storage_bucket" "check" {
  locals {
    logging_raw      = core::try(attrs.logging, null)
    logging_not_null = local.logging_raw != null
    logging_length   = local.logging_not_null ? core::length(local.logging_raw) : 0  # ✅ ternary safe
    logging_present  = local.logging_not_null && local.logging_length > 0
  }
}

# ✅ ALSO CORRECT — inline ternary in one line (equivalent to above).
locals {
  dest_ranges = core::try(attrs.destination_ranges, null) != null ? attrs.destination_ranges : []
}

Rule: core::try(expr, default) catches attribute-access errors (e.g. missing attribute, index out of range) and returns default in that case. It does NOT substitute default when the attribute exists but its value is null. Always use the two-step pattern:

  1. core::try(attrs.field, null) — safe access; returns null on missing attribute OR on null value
  2. != null ? attrs.field : <safe_default> — explicit null guard before passing to list functions

CRITICAL: && does NOT short-circuit in TFPolicy locals blocks, condition = expressions inside enforce {} blocks, or for...if predicates. Even if the left side local.var != null is false, the right side (e.g. core::length(local.var) or core::contains([...], local.var)) will still be evaluated and crash. Always use the ternary operator (condition ? value_if_true : value_if_false) to conditionally call functions on potentially-null values.

# ❌ WRONG — condition = also does NOT short-circuit; crashes when local.X is null
enforce {
  condition = local.X != null && core::contains(["a", "b"], local.X)  # ❌ crashes!
}

# ✅ CORRECT — use ternary inside the locals block, then reference in condition
locals {
  is_allowed = local.X != null ? core::contains(["a", "b"], local.X) : false
}
enforce {
  condition = local.is_allowed
}

# ❌ WRONG — for...if predicate also does NOT short-circuit; crashes when r.field is absent
violating = [
  for r in local.rules : r
  if core::try(r.field, null) != null && core::contains(["a", "b"], r.field)  # ❌ crashes!
]

# ✅ CORRECT — use ternary in for...if predicate; also wrap the second access with core::try
violating = [
  for r in local.rules : r
  if (core::try(r.field, null) != null ? core::contains(["a", "b"], core::try(r.field, "")) : false)
]

(Note: && in filter = does short-circuit for null values in real plan evaluation — optional absent attributes are treated as null in the Terraform resource schema, so local.raw != null && core::length(local.raw) > 0 (where local.raw = core::try(attrs.field, null)) is safe. However, in policytest mocks, if the mock completely omits an optional block attribute (rather than including it as null), the attrs object is a strict HCL literal that truly lacks that attribute. In that case, core::try(attrs.field, null) != null && core::length(attrs.field) > 0 fails: core::try catches the error on the first access and returns null, but the second bare attrs.field still throws "does not have attribute named 'field'" because && does not protect against the independent evaluation error. Safe patterns that work in both real plans and policytest:

  • Pre-capture: local.raw = core::try(attrs.field, null) then filter = local.raw != null && core::length(local.raw) > 0
  • Double-wrap: filter = core::try(attrs.field, null) != null && core::try(core::length(attrs.field), 0) > 0)

String interpolation + null: core::try() catches errors (missing attributes, index out of range), NOT null values. ${core::try(local.X, "default")} returns null — not "default" — when local.X is null, causing: "The expression result is null. Cannot include a null value in a string template.". Fix: use ternary in the string template: ${local.X != null ? local.X : "default"}.

Affected functions: core::length(), core::contains(), core::join(), for loops, and any function that requires a non-null list/map argument will crash if passed null. Apply the pattern wherever a list/set attribute may be absent or explicitly null in the provider schema.


❌ Mistake 27: Duplicating Common Values Across Multiple Policy Blocks

# ❌ WRONG — The same allowlist is copied into every resource_policy block.
# Changing the list requires editing multiple blocks, which is error-prone.
resource_policy "azurerm_linux_virtual_machine" "allowed_sizes" {
  locals {
    allowed_sizes = ["Standard_D2s_v3", "Standard_D4s_v3"]
  }
  enforce {
    condition     = core::contains(local.allowed_sizes, core::try(attrs.size, ""))
    error_message = "VM size is not in the allowed list."
  }
}

resource_policy "azurerm_windows_virtual_machine" "allowed_sizes" {
  locals {
    allowed_sizes = ["Standard_D2s_v3", "Standard_D4s_v3"]  # ❌ duplicated value
  }
  enforce {
    condition     = core::contains(local.allowed_sizes, core::try(attrs.size, ""))
    error_message = "VM size is not in the allowed list."
  }
}

# ✅ CORRECT — Extract the shared value to a top-level locals block.
# All policy blocks reference it via local.<name>. One change updates every policy.
locals {
  allowed_sizes = ["Standard_D2s_v3", "Standard_D4s_v3"]
}

resource_policy "azurerm_linux_virtual_machine" "allowed_sizes" {
  enforce {
    condition     = core::contains(local.allowed_sizes, core::try(attrs.size, ""))
    error_message = "VM size is not in the allowed list."
  }
}

resource_policy "azurerm_windows_virtual_machine" "allowed_sizes" {
  enforce {
    condition     = core::contains(local.allowed_sizes, core::try(attrs.size, ""))
    error_message = "VM size is not in the allowed list."
  }
}

Rule: When two or more resource_policy, module_policy, or provider_policy blocks share a local variable that holds the same constant value (e.g. an allowlist, blocklist, threshold, or configuration string), extract it to a top-level locals {} block and reference it as local.<name> in each policy. This follows the DRY principle — the value has a single source of truth.

When to extract:

  • Any literal list, map, string, or number used identically in two or more policy blocks
  • Computed values derived from the same constant inputs across multiple blocks (e.g. a formatted string built from shared constants)

When NOT to extract:

  • A value specific to exactly one resource type with no meaning outside that block
  • Any value that depends on attrs.* — those are resource-scoped and must stay inside the policy block (top-level locals cannot access attrs)

❌ Mistake 28: String Concatenation with + Is Not Supported

Error: Invalid operand — Unsuitable value for left operand: a number is required.

# ❌ WRONG — The + operator does not concatenate strings in tfpolicy
locals {
  pattern = "^com\\.amazonaws\\..+\\." + input.service_name  # ❌ runtime error
}

# ✅ CORRECT — Use ${ } interpolation for dynamic string building
locals {
  pattern        = "^com\\.amazonaws\\..+\\.${input.service_name}"
  error_msg      = "Service name must match pattern com.amazonaws.<region>.${input.service_name}."
}

# ✅ ALSO CORRECT — Avoid dynamic regex patterns entirely; use core::contains_substring
locals {
  service_ok = core::startswith(local.svc, "com.amazonaws.") &&
               core::contains_substring(local.svc, input.service_name)
}

Rule: String concatenation using + is not supported in tfpolicy HCL. Use "${expr}" interpolation syntax for all dynamic string construction.


❌ Mistake 29: enforcement_level Defined Multiple Times

Error: Attribute redefined — The argument "enforcement_level" was already set at line X.

# ❌ WRONG — enforcement_level appears twice, once before each enforce block
resource_policy "aws_vpc_endpoint" "check" {
  locals { ... }

  enforcement_level = "advisory"
  enforce {
    condition     = local.is_interface
    error_message = "..."
  }

  enforcement_level = "advisory"   # ❌ ERROR: already defined above
  enforce {
    condition     = local.service_matches
    error_message = "..."
  }
}

# ✅ CORRECT — enforcement_level appears exactly once for the whole block
resource_policy "aws_vpc_endpoint" "check" {
  locals { ... }

  enforcement_level = "advisory"   # ✅ declared once

  enforce {
    condition     = local.is_interface
    error_message = "..."
  }

  enforce {
    condition     = local.service_matches
    error_message = "..."
  }
}

Rule: enforcement_level is an attribute of the policy block itself, not of each enforce block. Declare it exactly once per resource_policy/module_policy/provider_policy block, at the same level as locals and enforce. Multiple enforce blocks within one policy block all share the same enforcement_level.


❌ Mistake 30: Referencing local.* Inside a For-Object Comprehension

Error: Undefined Reference — The reference "local.origin_domain" is not defined.

# ❌ WRONG — keys defined inside the for-object literal are NOT in local scope
locals {
  origin_checks = [
    for origin in local.origins : {
      origin_domain  = core::try(origin.domain_name, "")
      is_s3_origin   = core::contains_substring(local.origin_domain, ".s3.")  # ❌ local.origin_domain is unknown here
      is_compliant   = !local.is_s3_origin || local.has_oac_id                # ❌ local.is_s3_origin is unknown here
    }
  ]
}

# ✅ CORRECT — repeat the expression inline; each key is independent
locals {
  origin_checks = [
    for origin in local.origins : {
      origin_domain  = core::try(origin.domain_name, "")
      is_s3_origin   = core::contains_substring(core::try(origin.domain_name, ""), ".s3.")
      is_compliant   = !core::contains_substring(core::try(origin.domain_name, ""), ".s3.") ||
                       (core::try(origin.oac_id, null) != null && core::try(origin.oac_id, "") != "")
    }
  ]
}

# ✅ ALSO CORRECT — two-pass pattern: compute properties first, then combine
locals {
  origins_with_props = [
    for origin in local.origins : {
      domain       = core::try(origin.domain_name, "")
      has_oac      = core::try(origin.origin_access_control_id, null) != null
    }
  ]
  # Now the second pass can reference the object's own keys by iterating:
  origin_checks = [
    for o in local.origins_with_props : {
      is_s3        = core::contains_substring(o.domain, ".s3.")
      is_compliant = !core::contains_substring(o.domain, ".s3.") || o.has_oac
    }
  ]
}

Rule: Inside a for ... : { ... } object comprehension, keys defined within the same object literal cannot be referenced via local.key_name. The local.* scope only contains entries from the surrounding locals {} block. Either:

  1. Inline the expression wherever needed (repeat it), or
  2. Use a two-pass approach: compute intermediate values in one for-comprehension, then reference them by the iteration variable in a second for-comprehension.

❌ Mistake 31: Ternary Branches with Inconsistent Object Types

Error: The true and false result expressions must have consistent types. The 'true' value includes object attribute "X", which is absent in the 'false' value.

# ❌ WRONG — the true branch produces an object with "Statement" key,
# but the false branch is an empty object {} without that key
locals {
  policy_doc = local.appears_inline ? core::try(core::jsondecode(local.policy_value), {}) : {}
  statements = core::try(local.policy_doc.Statement, [])
}

# ✅ CORRECT — both branches must produce objects with the SAME set of keys
locals {
  policy_doc = local.appears_inline
    ? core::try(core::jsondecode(local.policy_value), { Statement = [] })
    : { Statement = [] }
  statements = core::try(local.policy_doc.Statement, [])
}

# ✅ ALSO CORRECT — avoid the ternary entirely; use core::try for the safe path
locals {
  # Always parse; core::try returns empty-statement fallback if decoding fails or is not applicable
  policy_doc = core::try(core::jsondecode(local.policy_value), { Statement = [] })
  statements = core::try(local.policy_doc.Statement, [])
}

Rule: In tfpolicy HCL, both branches of cond ? a : b must return values of identical type and shape. This