🤔 Are you backing up your git repositories?

Nick Jones

Product-Focused CTO, Founder,
Software Engineer, Indie Hacker

Cleaning up Secrets with multiple AWS CDK Stacks

If you’re using multiple stacks and are running into trouble deleting secrets you may be seeing this message:

Export ${ref} cannot be deleted as it is in use by ${stack}

As covered by Adam Ruka this because CloudFormation is validating a soon to be invalidated version of the template and preventing from deleting a reference another template relies on.

To fix this issue, deploy a version of your stack when you manually export the secret, then do a second deploy to clean the secret up.

For example, starting with the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
import { Stack } from 'aws-cdk-lib';
import { ISecret, Secret } from 'aws-cdk-lib/aws-secretsmanager';

class SecretStack extends Stack {
  public secret: Secret;
  constructor() {
    this.secret = new Secret(this, 'ExampleSecret', {});
  }
}

class DependantSatck extends Stack {
  constructor(secret: ISecret) {}
}

Export the secret manually and clean up your reference to it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
--- initial.ts	2023-07-14 11:00:13
+++ next.ts	2023-07-14 11:00:38
@@ -5,9 +5,10 @@
   public secret: Secret;
   constructor() {
     this.secret = new Secret(this, 'ExampleSecret', {});
+    this.exportValue(this.secret.secretArn);
   }
 }

 class DependantSatck extends Stack {
-  constructor(secret: ISecret) {}
+  constructor() {}
 }

Then clean up the secret itself.

1
2
3
4
5
6
7
8
9
10
11
12
13
--- next.ts	2023-07-14 11:00:38
+++ next2.ts	2023-07-14 11:01:11
@@ -1,11 +1,7 @@
 import { Stack } from 'aws-cdk-lib';
-import { ISecret, Secret } from 'aws-cdk-lib/aws-secretsmanager';

 class SecretStack extends Stack {
-  public secret: Secret;
   constructor() {
-    this.secret = new Secret(this, 'ExampleSecret', {});
-    this.exportValue(this.secret.secretArn);
   }
 }