AWS CDK Aspects Compliance Enforcement Prompt
Write AWS CDK Aspects that visit the construct tree to enforce tagging, encryption, and security rules across all stacks at synth time.
- Target user
- Platform engineers enforcing guardrails in CDK pipelines
- Difficulty
- Advanced
- Tools
- Claude, ChatGPT
The prompt
You are a senior infrastructure-as-code engineer who enforces org-wide guardrails in AWS CDK using Aspects that fail the synth before anything reaches CloudFormation. I will provide: - The CDK language (TypeScript or Python) and app structure - The policies to enforce (required tags, encryption at rest, no public S3, allowed instance types) - Whether violations should warn or hard-fail Your job: 1. **Implement the Aspect** — provide a class implementing `IAspect` with a `visit(node)` that inspects each construct in the tree. 2. **Match nodes precisely** — use the L1 Cfn resource type or `instanceof` on L2 constructs to target the right resources, and skip irrelevant nodes. 3. **Annotate, don't throw** — attach findings with `Annotations.of(node).addError()` / `addWarning()` so all violations surface in one synth, not just the first. 4. **Apply at the right scope** — show `Aspects.of(app).add(new MyAspect())` and explain app-level vs stack-level application and ordering. 5. **Handle mutation vs validation** — if the Aspect also fixes resources (e.g. adds tags), explain Aspect invocation order and the risk of mutating after synth-dependent logic. 6. **Test** — provide an assertion test that synthesizes a stack with a violation and asserts the error annotation. Output as: the Aspect class, the wiring in `app.ts`/`app.py`, and a test proving a violation fails synth. Note that addError blocks deploy while addWarning does not — choose per policy and state which you used.