[CDK] How do I update a stack resources in CDK without duplicating them?

0

Hello, I am somewhat new to CDK. Or at least I haven't came across this problem.

Problem: I created a stack in CDK and accidentally named it the wrong file. I also unwillingly used a module that I was not suppose to use for my particular use case. I now need to refactor the code in the stack to create resources without the module. I also need to rename the file. For example, I created an S3 bucket. I didn't add an event notificaiton. Now I want to add an event notification on the existing S3 bucket that I already created, in my new refactored code.

**Goal: ** The solution I'm looking to achieve is to update the existing stack I created with the new code and same resources except a few different parameters, without redeploying separate resources as a separate entity. Is there a way I can make configuration changes to my existing S3 bucket by just updating the stack, despite the file name changed?

1 Answer
0

With AWS CDK, the stacks you write are managed by a CDK app, or a project. You can name your source files in your project as you wish, you can rename the files freely. Renaming a file does not affect the file content.

When you deploy a CDK app using cdk deploy, an AWS CloudFormation stack (or multiple stacks) will be generated behind the scenes.

The physical names of the AWS CloudFormation stacks are automatically determined by the AWS CDK based on the stack's construct path in the tree. By default, a stack's name is derived from the construct ID of the Stack object. You provide the stack ID as a string in your code, like this:

const app = new App();

new MyFirstStack(app, 'MyStack1');

If you don't change the stack ID in your code, CDK will generate the same CloudFormation stack name and thus will update your existing (deployed) stack next time you run cdk deploy, instead of creating a new one.

In a nutshell:

  • you can rename your CDK project files as you want
  • update the resource configuration in your CDK code as you need
  • run cdk deploy
  • as long as you do not change the construct IDs, CDK will figure out whether it should create new resources or update existing ones

You can read more about how CDK works in the documentation.

profile pictureAWS
answered a year ago
profile picture
EXPERT
reviewed 22 days ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions