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

rce Enforcement

Enforce that one resource type has a corresponding companion resource:

aws_s3_bucket_server_side_encryption_configuration is a dependent child of aws_s3_bucket — its bucket argument always references attrs.id. The filter value is derived from attrs.*, so the top-level cache pattern is prohibited (Mistake 13 in verified-syntax.md). Always use the inline filter pattern for S3 companion resources.

# NOTE: This policy contains a cross-resource reference that will not resolve
# during plan time, but the policy will run successfully during apply time.
resource_policy "aws_s3_bucket" "require_encryption_config" {
    locals {
        sse_configs     = core::getresources("aws_s3_bucket_server_side_encryption_configuration", {
            bucket = attrs.id  # filter derived from current resource's own attr — must be inline
        })
        has_sse_config  = core::length(local.sse_configs) > 0
        # rule is a Set — convert to list before indexing; guard first
        sse_rules       = local.has_sse_config ? core::try([for r in local.sse_configs[0].rule : r], []) : []
        has_sse_rule    = core::length(local.sse_rules) > 0
        sse_apply_block = local.has_sse_rule ? core::try([for a in local.sse_rules[0].apply_server_side_encryption_by_default : a], []) : []
        has_apply_block = core::length(local.sse_apply_block) > 0
        sse_algorithm   = local.has_apply_block ? core::try(local.sse_apply_block[0].sse_algorithm, "") : ""
    }

    enforcement_level = "advisory"

    enforce {
        condition = local.has_sse_config
        error_message = "S3 bucket must have an aws_s3_bucket_server_side_encryption_configuration resource."
    }

    enforce {
        condition = local.sse_algorithm == "aws:kms"
        error_message = "S3 bucket encryption must use aws:kms (found: ${local.sse_algorithm != "" ? local.sse_algorithm : "(none configured)"})"
    }
}

Key points:

  • The filter value (attrs.id) is the current resource's own attribute — a top-level cache is impossible; use the inline call
  • Both checks (presence and KMS algorithm) live in one resource_policy block with multiple enforce blocks — never split checks on the same resource type into two blocks (SKILL.md Output Structure Rule 1)
  • Always include the apply-time # NOTE: comment

Pattern 11: Resource Count Limits

Limit the total number of resources of a specific type:

locals {
    all_nat_gateways = core::getresources("aws_nat_gateway", {})
    nat_gateway_count = core::length(local.all_nat_gateways)
    max_allowed = 3
}

resource_policy "aws_nat_gateway" "limit_count" {
    enforce {
        condition = local.nat_gateway_count <= local.max_allowed
        error_message = "Maximum ${local.max_allowed} NAT gateways allowed (found: ${local.nat_gateway_count})"
    }
}

Key points:

  • Policy runs for each resource but references global count
  • All resources will fail if limit is exceeded
  • Use top-level locals to count once

Pattern 12: Cross-Resource Attribute Validation

Validate that one resource's attribute matches another resource's attribute:

resource_policy "aws_subnet" "vpc_tag_match" {
    filter = attrs.vpc_id != null

    locals {
        # NOTE: This policy contains a cross-resource reference that will not resolve
        # during plan time, but the policy will run successfully during apply time.
        matching_vpcs  = core::getresources("aws_vpc", { id = attrs.vpc_id })
        vpc            = core::length(local.matching_vpcs) > 0 ? local.matching_vpcs[0] : null
        vpc_env_tag    = core::try(local.vpc.tags["Environment"], "")
        subnet_env_tag = core::try(attrs.tags["Environment"], "")
        tags_match     = local.vpc_env_tag == local.subnet_env_tag
    }

    enforce {
        condition = local.tags_match
        error_message = "Subnet Environment tag (${local.subnet_env_tag}) must match VPC Environment tag (${local.vpc_env_tag})"
    }
}

Key points:

  • aws_vpc.id is the linking attribute referenced by attrs.vpc_id — this is an attrs.*-derived key so the top-level cache + map-index pattern is prohibited (Mistake 13 in verified-syntax.md); always use inline core::getresources
  • Use core::try() for safe attribute access
  • Check both existence and value matching

Pattern 13: Sentinel Conversion - DMS Endpoint SSL Mode

Source policy: HashiCorp PCI DSS library - dms-endpoints-should-use-ssl.sentinel

Conversion quality: Perfect

resource_policy "aws_dms_endpoint" "require_ssl_mode" {
    locals {
        ssl_mode = core::try(attrs.ssl_mode, "")
        valid_ssl_modes = ["require", "verify-ca", "verify-full"]
    }

    enforce {
        condition = core::contains(local.valid_ssl_modes, local.ssl_mode)
        error_message = "DMS endpoints must set ssl_mode to one of: require, verify-ca, verify-full"
    }
}

Why this converts cleanly:

  • Single resource type
  • Direct attribute check on planned values
  • No cross-resource dependency or reference metadata
  • Sentinel collection.reject() becomes one focused enforce condition

Pattern 14: Sentinel Conversion - Elasticsearch HTTPS Required

Source policy: HashiCorp PCI DSS library - elasticsearch-https-required.sentinel

Conversion quality: Good

resource_policy "aws_elasticsearch_domain" "https_required" {
    locals {
        endpoint_options = core::try(attrs.domain_endpoint_options, [])
        endpoint_options_present = core::length(local.endpoint_options) > 0
        enforce_https = core::try(local.endpoint_options[0].enforce_https, false)
        tls_security_policy = core::try(local.endpoint_options[0].tls_security_policy, "")
    }

    enforce {
        condition = local.endpoint_options_present
        error_message = "Elasticsearch domains must define domain_endpoint_options"
    }

    enforce {
        condition = local.enforce_https == true
        error_message = "Elasticsearch domains must set domain_endpoint_options.enforce_https = true"
    }

    enforce {
        condition = local.tls_security_policy == "Policy-Min-TLS-1-2-PFS-2023-10"
        error_message = "Elasticsearch domains must use tls_security_policy 'Policy-Min-TLS-1-2-PFS-2023-10'"
    }
}

Why this is Good instead of Perfect:

  • The Sentinel policy uses helper functions and nested map lookups; tfpolicy rewrites that logic into direct block access with core::try()
  • The enforcement intent is preserved, but the structure is idiomatic tfpolicy rather than one-to-one

Pattern 15: Sentinel Conversion - EventBridge Bus Must Have Attached Policy

Source policy: HashiCorp PCI DSS library - eventbridge-custom-event-bus-should-have-attached-policy.sentinel

Conversion quality: Limited

locals {
    all_event_bus_policies = core::getresources("aws_cloudwatch_event_bus_policy", {})
    event_bus_policy_map = {
        for policy in local.all_event_bus_policies :
        policy.event_bus_name => true
    }
}

resource_policy "aws_cloudwatch_event_bus" "require_attached_policy" {
    locals {
        bus_name = core::try(attrs.name, "")
        has_attached_policy = core::try(local.event_bus_policy_map[local.bus_name], false)
    }

    enforce {
        condition = local.has_attached_policy
        error_message = "EventBridge buses must have a matching aws_cloudwatch_event_bus_policy resource"
    }
}

Why this is only Limited:

  • This relies on value matching through core::getresources(), not Terraform graph/reference metadata
  • It works best when event_bus_name is explicit and already resolved
  • New resources with unresolved references can produce different behavior from Sentinel or fail to match on first creation

Previous: Quick Start Guide Back to: Main README