In my stacks, I need to define a dynamo table and ...
# sst
In my stacks, I need to define a dynamo table and pass it into an Api. The issue I have is what I want is to create the table if it doesn't exist but if it does to get a reference to the existing table and then pass that into the Api. I know I can set the
so I can remove the tables on ephemeral environments, but if it is in prod how does it pass a reference to the existing table?
If the table in prod is created outside of the SST app, you can import it like this
You can conditionally import:
Copy code
const table = app.stage === "prod"
  ? new Table(this, "Table", {
      dynamodbTable: dynamodb.Table.fromTableArn(this, "ITable", tableArn),
  : new Table(this, "Table", {
      fields: {
        userId: TableFieldType.STRING,
      primaryIndex: { partitionKey: "userId" },
Thanks Frank, so I'd need to know the ARN... what if I just don't want to delete my "local" databases, so they get created by SST at some point, but then I do a
yarn sst remove
and when I start it back up I don't want to have to go find the arn and poke it in... would this be something that a 'policy' could be defined? Something like:
Copy code
const table = new Table(this, "Table", {
  fields: { userId: TableFieldType.STRING},
  primaryIndex: { partitionKey: "userId" },
  creationPolicy: "ReuseIfExisting"
and if that is set it would go and find the ARN based upon the active aws account, project name and table name?
Hey @jamlen this is a bit tricky to implement with IaC. You would maybe have to do a lookup inside the main function with aws-sdk and pass a variable to tell the stack if it should create or import
Generally this type of thing is avoided in IaC because you can get into some weird scenarios. People typically just fully delete everything on
and let it get recreated
There was a streaming session by the authors of the CDK Book recently and someone asked this question and they essentially said this is an anti-pattern.
I think their answer is half-motivated by the fact that CDK makes this hard.
But they did have a point that this sort of conditional creation of resources make provisioning more complex and less reproduceable.
+1 this is totally hard in CDK.