Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CDK create resource if does not exist - typescript

Created a dynamoDB table in my CDK project. this is fine it is used by lambdas created in the project. We needed to delete the stack which is also fine as we have retain resource set to true on the table.

Now when I try a fresh deploy we get table already exists error and stack rolls back. I need code that will create the table only if it does not exist.

Here is basic creation of a table, i cannot find any documentation anywhere on this issue or even an exception that can be caught or where i can see the type of exception that gets thrown to catch as we only see logs in the cloudformation console on AWS console.

 const dynamoTable = new Table(this, "my-table", {
      tableName: StackConfiguration.tableName,
      partitionKey: { name: "id", type: AttributeType.STRING },
    });
like image 540
AnonymousAlias Avatar asked Mar 17 '26 20:03

AnonymousAlias


2 Answers

Unfortunately you can't do that in CDK, because CDK generates CloudFormation template at compile time, not at runtime. I see several options here:

  1. Use CloudFormation Resource Import to import existing table into your stack
  2. Use Custom resource lambda to do an AWS API call to check if table exists. Use Custom resource output in Fn.conditionEquals in CDK code to create table conditionally

I would recommend going with first option if it's a one-off thing you need to do, and option 2 if you expect this to happen regularly.

like image 136
Tofig Hasanov Avatar answered Mar 20 '26 14:03

Tofig Hasanov


As of Sept 2023, the CDK allows you to import existing resources. I was able to follow these steps to use the CDK to import my existing DynamoDB. However, when I did the cdk import command, it complained that my Lambda functions had changed, even though the cdk diff command reported no changes. I had to add the --force option to the import command.

Note: This did not allow me to do what @AnonymousAlias originally wanted to do, which was to create the resource if needed, and skip it otherwise. I think that in order to do that you would have to do as @Tofig Hasanov suggested, and check if the resource exists first, and create it only if it doesn't exist.

From https://docs.aws.amazon.com/cdk/v2/guide/cli.html#cli-import:

Importing existing resources into a stack

You can use the cdk import command to bring resources under the management of CloudFormation for a particular AWS CDK stack. This is useful if you are migrating to AWS CDK, or are moving resources between stacks or changing their logical id. cdk import uses CloudFormation resource imports. See the list of resources that can be imported here.

To import an existing resource into a AWS CDK stack, follow the following steps:

  • Make sure the resource is not currently being managed by any other CloudFormation stack. If it is, first set the removal policy to RemovalPolicy.RETAIN in the stack the resource is currently in and perform a deployment. Then, remove the resource from the stack and perform another deployment. This process will make sure that the resource is no longer managed by CloudFormation but does not delete it.

  • Run a cdk diff to make sure there are no pending changes to the AWS CDK stack you want to import resources into. The only changes allowed in an "import" operation are the addition of new resources which you want to import.

  • Add constructs for the resources you want to import to your stack. For example, if you want to import an Amazon S3 bucket, add something like new s3.Bucket(this, 'ImportedS3Bucket', {});. Do not make any modifications to any other resource.

    You must also make sure to exactly model the state that the resource currently has into the definition. For the example of the bucket, be sure to include AWS KMS keys, life cycle policies, and anything else that's relevant about the bucket. If you do not, subsequent update operations may not do what you expect.

    You can choose whether or not to include the physical bucket name. We usually recommend to not include resource names into your AWS CDK resource definitions so that it becomes easier to deploy your resources multiple times.

  • Run cdk import STACKNAME.

  • If the resource names are not in your model, the CLI will prompt you to pass in the actual names of the resources you are importing. After this, the import starts.

  • When cdk import reports success, the resource is now managed by AWS CDK and CloudFormation. Any subsequent changes you make to the resource properties in your AWS CDK app the construct configuration will be applied on the next deployment.

  • To confirm that the resource definition in your AWS CDK app matches the current state of the resource, you can start an CloudFormation drift detection operation.

This feature currently does not support importing resources into nested stacks.

like image 34
Gillfish Avatar answered Mar 20 '26 14:03

Gillfish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!