Delete a Cognito User Pool on CDK Destroy in AWS CDK


Borislav Hadzhiev

Last updated: Apr 14, 2022


Photo from Unsplash

Deleting a Cognito User Pool on CDK Stack Deletion #

In order to delete a Cognito User Pool when our CDK stack is deleted, we need to override theremovalPolicy prop of the user pool and set it to DESTROY.

const userPool = new cognito.UserPool(this, 'user-pool', { // // 👇 set to DESTROY removalPolicy: cdk.RemovalPolicy.DESTROY, });

If we run the cdk destroy command after we've updated the removalPolicy prop, our Cognito User Pool will get deleted along with the stack.

The Cognito User Pool would also get deleted if we delete the resource from our CDK code.

Default Behavior is to Retain Stateful Resources #

By default stateful resources (databases, tables, user pools) in AWS CDK have their removalPolicy set to RETAIN - docs.

const userPool = new cognito.UserPool(this, 'user-pool', { // ... // 👇 default is RETAIN removalPolicy: cdk.RemovalPolicy.RETAIN, });

When the removalPolicy is set to RETAIN, the Cognito User Pool will not get deleted when the stack gets deleted. Instead, it will remain in the account in an orphaned state.

The same is the default behavior for when we delete Dynamodb tables, S3 Buckets, and other stateful resources.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.