Skip to content

Instantly share code, notes, and snippets.

@hassaku63
Last active September 17, 2024 08:13
Show Gist options
  • Save hassaku63/625927f26ac49ae2f6edd708b3840980 to your computer and use it in GitHub Desktop.
Save hassaku63/625927f26ac49ae2f6edd708b3840980 to your computer and use it in GitHub Desktop.
CDK app example impl. (set RemovalPolicy = "DELETE" if performing deployment to 'dev' stage)
#!/usr/bin/env node
import 'source-map-support/register';
import * as cdk from 'aws-cdk-lib';
import { IConstruct } from 'constructs';
import { MyStack } from '../lib/my-stack';
const app = new cdk.App();
const availableStages = ['dev', 'stg', 'prod'] as const;
type Stage = typeof availableStages[number];
function isValidStage(stage: string): stage is Stage {
return availableStages.includes(stage as Stage);
}
const stage = app.node.tryGetContext('stage');
if (!isValidStage(stage)) {
throw new Error(`Invalid stage: ${stage}`);
}
new MyStack(app, 'MyStack', {});
// Add tags to all resources
cdk.Tags.of(app).add('Project', 'MyProject');
// Apply removal policy to all resources in given node
class EnforceDeletionPolicy implements cdk.IAspect {
public visit(node: IConstruct): void {
if (node instanceof cdk.CfnResource) {
node.applyRemovalPolicy(cdk.RemovalPolicy.DESTROY);
}
}
}
// Apply a policy to all resources in the 'dev' stage
if (stage === 'dev') {
cdk.Aspects.of(app).add(new EnforceDeletionPolicy());
}
@hassaku63
Copy link
Author

Blog post:

AWS CDK の慣用句的テクニックの紹介 - 特定のデプロイステージにのみ適用する設定を Aspects で実装する

https://blog.serverworks.co.jp/2024/09/17/160000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment