0
votes

Using the CDK to create KMS Keys (and other resources for that matter) for my project and want to ensure I'm handling the resource properly.

During my development stage I might do a deploy, do some development work then issue a cdk destroy to cleanup the project as I know I'll not be back to it for some days.

If I don't wrap the code in an import I find duplicate keys are being created or for some resources like DynamoDB it will fail with the resource already existing:

 try {
      const keyRef = kms.Alias.fromAliasName(this, 'SomeKey', 'SomeKey');
    } catch {
      const keyRef = new kms.Key(this, 'SomeKey', {
        description: 'Some descriptive text',
        enableKeyRotation: true,
        trustAccountIdentities: true
      });

      keyRef .grantEncryptDecrypt(lambdaFunc);
    }

Can anyone suggest a better way of handling this or is this expected?

While developing my projects I don't like to leave resources in play until the solution is at least at Alpha stage.

1

1 Answers

0
votes

When creating a KMS, you can define a RemovalPolicy:

The default value for it is RETAIN, meaning that the KMS key will stay in your account even after you delete your stack. This is useful for production environment, where you would normally want to keep keys that might be used by resources outside your stack.

In your dev environment you can set it to DESTROY and it will be deleted with your stack.

You should capture this logic in your code. Something like

    const keyRef = new kms.Key(this, 'SomeKey', {
        description: 'Some descriptive text',
        enableKeyRotation: true,
        trustAccountIdentities: true,

        // define a method to check if it's a dev environment 
        // and set removalPolicy accordingly
        removalPolicy: isDevEnv() ? cdk.RemovalPolicy.DESTROY : cdk.RemovalPolicy.RETAIN,
    });