I’m curious about how to use CI/CD in conjunction with AWS CDK; specifically, I want need a pattern where if a given resource does not yet exist, it is created else the (therefore existing) resource is referenced.
Here is an attempt to create a DynamoDb table if it does not exist else reference it. I’m curious, is this the correct/canonical way to do this?
const existingTable = dynamodb.Table.fromTableName(stack, 'ExistingTable', 'existing-table-name');
const table = new dynamodb.Table(stack, 'MyTable', {
tableName: 'my-table',
partitionKey: { name: 'id', type: dynamodb.AttributeType.STRING },
// Define other table attributes
});
if (!existingTable.tableArn) {
// Create the table if it doesn't exist
table.create();
}
This is not something you can do only using CDK. CDK is not a library that interacts with AWS resource APIs by default (there are some exceptions, such as the functions that generally start with lookup*
). It is a library that generates CloudFormation templates. Those templates do not have the ability to "create a resource if it doesn't exist" semantic.
You have a few options here:
fromTableName
/fromTableArn
methods. This is my personal preference, and where appropriate I use this pattern.Keep in mind that, generally speaking, this is an anti-pattern. You should know at deploy-time whether you are are using an existing resource or creating a new one. Having it dynamically detect and change what is deployed opens you up to errors/unexpected behavior, up to and including data loss:
Fn::ImportValue
to ensure there is a dependency between two stacks, where one provides the table and the other uses it.