|
1 | | -# Copilot Instructions (TypeScript AWS CDK for this repo) |
2 | 1 | --- |
3 | | -description: 'Brief description of the instruction purpose and scope' |
4 | | -applyTo: 'packages/cdk/**' |
| 2 | +description: 'Guidelines for writing, reviewing, and maintaining AWS CDK (TypeScript) code in the cdk package' |
| 3 | +applyTo: 'packages/cdk/**/*.ts' |
5 | 4 | --- |
6 | | -## Purpose |
7 | | -Guide generation of AWS CDK TypeScript code consistent with existing constructs, patterns, naming conventions, and compliance expectations in this repository. |
8 | | - |
9 | | -## Core Constructs (reuse over raw CDK) |
10 | | -- Prefer custom constructs: |
11 | | - - LambdaFunction -> wraps NodejsFunction with logging, layers, policies ([constructs/LambdaFunction.ts](packages/cdk/constructs/LambdaFunction.ts)). |
12 | | - - RestApiGateway + LambdaEndpoint / StateMachineEndpoint for API resources ([constructs/RestApiGateway.ts](packages/cdk/constructs/RestApiGateway.ts), [constructs/RestApiGateway/LambdaEndpoint.ts](packages/cdk/constructs/RestApiGateway/LambdaEndpoint.ts)). |
13 | | - - ExpressStateMachine for Step Functions ([constructs/StateMachine.ts](packages/cdk/constructs/StateMachine.ts)). |
14 | | - - State machine definition ([resources/StateMachineDefinitions/ClinicalView.ts](packages/cdk/resources/StateMachineDefinitions/ClinicalView.ts)). |
15 | | -- When adding a Lambda, use LambdaFunction; do NOT instantiate NodejsFunction directly unless enhancing the construct itself. |
16 | | - |
17 | | -## Naming & Environment |
18 | | -- Lambda function names: `${stackName}-<ComponentName>` (see Functions.ts). |
19 | | -- Expose new functions via Functions construct; add environment variables into `lambdaDefaultEnvironmentVariables` ([resources/Functions.ts](packages/cdk/resources/Functions.ts)). |
20 | | -- Required env keys pattern: `LOG_LEVEL`, `NODE_OPTIONS="--enable-source-maps"`, `TargetSpineServer`, versioning (`VERSION_NUMBER`, `COMMIT_ID`), secrets layer (`AWS_LAMBDA_EXEC_WRAPPER="/opt/get-secrets-layer"`). |
21 | | -- Use `Fn.importValue` for cross-stack references (KMS keys, policies, secrets). |
22 | | -- Context keys consumed externally: `accountId`, `stackName`, `versionNumber`, `commitId`, `logRetentionInDays` (set via deployment script). |
23 | | - |
24 | | -## Lambda Defaults |
25 | | -Replicate defaults from getDefaultLambdaOptions: |
26 | | -- runtime: `Runtime.NODEJS_22_X` |
27 | | -- memorySize: 256 |
28 | | -- timeout: 50s |
29 | | -- architecture: `X86_64` |
30 | | -- handler: "handler" |
31 | | -- bundling: `target: es2022`, `minify: true`, `sourceMap: true`, `tsconfig` points to package's tsconfig |
32 | | - |
33 | | -## Logging & Retention |
34 | | -- Pass `logRetentionInDays` into constructs; never hard-code retention. |
35 | | -- Log groups encrypted via imported KMS key; maintain existing pattern. |
36 | | -- When adding subscription filters or streams, follow pattern used in LambdaFunction (Kinesis Stream, subscription roles). |
37 | | - |
38 | | -## Policies & Security |
39 | | -- Attach least-privilege managed policies; reuse imported managed policies. |
40 | | -- Suppress cdk-nag rules only via helper in nagSuppressions.ts; do not inline suppressions. |
41 | | -- Avoid wildcard resource ARNs unless justified; document justification consistent with existing reasoning style. |
42 | | - |
43 | | -## API Resources |
44 | | -- For new API route: |
45 | | - 1. Create LambdaFunction in Functions.ts. |
46 | | - 2. Use LambdaEndpoint under RestApiGateway with `resourceName` matching path segment. |
47 | | - 3. Attach execution policy via `restApiGatewayRole.addManagedPolicy(lambda.executionPolicy)` (see LambdaEndpoint construct). |
48 | | - |
49 | | -## Step Functions |
50 | | -- Compose definitions using existing patterns: Pass, Choice, TaskInput, Function.fromFunctionArn for imported lambdas. |
51 | | -- Return a chainable definition assigned to `this.definition`. |
52 | | - |
53 | | -## Layers & Secrets |
54 | | -- Always include secrets layer and Insights layer (see LambdaFunction: insightsLayerArn + getSecretLayer). |
55 | | -- Do not create additional layers unless absolutely needed; if needed, follow same RemovalPolicy and packaging style. |
56 | | - |
57 | | -## Removal Policies |
58 | | -- Log groups: `RemovalPolicy.RETAIN`. |
59 | | -- Layers: `RemovalPolicy.RETAIN`. |
60 | | -- Keep consistent to avoid accidental data loss. |
61 | | - |
62 | | -## Code Style |
63 | | -- Two-space indentation. |
64 | | -- Interfaces named `<Name>Props`. |
65 | | -- Public construct properties explicitly declared (`public readonly`). |
66 | | -- Avoid default exports. |
67 | | -- Use trailing commas only where existing codebase does (mostly arrays/objects in multiline). |
68 | | -- Enforce explicit access modifiers. |
69 | | - |
70 | | -## Import Ordering |
71 | | -1. aws-cdk-lib modules (grouped). |
72 | | -2. Third-party constructs. |
73 | | -3. Local relative imports. |
74 | | -4. Then interfaces & exports. |
75 | | - |
76 | | -## Error Handling |
77 | | -- Do not add try/catch in constructs unless wrapping unsafe dynamic operations; rely on CDK synthesis errors. |
78 | | - |
79 | | -## Adding New Functionality Example (Lambda + Endpoint) |
80 | | -Generate code that: |
81 | | -- Adds a new LambdaFunction in Functions.ts with proper env reuse. |
82 | | -- Adds endpoint in Apis.ts using LambdaEndpoint. |
83 | | - |
84 | | -## What to Avoid |
85 | | -- Direct instantiation of CloudWatch LogGroups outside constructs unless extending logging pattern. |
86 | | -- Hard-coded ARNs instead of `Fn.importValue`. |
87 | | -- Inconsistent environment variable casing. |
88 | | -- Adding inline IAM policies directly to Roles when a ManagedPolicy pattern exists. |
89 | | - |
90 | | -## Testing Expectations |
91 | | -- Any new construct should be testable via snapshot or fine-grained assertions (not provided here—keep design modular). |
92 | | - |
93 | | -## Performance & Bundling |
94 | | -- Keep bundle size small: rely on minification and es2022 target. |
95 | | -- Do not disable source maps (used for debugging with NODE_OPTIONS). |
96 | | - |
97 | | -## cdk-nag |
98 | | -- If new resources trigger nag findings needing suppression, add them to existing grouped calls in nagSuppressions.ts using helper functions; supply reason matching style. |
99 | | - |
100 | | -## Deployment Flow |
101 | | -- Remember deployment scripts set context keys: do not rely on undefined fallbacks; ensure constructs read from props rather than process.env (process.env used only inside Lambda runtime code). |
102 | | - |
103 | | -## Style Snippet Template (for new construct) |
104 | | -```ts |
105 | | -export interface MyFeatureProps { |
106 | | - readonly stackName: string |
107 | | - readonly logRetentionInDays: number |
108 | | - // additional props... |
| 5 | + |
| 6 | +# AWS CDK TypeScript Development |
| 7 | + |
| 8 | +This file provides instructions for generating, reviewing, and maintaining AWS CDK code in the `packages/cdk` folder. It covers best practices, code standards, architecture, and validation for infrastructure-as-code using AWS CDK in TypeScript. |
| 9 | + |
| 10 | +## General Instructions |
| 11 | + |
| 12 | +- Use AWS CDK v2 constructs and idioms |
| 13 | +- Prefer high-level CDK constructs over raw CloudFormation resources |
| 14 | +- Organize code by logical infrastructure components (e.g., stacks, constructs, resources) |
| 15 | +- Document public APIs and exported constructs |
| 16 | + |
| 17 | +## Best Practices |
| 18 | + |
| 19 | +- Use environment variables and context for configuration, not hardcoded values |
| 20 | +- Use CDK Aspects for cross-cutting concerns (e.g., security, tagging) |
| 21 | +- Suppress warnings with `nagSuppressions.ts` only when justified and documented |
| 22 | +- Use `bin/` for entrypoint apps, `constructs/` for reusable components, and `stacks/` for stack definitions |
| 23 | +- Prefer `props` interfaces for construct configuration |
| 24 | + |
| 25 | +## Code Standards |
| 26 | + |
| 27 | +### Naming Conventions |
| 28 | + |
| 29 | +- Classes: PascalCase (e.g., `LambdaFunction`) |
| 30 | +- Files: PascalCase for classes, kebab-case for utility files |
| 31 | +- Variables: camelCase |
| 32 | +- Stacks: Suffix with `Stack` (e.g., `CptsApiAppStack`) |
| 33 | +- Entry points: Suffix with `App` (e.g., `CptsApiApp.ts`) |
| 34 | + |
| 35 | +### File Organization |
| 36 | + |
| 37 | +- `bin/`: CDK app entry points |
| 38 | +- `constructs/`: Custom CDK constructs |
| 39 | +- `stacks/`: Stack definitions |
| 40 | +- `resources/`: Resource configuration and constants |
| 41 | +- `lib/`: Shared utilities and code |
| 42 | + |
| 43 | +## Common Patterns |
| 44 | + |
| 45 | +### Good Example - Defining a Construct |
| 46 | + |
| 47 | +```typescript |
| 48 | +export class LambdaFunction extends Construct { |
| 49 | + constructor(scope: Construct, id: string, props: LambdaFunctionProps) { |
| 50 | + super(scope, id); |
| 51 | + // ...implementation... |
| 52 | + } |
109 | 53 | } |
| 54 | +``` |
| 55 | + |
| 56 | +### Bad Example - Using Raw CloudFormation |
| 57 | + |
| 58 | +```typescript |
| 59 | +const lambda = new cdk.CfnResource(this, 'Lambda', { |
| 60 | + type: 'AWS::Lambda::Function', |
| 61 | + // ...properties... |
| 62 | +}); |
| 63 | +``` |
110 | 64 |
|
111 | | -export class MyFeature extends Construct { |
112 | | - public readonly lambda: LambdaFunction |
113 | | - public constructor(scope: Construct, id: string, props: MyFeatureProps) { |
114 | | - super(scope, id) |
115 | | - this.lambda = new LambdaFunction(this, "MyFeatureLambda", { |
116 | | - stackName: props.stackName, |
117 | | - functionName: `${props.stackName}-MyFeature`, |
118 | | - packageBasePath: "packages/myFeature", |
119 | | - entryPoint: "src/handler.ts", |
120 | | - environmentVariables: {/* extend from shared defaults */}, |
121 | | - logRetentionInDays: props.logRetentionInDays, |
122 | | - logLevel: "INFO" |
123 | | - }) |
| 65 | +### Good Example - Stack Definition |
| 66 | + |
| 67 | +```typescript |
| 68 | +export class CptsApiAppStack extends Stack { |
| 69 | + constructor(scope: Construct, id: string, props?: StackProps) { |
| 70 | + super(scope, id, props); |
| 71 | + // ...add constructs... |
124 | 72 | } |
125 | 73 | } |
126 | 74 | ``` |
127 | 75 |
|
128 | | -## Consistency |
129 | | -Generate code that composes existing constructs, avoids duplication, and maintains naming / environment conventions. |
| 76 | +## Security |
| 77 | + |
| 78 | +- Use least privilege IAM policies for all resources |
| 79 | +- Avoid wildcard permissions in IAM statements |
| 80 | +- Store secrets in AWS Secrets Manager, not in code or environment variables |
| 81 | +- Enable encryption for all data storage resources |
| 82 | + |
| 83 | +## Performance |
| 84 | + |
| 85 | +- Use provisioned concurrency for Lambda functions when needed |
| 86 | +- Prefer VPC endpoints for private connectivity |
| 87 | +- Minimize resource creation in test environments |
| 88 | + |
| 89 | + |
| 90 | +## Validation and Verification |
| 91 | + |
| 92 | +- Build: `make cdk-synth` |
| 93 | +- Lint: `npm run lint --workspace packges/cdk` |
| 94 | + |
| 95 | +## Maintenance |
| 96 | + |
| 97 | +- Update dependencies regularly |
| 98 | +- Remove deprecated constructs and suppressions |
| 99 | +- Document changes in `nagSuppressions.ts` with reasons |
| 100 | + |
| 101 | +## Additional Resources |
130 | 102 |
|
131 | | -## If Unsure |
132 | | -Prefer referencing or extending an existing construct rather than creating raw CDK resources. |
| 103 | +- [AWS CDK Documentation](https://docs.aws.amazon.com/cdk/latest/guide/home.html) |
| 104 | +- [CDK Best Practices](https://github.com/aws-samples/aws-cdk-best-practices) |
0 commit comments