10

I want to create the same CW alarm/metrics for a number of DynamoDB tables in cdk, my instinct was to try to use a for loop to append the name of the DDB table to the CW alarm, but doing so generates the following error: Cannot use tokens in construct ID

It makes sense, because the token has yet to be evaluated so its just a placeholder value. But then what would a good alternative be to sequentially naming the alarms?

My usecase isn't that complicated I could just repeat the same code X times and tweak the name each time, but that seems like an incorrect approach.

I'm using the bellow code for inspiration, but I can't see what values I can call on that wouldn't trigger this error.

https://aws.amazon.com/blogs/developer/aws-cdk-developer-preview/

Claudiu Moise
  • 376
  • 3
  • 14
  • Have you tried using `Table.tableName` attribute? It's a simple `string` – Oleksii Donoha May 22 '20 at 16:54
  • That was my initial approach, but even that was triggering the error. My eventual solution was to have a hardcoded array that contained the half dozen or so tables I was interested in. – Claudiu Moise May 22 '20 at 21:40
  • The key to the solution is to pass the object from which to get the ID from, as the `scope` of the alarm constructor ([ref](https://github.com/aws/aws-cdk/issues/6013#issuecomment-579870328)). The ID will include it, but then can access other IDs as name. – Efren Dec 29 '21 at 04:46

1 Answers1

10

You should use the id or uniqueId of the table, something like:

for (const table of tables) {
  new cloudwatch.Alarm(this, `AlarmFor${table.node.id}`, ...); // or table.node.uniqueId
}

But a better pattern could be to create a TableWithAlarm construct and instantiate it multiple times in your stack.

jogold
  • 6,667
  • 23
  • 41