Skip to content

Commit 3ded718

Browse files
author
arunim2@gmail.com
committed
chore: sync skills from sg-clickhouse-mcp@a6e5424
1 parent f0bc65e commit 3ded718

30 files changed

Lines changed: 3642 additions & 0 deletions
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
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`).
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Examples
2+
3+
Every file pairs with `versions.tf` as a root module and passes `terraform validate` and
4+
`tofu validate` (provider 1.12.3). All were also applied against a real org with names prefixed
5+
and `enforced_on` pointed at an empty scope, re-planned with no changes (the OPA policy after the
6+
documented untaint), and destroyed. Every
7+
inline Tirith document was extracted from the Terraform plan and executed on Tirith 1.0.5 with
8+
passing, failing and skip inputs.
9+
10+
| File | Rules | Where it runs |
11+
|---|---|---|
12+
| `no_public_s3.tf` | S3 ACL deny-list + public-access-block check; group + single-workflow scope | runtime (plan) |
13+
| `required_tags.tf` | CostCenter key and Environment=production on EC2/RDS | runtime (plan) |
14+
| `network_guardrails.tf` | no 0.0.0.0/0 ingress, EU regions via `provider_config`, instance-type allow-list | runtime (plan) |
15+
| `approvals.tf` | approval on any delete/replace, approval when monthly cost > 500; org-wide `["*"]`, shared approvers | runtime (plan / Infracost) |
16+
| `config_rules.tf` | managed state required (warn), approved connectors + private runners (fail), pinned Terraform version (warn) | config time (workflow create/update, run build) |
17+
| `opa_and_marketplace.tf` | Rego from private GitHub with `opaQuery` (+ the untaint / `ignore_changes = all` handling), connector scope; marketplace checkov bundle warn-only | runtime |
18+
19+
The `terraform_version` rule in `config_rules.tf` was added later: it passes both validators and its
20+
document was run on Tirith 1.0.5 with passing and failing workflow payloads, but it was not applied
21+
live.
22+
23+
Replace the placeholder ids (`acme`, connector names, repo URLs, approver emails) with yours.
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# Two approval gates in one policy, org-wide: plans that delete anything, and plans whose
2+
# estimated monthly cost exceeds $500. Approvers are policy-level and shared by both rules.
3+
# Runtime approvals pause before apply; plan-only runs never pause.
4+
5+
locals {
6+
inline = {
7+
use_marketplace_template = false
8+
custom_source = { source_config_kind = "SG_POLICY_FRAMEWORK", source_config_dest_kind = "INLINE" }
9+
}
10+
}
11+
12+
resource "stackguardian_policy" "change_approvals" {
13+
resource_name = "change-approvals" # slug: runtime approvals match approvers on this name
14+
policy_type = "GENERAL"
15+
description = "Human approval for deletions and expensive plans"
16+
tags = ["governance"]
17+
enforced_on = ["*"] # whole organization — on its own, never combined
18+
19+
approvers = ["finops@acme.com", "cto@acme.com"] # lowercase emails or SSO groups
20+
number_of_approvals_required = 1 # 0 would mean ALL of them
21+
22+
policies_config = [
23+
{
24+
name = "approve_deletes"
25+
skip = false
26+
on_fail = "APPROVAL_REQUIRED"
27+
on_pass = "PASS"
28+
policy_vcs_config = local.inline
29+
policy_input_data = {
30+
schema_type = "TIRITH_JSON"
31+
data = jsonencode({
32+
meta = { version = "v1", required_provider = "stackguardian/terraform_plan" }
33+
evaluators = [{
34+
id = "no_deletes"
35+
provider_args = { operation_type = "action", terraform_resource_type = "*" }
36+
# plan actions are create/update/delete/no-op/read; a replace yields delete + create
37+
condition = { type = "NotContainedIn", value = ["delete"], error_tolerance = 1 }
38+
}]
39+
eval_expression = "no_deletes"
40+
})
41+
}
42+
},
43+
{
44+
name = "approve_cost_over_500"
45+
skip = false
46+
on_fail = "APPROVAL_REQUIRED"
47+
on_pass = "PASS"
48+
policy_vcs_config = local.inline
49+
policy_input_data = {
50+
schema_type = "TIRITH_JSON"
51+
data = jsonencode({
52+
meta = { version = "v1", required_provider = "stackguardian/infracost" }
53+
evaluators = [{
54+
id = "monthly_cost_ok"
55+
provider_args = { operation_type = "total_monthly_cost", resource_type = ["*"] }
56+
condition = { type = "LessThanEqualTo", value = 500 } # integers only
57+
}]
58+
eval_expression = "monthly_cost_ok"
59+
})
60+
}
61+
},
62+
]
63+
}

0 commit comments

Comments
 (0)