This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: aws-cdk-v2-constructs

AWS CDK v2 Modern L2 Constructs & Least-Privilege IAM Discipline

Enterprise cloud infrastructure standard using AWS CDK v2. Mandates higher-level L2/L3 constructs over raw Cfn escape hatches, fine-grained resource-level IAM grants, and strict multi-stack state isolation.

Prohibited Anti-Pattern: AI drops to low-level Cfn* primitives with wildcards in IAM policies (Action: '*', Resource: '*').

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: AWS CDK v2 Modern L2 Constructs & Least-Privilege IAM Discipline - Enterprise cloud infrastructure standard using AWS CDK v2. Mandates higher-level L2/L3 constructs over raw Cfn escape hatches, fine-grained resource-level IAM grants, and strict multi-stack state isolation.
globs: bin/*.ts, lib/*.ts, cdk.json
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/aws-cdk-v2-constructs"
---

# AWS CDK v2 Modern L2 Constructs & Least-Privilege IAM Discipline

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: AI drops to low-level Cfn* primitives with wildcards in IAM policies (Action: '*', Resource: '*').

## System Constraints
You are an AWS cloud solutions architect. In AWS CDK v2 code, NEVER use low-level Cfn* primitives when an L2 construct exists. Never create IAM policies with wildcard actions or wildcard resources. Always use L2 grant methods (e.g. bucket.grantRead(fn)) and split stateful data resources into separate stacks.

## Strict Guidelines
- Use AWS CDK L2 constructs (e.g. aws_s3.Bucket, aws_lambda_nodejs.NodejsFunction) rather than raw L1 Cfn* constructs.
- Enforce least-privilege IAM permissions via native grant methods (table.grantReadWriteData(fn)) instead of attaching AdministratorAccess.
- Isolate stateful resources (RDS, S3, DynamoDB) into dedicated StateStacks with RemovalPolicy.RETAIN to prevent accidental deletion during CI deployments.
- Integrate cdk-nag security assertion rules in bin/app.ts to detect unencrypted storage and overly permissive security groups.

## Bad vs Good Implementations
### L2 Constructs with Granular IAM Grants vs Wildcard Policies

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Violates the principle of least privilege; compromise of the Lambda function exposes the entire AWS account.
```typescript
// ANTI-PATTERN: Wildcard IAM policy and destroy removal policy on production database!
const table = new dynamodb.CfnTable(this, 'Table', { keySchema: [] });
const fn = new lambda.Function(this, 'Fn', { code: lambda.Code.fromInline(''), handler: 'index.handler', runtime: lambda.Runtime.NODEJS_20_X });
fn.addToRolePolicy(new iam.PolicyStatement({
  actions: ['*'], // CRITICAL RISK: Full administrative control!
  resources: ['*'],
}));
```

#### Production Standard (Correct)
> **Standard**: CDK automatically calculates the exact minimum IAM actions and resource ARNs, eliminating privilege escalation risks.
```typescript
// PRODUCTION STANDARD: AWS CDK v2 L2 Construct with Explicit Grant
import * as cdk from 'aws-cdk-lib';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import * as lambdaNode from 'aws-cdk-lib/aws-lambda-nodejs';
import { Construct } from 'constructs';

export class OrderServiceStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const ordersTable = new dynamodb.Table(this, 'OrdersTable', {
      partitionKey: { name: 'orderId', type: dynamodb.AttributeType.STRING },
      billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
      encryption: dynamodb.TableEncryption.AWS_MANAGED,
      pointInTimeRecovery: true,
      removalPolicy: cdk.RemovalPolicy.RETAIN,
    });

    const processorFn = new lambdaNode.NodejsFunction(this, 'ProcessorFn', {
      entry: 'src/handlers/process-order.ts',
      runtime: cdk.aws_lambda.Runtime.NODEJS_20_X,
      environment: { TABLE_NAME: ordersTable.tableName },
    });

    // Fine-grained IAM: Grants only GetItem/PutItem/UpdateItem on this specific ARN
    ordersTable.grantReadWriteData(processorFn);
  }
}
```

### Automated Security Linting with cdk-nag

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Security misconfigurations pass silently into production pipelines.
```typescript
// ANTI-PATTERN: App synthesis without compliance checks
const app = new cdk.App();
new MyStack(app, 'Stack');
```

#### Production Standard (Correct)
> **Standard**: Blocks CI synthesis if any construct violates AWS Well-Architected security best practices.
```typescript
// PRODUCTION STANDARD: Enforcing AWS Solutions security checks in app entrypoint
import { Aspects } from 'aws-cdk-lib';
import { AwsSolutionsChecks } from 'cdk-nag';
const app = new cdk.App();
Aspects.of(app).add(new AwsSolutionsChecks({ verbose: true }));
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: AWS CDK v2 Modern L2 Constructs & Least-Privilege IAM Discipline

AWS CDK v2 Modern L2 Constructs & Least-Privilege IAM Discipline defines an industrial-grade behavioral standard for devops engineering. Enterprise cloud infrastructure standard using AWS CDK v2. Mandates higher-level L2/L3 constructs over raw Cfn escape hatches, fine-grained resource-level IAM grants, and strict multi-stack state isolation. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: AI drops to low-level Cfn* primitives with wildcards in IAM policies (Action: '*', Resource: '*'). Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftAI drops to low-level Cfn* primitives with wildcards in IAM policies (Action: '*', Resource: '*').Critical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Use AWS CDK L2 constructs (e.g. aws_s3.Bucket, aws_lambda_nodejs.NodejsFunction) rather than raw L1 Cfn* constructs.

Use AWS CDK L2 constructs (e.g. aws_s3.Bucket, aws_lambda_nodejs.NodejsFunction) rather than raw L1 Cfn* constructs.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Enforce least-privilege IAM permissions via native grant methods (table.grantReadWriteData(fn)) instead of attaching AdministratorAccess.

Enforce least-privilege IAM permissions via native grant methods (table.grantReadWriteData(fn)) instead of attaching AdministratorAccess.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Isolate stateful resources (RDS, S3, DynamoDB) into dedicated StateStacks with RemovalPolicy.RETAIN to prevent accidental deletion during CI deployments.

Isolate stateful resources (RDS, S3, DynamoDB) into dedicated StateStacks with RemovalPolicy.RETAIN to prevent accidental deletion during CI deployments.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Integrate cdk-nag security assertion rules in bin/app.ts to detect unencrypted storage and overly permissive security groups.

Integrate cdk-nag security assertion rules in bin/app.ts to detect unencrypted storage and overly permissive security groups.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is AWS CDK v2 Modern L2 Constructs & Least-Privilege IAM Discipline critical for AI coding assistants?

Enterprise cloud infrastructure standard using AWS CDK v2. Mandates higher-level L2/L3 constructs over raw Cfn escape hatches, fine-grained resource-level IAM grants, and strict multi-stack state isolation. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (AI drops to low-level Cfn* primitives with wildcards in IAM policies (Action: '*', Resource: '*').) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

AWS