Skip to content

CDK Python - Clarification on Using Factory Classes and NestedStacks.

0

Hello everyone,

I hope you're doing well.

I’m working on an AWS CDK application in Python where I want to dynamically create S3 buckets using CloudFormation. To organize the code, I’ve implemented a factory class that encapsulates the creation of the buckets using aws_s3.CfnBucket. Below is a simplified version of my current implementation:

class BucketFactory:
    def __init__(self, scope: Construct):
        self.scope = scope

    def create_bucket(self, bucket_name: str):
        raw_bucket = s3.CfnBucket(
            self.scope,
            id=f'bucket-{bucket_name}-L1',
            bucket_name=bucket_name,
            object_lock_enabled=True,
            # other properties
        )
        return raw_bucket

class MyStack(cdk.Stack):
    def __init__(self, scope: Construct, id: str, **kwargs):
        super().__init__(scope, id, **kwargs)

        bucket_factory = BucketFactory(self)
        new_bucket = bucket_factory.create_bucket('nuevo-bucket')

My question is:
In my project, I also have other classes that inherit from cdk.NestedStack, such as:

class MyNestedStack(cdk.NestedStack):
    def __init__(self, scope: Construct, id: str, **kwargs):
        super().__init__(scope, id, **kwargs)
        # additional implementation

Should I apply the same pattern (i.e., passing self as the scope to the BucketFactory) when working inside a NestedStack?
Or is there any risk that this pattern might cause issues or stack deployment failures due to incorrect scoping or usage of low-level constructs like CfnBucket?

Any guidance or best practices you could provide would be greatly appreciated.

Best regards,

asked a year ago192 views
1 Answer
0

Yes, you can apply the same pattern of using the BucketFactory within a NestedStack, passing self as the scope. This approach is valid and should work correctly.

When you create resources within a NestedStack, they become part of that nested stack's template. By passing self as the scope to the BucketFactory when inside a NestedStack, you're ensuring that the S3 buckets are created within the context of that nested stack.

Here's how you could use it within your MyNestedStack:

class MyNestedStack(cdk.NestedStack):
    def __init__(self, scope: Construct, id: str, **kwargs):
        super().__init__(scope, id, **kwargs)
        
        bucket_factory = BucketFactory(self)
        new_bucket = bucket_factory.create_bucket('nested-stack-bucket')

This pattern is safe to use and shouldn't cause issues with scoping or deployment. The CfnBucket (Level 1 construct) will be properly added to the nested stack's template.

However, there are a few things to keep in mind:

  1. Ensure that your bucket names are unique across your entire application, as S3 bucket names must be globally unique.

  2. Be aware that resources in nested stacks are treated as part of the parent stack for deployment purposes. This means that updates to the nested stack will trigger an update of the parent stack.

  3. Cross-references between the parent stack and nested stack are automatically handled by CDK, translating them into stack parameters and outputs as needed.

  4. If you need to reference resources across different nested stacks, you might need to use outputs and imports, which CDK can help manage.

Using this factory pattern with NestedStacks can help organize your code and make it more modular, especially if you have complex infrastructure with many resources. Just ensure you're mindful of the scope in which you're creating resources, and you should be able to use this pattern effectively across both regular Stacks and NestedStacks.
Sources
NestedStack — AWS Cloud Development Kit 2.192.0 documentation
Execute Nested Stacks from the Root Stack using AWS CDK C# | AWS re:Post
AWS Cloud Development Kit Library — AWS Cloud Development Kit 2.192.0 documentation

answered a year ago
AWS
SUPPORT ENGINEER
reviewed a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.