pythonamazon-web-servicesaws-cdkamazon-timestream

Create Amazon Timestream database without physical name using AWS CDK v2


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?


Solution

  • 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.