|
| 1 | +--- |
| 2 | +name: sg-writing-stackguardian-policy-terraform |
| 3 | +description: Use when writing, reviewing or debugging Terraform/OpenTofu HCL for StackGuardian policies (stackguardian_policy, policies_config, enforced_on, Tirith JSON, OPA/Rego, marketplace policy templates, cost limits, approval gates, config-time workflow rules), attaching a policy to a workflow, group or connector — or when a policy applies but never blocks, blocks every plan, never asks for approval, or its scope silently disappears. Also covers resolving scopes and dependencies via the StackGuardian MCP server. |
| 4 | +--- |
| 5 | + |
| 6 | +# Writing StackGuardian policy Terraform |
| 7 | + |
| 8 | +## Overview |
| 9 | + |
| 10 | +A `stackguardian_policy` is a list of rules (`policies_config`) plus a scope (`enforced_on`). |
| 11 | +**Attachment lives only on the policy** — workflows, groups and templates have no policy |
| 12 | +attribute. Rules are evaluated at two different moments: |
| 13 | + |
| 14 | +| `meta.required_provider` | Evaluated | Verdict effect | |
| 15 | +|---|---|---| |
| 16 | +| `stackguardian/terraform_plan`, `stackguardian/infracost`, OPA (`OPA_REGO`) | in the plan step of TERRAFORM/OPENTOFU runs (also CloudFormation/Pulumi steps), before `apply`; not on drift or `plan-without-policy` runs, not in Ansible/Kubernetes steps | FAIL errors the run; APPROVAL_REQUIRED pauses before the next step | |
| 17 | +| `stackguardian/json` (config rule) | when a workflow in scope is **created/updated** (also via Terraform) and when a run is **built** | FAIL = `403 Workflow policy (<policy>:<rule>) failed …` on create/update (live); at run build the run is refused or gated at step 0 | |
| 18 | + |
| 19 | +The provider validates nothing and the Tirith engine fails *open* on many mistakes, so a wrong |
| 20 | +rule usually applies cleanly and then passes everything. Provider **1.12.3**, Tirith **1.0.5** |
| 21 | +(core; the terraform step on `main` pins 1.0.7 with the same semantics). "(live)" = reproduced against a real org. Setup (source address, |
| 22 | +`api_uri`): **sg-writing-stackguardian-workflow-terraform**. |
| 23 | + |
| 24 | +## Discover scope and dependencies first (StackGuardian MCP) |
| 25 | + |
| 26 | +`enforced_on` entries are never validated, so a typo silently attaches nothing. **If the |
| 27 | +StackGuardian MCP server is connected, take scope strings and ids from it** (rows must carry |
| 28 | +`OrgId = "/orgs/<STACKGUARDIAN_ORG_NAME>"`; read tools only): |
| 29 | + |
| 30 | +| Need | MCP call | Value to use | |
| 31 | +|---|---|---| |
| 32 | +| group scope | `search_orchestrator_resources(resourceTypes=["WORKFLOW_GROUP"], searchQuery=…)` | `SubResourceId` as-is (`/wfgrps/PROD/GCP-4jc2fd3k`) — not `ResourceId` (leaf only) | |
| 33 | +| workflow / stack scope | `search_workflows(searchQuery=…)`, `search_stacks` | `SubResourceId` as-is (`/wfgrps/<g>/wfs/<w>`, `/wfgrps/<g>/stacks/<s>`) | |
| 34 | +| connector scope | `search_orchestrator_resources(resourceTypes=["INTEGRATION.CLOUD"])` | `ResourceId` (`/integrations/<id>`) | |
| 35 | +| blast radius before applying | `search_workflows(parentId="/orgs/<org>/wfgrps/<g>", count=true)`, `search_workflows(cloudIntegrationIds=[…])`, `cross_reference(targetKind="cloud_integration", targetId=…, count=true)` | how many workflows the policy will judge | |
| 36 | +| existing policies | `search_policies(searchQuery=…)`, `get_orchestrator_resource_by_id(parentId="/orgs/<org>", resourceId="/policies/<id>")` | name collisions, current rules and `Scope` | |
| 37 | +| marketplace policy template | `get_subscription(subscriptionTypes=["IAC_POLICY"])` | `/<owner>/<name>` + a revision that exists | |
| 38 | +| git repo auth (OPA / git Tirith) | `search_orchestrator_resources(resourceTypes=["INTEGRATION.VCS"])`, `["SECRET"]` | `auth` = `ResourceId` / `/secrets/<name>` | |
| 39 | +| config-rule key paths | `get_orchestrator_resource_by_id` on a real workflow | exact field names (`TerraformConfig`, `DeploymentPlatformConfig`, `RunnerConstraints`, …) | |
| 40 | + |
| 41 | +Without MCP: literal paths from the user plus data-source existence checks — never guessed. |
| 42 | + |
| 43 | +## Core template (runtime rule on the Terraform plan) |
| 44 | + |
| 45 | +```terraform |
| 46 | +resource "stackguardian_policy" "no_public_s3" { |
| 47 | + resource_name = "no-public-s3" # slug: it is the id, and approvals match on it |
| 48 | + policy_type = "GENERAL" # the only value the provider can write |
| 49 | + description = "Block public S3 ACLs" |
| 50 | + tags = ["security"] |
| 51 | + enforced_on = ["/wfgrps/${stackguardian_workflow_group.payments.id}"] # ALWAYS declare (see rule 1) |
| 52 | + approvers = [] # declare, even when empty |
| 53 | + number_of_approvals_required = 0 |
| 54 | +
|
| 55 | + policies_config = [{ |
| 56 | + name = "s3_acl_not_public" # slug, unique in the policy |
| 57 | + skip = false |
| 58 | + on_fail = "FAIL" # FAIL | WARN | PASS | APPROVAL_REQUIRED |
| 59 | + on_pass = "PASS" # REQUIRED too: omitted -> 400 `onPass: "" is not a valid choice` (live) |
| 60 | +
|
| 61 | + policy_vcs_config = { |
| 62 | + use_marketplace_template = false |
| 63 | + custom_source = { source_config_kind = "SG_POLICY_FRAMEWORK", source_config_dest_kind = "INLINE" } |
| 64 | + } |
| 65 | +
|
| 66 | + policy_input_data = { |
| 67 | + schema_type = "TIRITH_JSON" |
| 68 | + data = jsonencode({ # only meta, evaluators, eval_expression at the top level |
| 69 | + meta = { version = "v1", required_provider = "stackguardian/terraform_plan" } |
| 70 | + evaluators = [{ |
| 71 | + id = "acl_not_public" # snake_case; never a prefix of another id |
| 72 | + provider_args = { |
| 73 | + operation_type = "attribute" |
| 74 | + terraform_resource_type = "aws_s3_bucket_acl" |
| 75 | + terraform_resource_attribute = "acl" |
| 76 | + } |
| 77 | + condition = { |
| 78 | + type = "NotContainedIn" # found value must NOT be in this list |
| 79 | + value = ["public-read", "public-read-write", "authenticated-read"] |
| 80 | + error_tolerance = 1 # skip plans without aws_s3_bucket_acl (0 = FAIL them) |
| 81 | + } |
| 82 | + }] |
| 83 | + eval_expression = "acl_not_public" # && || ! ( ) only |
| 84 | + }) |
| 85 | + } |
| 86 | + }] |
| 87 | +} |
| 88 | +``` |
| 89 | + |
| 90 | +## Rules that bite |
| 91 | + |
| 92 | +1. **Declare `enforced_on`, `tags`, `approvers`, `number_of_approvals_required`, `description` and |
| 93 | + `policies_config` every time.** They are Optional+Computed without state carry-over: omit one |
| 94 | + while changing anything else and the provider sends `null` (the live test wiped `enforced_on` to |
| 95 | + `[]`, silently detaching the policy); an omitted `number_of_approvals_required` is sent as `0` — |
| 96 | + *all* approvers. `enforced_on = []` or no attribute = attached to **nothing**; org-wide is `["*"]`. |
| 97 | +2. **Scope paths** are exact strings, never validated: `"*"`, `/wfgrps/<group-id>` (includes nested |
| 98 | + groups, stacks, workflows), `/wfgrps/<g>/wfs/<wf>`, `/wfgrps/<g>/stacks/<s>[/wfs/<wf>]`, |
| 99 | + `/integrations/<connector>` (every workflow deploying through it), |
| 100 | + `/integrationgroups/<g>[/integrations/<c>]`. Nested group: `/wfgrps/parent/child`. No trailing `/`. |
| 101 | +3. **Condition direction:** `Contains` = found value contains yours; `ContainedIn` = found value is |
| 102 | + in your list (allow-list); `NotContainedIn` = deny-list. Types are case-sensitive; an unknown |
| 103 | + type (`In`, `Exists`, `StartsWith`, `NotRegexMatch`) fails every input. |
| 104 | +4. **`error_tolerance`** (inside `condition`): 0 fails plans that lack the resource type, 1 skips |
| 105 | + them, 2 also skips resources missing the attribute. A fully skipped rule **passes**. |
| 106 | +5. **Terraform plan actions are `create`, `update`, `delete`, `no-op`, `read`** — never `apply` or |
| 107 | + `destroy`. The provider docs' `NotEquals "apply"` approval example never fires. |
| 108 | +6. **APPROVAL_REQUIRED** needs `approvers` + `number_of_approvals_required` on the policy (`0` = |
| 109 | + all approvers). A runtime approval pauses before the *next* step, so plan-only runs never pause. |
| 110 | + Approvals match on the policy's id: keep `resource_name` a slug, don't set a different `id`, and |
| 111 | + never rename a policy that uses APPROVAL_REQUIRED (the id stays, the match breaks). |
| 112 | +7. **Config rules** must be `stackguardian/json` + `operation_type = "get_value"` + a `key_path` |
| 113 | + rooted at a workflow field (`TerraformConfig.managedTerraformState`, `Tags`, `WfType`, |
| 114 | + `DeploymentPlatformConfig.*.config.integrationId`, …). Any other `required_provider` |
| 115 | + (`sg_workflow`, `sg_stack`, `kubernetes`, none) ends in "Tirith run errored" → `on_fail` in the |
| 116 | + terraform step — it **blocks every Terraform/OpenTofu run in scope**. `sg_workflow`/`sg_stack` |
| 117 | + with a workflow `key_path` are also picked up at config time and always fail there (Tirith has no |
| 118 | + `sg_stack` provider; `sg_workflow` ignores `key_path`): with `FAIL`, every workflow create/update gets 403. |
| 119 | +8. **OPA** needs `additional_config = jsonencode({ opaQuery = "<package>.<bool_rule>" })` (no `data.` |
| 120 | + prefix) — without it every Rego policy passes. The provider cannot read it back: the first apply |
| 121 | + ends in *inconsistent result* (tainted); `terraform untaint`, then use |
| 122 | + `lifecycle { ignore_changes = all }` and change the policy only with `-replace`. |
| 123 | + **Not** `ignore_changes = [policies_config]`: any later update then re-sends the rules from state |
| 124 | + and wipes `opaQuery` server-side (live). |
| 125 | +9. **Only three top-level keys** in a Tirith document (`meta`, `evaluators`, `eval_expression`), |
| 126 | + integers rather than floats, `jsonencode` for `data`, `schema_type = "TIRITH_JSON"` for inline Tirith. |
| 127 | +10. **A policy in scope also blocks Terraform:** a failing config rule makes `terraform apply` of |
| 128 | + the affected `stackguardian_workflow_*` resources fail with 403. |
| 129 | + |
| 130 | +## Quick reference |
| 131 | + |
| 132 | +| Need | Use | |
| 133 | +|---|---| |
| 134 | +| Block a resource setting | `terraform_plan` / `attribute` + `NotContainedIn` / `NotEquals`, tolerance 1 | |
| 135 | +| Required tags | `attribute` on `tags` (or `tags_all`) + `Contains "<key>"` (key) or `Contains { K = "v" }` (pair) | |
| 136 | +| Restrict region | `provider_config`, `attribute = "region"`, `ContainedIn [...]` — one evaluator per registry (`registry.terraform.io/hashicorp/aws` for Terraform, `registry.opentofu.org/hashicorp/aws` for OpenTofu), tolerance 2, joined with `&&`; only literal regions are checked | |
| 137 | +| Count cap | `count` + `LessThanEqualTo N` | |
| 138 | +| Monthly cost cap | `stackguardian/infracost`, `total_monthly_cost`, `resource_type = ["*"]`, `LessThanEqualTo 500` | |
| 139 | +| Approval on deletes | `action`, type `"*"`, `NotContainedIn ["delete"]`, `on_fail = "APPROVAL_REQUIRED"` | |
| 140 | +| Config guardrail | `stackguardian/json`, `get_value`, `key_path`; e.g. managed state = `is_custom \|\| uses_managed_state` (tolerance 1 on the managed key — see `examples/config_rules.tf`) | |
| 141 | +| Scope an existing group/workflow | a literal/local path (`local.net = "platform/networking"` → `"/wfgrps/${local.net}"`), with `data "stackguardian_workflow_group" { id = local.net }` as a plan-time existence check. Don't use `data.<group>.id` in the path: it is only the leaf for nested groups (live) | |
| 142 | +| Marketplace rule | `policy_vcs_config = { use_marketplace_template = true, policy_template_id = "/<owner-org>/<name>:<n>" }` | |
| 143 | +| Git Tirith | `SG_POLICY_FRAMEWORK` + git kind; the file must be `<working_dir>/tirith.json`; runtime only | |
| 144 | +| Warn-only rollout / disable | `on_fail = "WARN"` / `skip = true` (there is no active flag) | |
| 145 | +| Import | `terraform import stackguardian_policy.x <policy-id>` | |
| 146 | + |
| 147 | +## Common mistakes |
| 148 | + |
| 149 | +| Mistake | What happens | |
| 150 | +|---|---| |
| 151 | +| `schema_type = "TIRITH_FORMAT"` / other invented enums | Apply error: `… is not a valid …` | |
| 152 | +| Org-wide by listing groups | Misses new groups; use `["*"]` | |
| 153 | +| `eval_expression = "a and b"` | Becomes an undefined symbol → **silent pass** | |
| 154 | +| Ids `acl-ok` and `acl-ok-2` | Prefix collision → `final_result = -1`, treated as a pass: the longer id's evaluator is silently ignored | |
| 155 | +| `error_tolerance = 0` on a type-specific rule, group-wide | Every plan without that type FAILS | |
| 156 | +| `on_fail = "APPROVAL_REQUIRED"` without approvers | The run pauses and anyone with approve permission can release it | |
| 157 | +| `required_provider = "stackguardian/sg_workflow"` (or `sg_stack`, `kubernetes`) | FAILs the terraform step of every run in scope; with a workflow `key_path` also 403s every workflow create/update (rule 7) | |
| 158 | +| Required tag as `terraform_resource_attribute = "tags.CostCenter"` with tolerance 2, or with type `"*"` | A missing key is "attribute not found" (severity 2): tolerance 2 skips it, so the rule never fails; with `"*"` and tolerance 1 every untaggable resource fails. Use one type per evaluator with tolerance 1, or `tags` + `Contains "CostCenter"` | |
| 159 | +| `policies_config { ... }` block, or a raw HCL object as `data` | Syntax / type error: `policies_config = [{ ... }]`, `data = jsonencode({ ... })` | |
| 160 | +| `stackguardian_policy { data = jsonencode({...}) }` (pre-1.x form, still in the provider's onboarding guide asset) | Unsupported argument; use the typed attributes | |
| 161 | +| `severity`, a stage (`PRE_PLAN`, `PRE_APPLY`), per-rule approvers, nested `all_of`/`any_of` | Not part of a policy: severity/stage keys are ignored, nested shapes are not read. Enforcement is only `on_fail`/`on_pass`; approvers are policy-level | |
| 162 | +| `{{ var.x }}` placeholders in the document | Never filled; the plan step crashes (even with `on_fail = "WARN"`) | |
| 163 | +| OPA `opaQuery = "data.main.allow"` or `main.deny` | KeyError / non-boolean → on_fail | |
| 164 | +| `policy_template_id = "/stackguardian/x:latest"` | Resolved per run; pin a number | |
| 165 | +| `policy_type = "FILTER.INSIGHT"` | Provider always writes GENERAL → inconsistent result | |
| 166 | +| `policies_config = []` (a policy without rules) | Inconsistent result, tainted (live) — a policy needs at least one rule; disable with `skip = true` | |
| 167 | +| `resource_name` of a policy that already exists | `409 Policy ID not unique` (from code) — `terraform import` it instead | |
| 168 | +| Floats like `value = 99.5` in the document | The create stores raw floats and can 409 (unverified); use integers | |
| 169 | + |
| 170 | +## References |
| 171 | + |
| 172 | +- `references/tirith.md` — Tirith 1.0.5: providers, operation types, conditions, tolerance and skip |
| 173 | + semantics (incl. the skip-erasure bug), `eval_expression`, config-time key paths, verified recipes. |
| 174 | +- `references/sources-and-lifecycle.md` — inline / git / OPA / marketplace sources, scope |
| 175 | + resolution, approvals, provider round-trip behaviour, import, destroy, error catalog. |
| 176 | +- `references/schema.md` — exact `stackguardian_policy` schema (provider 1.12.3). |
| 177 | +- `examples/*.tf` — validated with `terraform`/`tofu validate`, applied live, and every Tirith |
| 178 | + document executed against Tirith 1.0.5 with passing and failing sample plans (`examples/README.md`). |
0 commit comments