0

AWS has best practices for CDK in place, which state that it's better to use generated names for resources instead of physical ones, see section "Use generated resource names, not physical names".

Consider the following Construct:

from aws_cdk import aws_timestream
from constructs import Construct

class MyConstruct(Construct):
    def __init__(self, scope, id_):
        super().__init__(scope, id_)
    
    my_database = aws_timestream.CfnDatabase(self, "MyTimestreamDatabase")
    my_table = aws_timestream.CfnTable(
        scope=self, 
        id="MyTimestreamTable",
        database_name=my_database.database_name,
        retention_properties={...}
    )
    my_table.add_depends_on(my_database)

Running cdk synth involving an instance of this class throws

TypeError: type of argument database_name must be str; got NoneType instead

Question: How do I create an Amazon Timestream database with AWS CDK v2 without assigning a physical name to it?

nluckn
  • 171
  • 1
  • 1
  • 16

1 Answers1

1

Passing ref instead works, as it is never None, and it returns the database name. Docs for reference.

Example code:

from aws_cdk import aws_timestream
import aws_cdk as cdk
from constructs import Construct

class MyConstruct(Construct):
    def __init__(self, scope, id_):
        super().__init__(scope, id_)
    
        my_database = aws_timestream.CfnDatabase(self, "MyTimestreamDatabase")
        my_table = aws_timestream.CfnTable(
            self, 
            "MyTimestreamTable",
            database_name=my_database.ref,
        )
        

app = cdk.App()

stack = cdk.Stack(app, "stack")

MyConstruct(stack, "construct")

app.synth()

You don't need to declare an explicit dependency - CDK knows that the table depends on the database because you're passing one of the database's props to it.

I can confirm this synths correctly on my machine with CDK 2.37.1.

gshpychka
  • 8,523
  • 1
  • 11
  • 31
  • Now I can also confirm that it also works on my machine with 2.37.1. Thanks a lot for your help! – nluckn Aug 12 '22 at 11:43
  • Did you manage to figure out why it wasn't working? – gshpychka Aug 12 '22 at 12:06
  • Call me stupid: In fact, I create another table in my code, right after the first one and within the same database, and I only changed `database_name` to `ref` for the first table; so the error was probably from the second table... – nluckn Aug 12 '22 at 12:26
  • Ah, happens. I'm glad it works now. – gshpychka Aug 12 '22 at 12:26