How to skip DynamoDB Table creation if already exists
:question: General Issue
The Question
How can we skip if the Dynamo Table creation if already existing in the stack, otherwise always create a new table. or Is there any way to catch the error and proceed with the next steps? (Similar to Try/Catch)
Environment
- CDK CLI Version: 1.27.0
- Module Version: 1.20.0
- OS: Macintosh
- Language: TypeScript
Other information
We have a SingletonFunction construct that does something similar for lambda Functions. You can find the source of it at @aws-cdk/aws-lambda/lib/singleton-lambda.ts.
Conceptually, it creates the resource in the root Stack (instead of in some construct's scope). A UUID is assigned to reduce the risk of collisions with a legitimate construct scoped to the Stack as well... Then we use tryFindChild to tell if the singleton already exists, creating it otherwise.
You should be able to easily implement the same pattern for a DynamoDB Table.
Thanks for the reply. Do we have any way to check the existence of the DynamoDB table in an AWS environment through CDK?
I believe this is possible with a CustomResource.
https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-cloudformation.CustomResource.html
@Douglas-Scott Sorry, but that documentation page is far from helpful.
Is there any example available how to check if the table does exist? We use RemovalPolicy.RETAIN on the DB so when we remove our stack but not our DB, it would be nice if it could skip DB creation and just continue.
I create on solution which you might find hacky, but it works fine in our CDK stack deploy script:
import * as Dynamodb from 'aws-sdk/clients/dynamodb';
import { SharedIniFileCredentials } from 'aws-sdk';
...
async checkIfDynamoDbExists(name: string ) {
const credentials = new SharedIniFileCredentials({profile: this.user});
const dynamodb = new Dynamodb({
region: this.config.region,
credentials: this.user ? credentials : undefined
});
const tables = await dynamodb.listTables().promise();
return tables!.TableNames!.indexOf(name) > 0;
}
It will return me a true or false, and based on that I either create a table or get it:
const tableExists = await this.resourceService.checkIfDynamoDbExists(applicationName);
let dynamoDBTable: Table;
if (!tableExists) {
dynamoDBTable = new DynamoDbConstruct(this, `${id}-dynamoDb`, {
applicationName
}).table;
} else {
dynamoDBTable = Table.fromTableName(this, 'Table', applicationName) as Table;
}
Why is this issue closed? Seems like a pretty big missing piece for IaC. How is a CDK stack that creates an API, crud Lambdas and a DynamoDB supposed to re-deploy?
I agree this is crazy that this issue is closed.
So a downside of that workaround I proposed is that if you recreate your stack, and the table needs to be assimilated, it will not be part of the stack by just using the fromTableName solution.
You actually have to import the CFN resource of your table back into your new stack using an import in the CF dashboard.
If you your stack has created the table in the first place, it will not throw an error on redeploy. It knows that the table exists. Only if you have recreated your stack, the table would be an orphan. And you have to bring it into your family.
I've created another issue here https://github.com/aws/aws-cdk/issues/11208 raised it as a bug cause it sounds like it is to me but looks like the stance on it is that when a stack is pulled down it only retains resources to prevent data loss and is not meant to be used again. I thought it was common enough to pull down stacks though from time to time for a fresh deployment it can be great to fix something when having problems trouble shooting an issue. The old turn it off and back on trick
return tables!.TableNames!.indexOf(name) > 0;
This may need to be ...indexOf(name) >= 0 as the index of the table name is 0 if it exists.
const tables = await dynamodb.listTables().promise(); return tables!.TableNames!.indexOf(name) > 0;
It is not even safe to assume this will always work, as the result of listTables() is paginated.
I've created a solution which might seem a bit long, but works for any construct as far as I'm aware (and will pay off if you do this to multiple resources).
First of all I've assumed this is being done because the removalPolicy is retain, though if this is not the case, naming schemes can easily be modified.
Unfortunately this solution involves tags. If this doesn't float your boat, sorry.
The essence is that you search for aws resources with a predefined tag key. We use the ARN from the aws resource to get the id of the resource. If the id matches one of the ids of the cdk constructs, skip the creation of that construct:
(I cba to extract stuff out so here is the entire file)
import { Construct } from "constructs";
import { RemovalPolicy, Stack, StackProps, Tags} from "aws-cdk-lib"
import * as ecr from "aws-cdk-lib/aws-ecr"
import { config as AWSConfig, ResourceGroupsTaggingAPI } from "aws-sdk"
AWSConfig.update({region:'eu-west-2'});
const RETAIN_TAG = "retain-removal-policy"
export default class BaseStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props)
this.initStatefulConstructs()
}
/**
* Stateful constructs will generally be retained (cdk destroy will keep the constructs in AWS)
*/
async initStatefulConstructs() {
const resources = [
new ecr.Repository(this, "api-repo", {
repositoryName: "api-repo",
imageTagMutability: ecr.TagMutability.MUTABLE,
removalPolicy: RemovalPolicy.RETAIN
})
]
let deployedRetainedIds: string[] = await this.getDeployedRetainedIds()
resources.forEach(x => {
Tags.of(x).add(RETAIN_TAG, "")
const id = x.node.id
if (deployedRetainedIds.includes(id)){
console.log(`${id} already exists - skipping creation`)
this.node.tryRemoveChild(id)
}
})
}
/**
* @param arn AWS ARN identifier
* @returns ID (aka Physical Name) of the resource
*/
getIdFromARN(arn: string): string {
let name = arn.substring(arn.search(/:.*$/) + 1)
name = name.substring(name.search(/\/.*$/) + 1)
return name
}
/**
* @returns IDs of the retained resources currently deployed on AWS
*/
async getDeployedRetainedIds() {
let deployedRetainedIds: string[] = []
const api = new ResourceGroupsTaggingAPI()
let nextPage = ""
do{
const ret = await api.getResources({
TagFilters: [{ Key: RETAIN_TAG }],
PaginationToken: nextPage
}).promise()
nextPage = ret.PaginationToken ?? ""
const ids = ret.ResourceTagMappingList?.map(x => this.getIdFromARN(x.ResourceARN ?? '')) ?? []
deployedRetainedIds = [...deployedRetainedIds, ...ids]
} while(nextPage !== "")
return deployedRetainedIds
}
}
Although the async function is not awaited, it will be executed before program exit.
Just add any constructs you want to skip creation of (when existing) to the resources array.
Hope someone finds this helpful
Hello, any update on that issue? Currently I'm locally storing tables per env that don't need update into a json file (far to be optimal) Can't we update an existing table? Like adding scalability parameters or stream options, .. .?
Why is this closed? It seems weird that most other constructs can be changed and are ignored if there isnt any change in a stack, but for some reason dynamodb tables cause it to fail. I dont see how hacky workarounds are a viable answer to a bad feature.
Is this the same strategy I would use for cognito user pools? I have the same problem. If there's a user pool already there by this name I don't want to create another one. This way I can turn off delete protection and have everything still work.
Bump, we need an update on this, it's been almost 3 years since this issue was generated.
+1
This appears to be a feature request, that is valuable to the community, and is in fact behavior many assume it would have already. I'm confused why it's closed.
The ask seems straightforward, however difficult the implementation may be: when deploying a stack, have the option to adopt persistent resources (DDB, S3, etc) during name collision rather than erroring out. I assume there is devil in those details, but the issue should remain open?
Retaining persistent resources during stack deletion is definitely better than deleting them, so kudos to AWS CFN/CDK teams for that, but if we cannot re-adopt them then the dev is left in an encumbered position and re-deploying the stack around those resources is a very likely solution they want.
This issue appears to be happening in CDK v2, albeit inconsistently. Does anyone know what triggers this?
Another brick in the wall.
I created a stack with CDK, re-arranged the stack so the code with the DynamoDB Tables are in a construct now, pushing the stack:
TableXXX already exists in stack arn:aws:cloudformation:xxx:xxx:stack/xxx
What is the work around ? Back up and restore?