Last active
September 17, 2024 08:13
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Blog post:
AWS CDK の慣用句的テクニックの紹介 - 特定のデプロイステージにのみ適用する設定を Aspects で実装する
https://blog.serverworks.co.jp/2024/09/17/160000