Skip to content

AbstractAWSResourceBuilder

Bases: ABC, Generic[TBuilder, TConfig]

Abstract base class for building AWS resources using the builder pattern.

This class provides a consistent interface for building various AWS resources with proper configuration validation, naming conventions, and tagging support. All concrete builders should inherit from this class and implement the required abstract methods.

Class Type Parameters:

Name Bound or Constraints Description Default
- TBuilder

The concrete builder type that inherits from this class

required
- TConfig

The Pydantic model type used for configuration validation

required
Class Attributes

_resource_type (AWSResourceType): Must be defined by subclasses to specify the type of AWS resource being built _requires_builder_config (bool): Whether the builder requires configuration to be set before building (default: True) _requires_usage (bool): Whether the builder requires usage to be specified before building (default: False)

Source code in mare_aws_common_lib/builders/abstract_aws_resource_builder.py
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
class AbstractAWSResourceBuilder(ABC, Generic[TBuilder, TConfig]):
    """
    Abstract base class for building AWS resources using the builder pattern.

    This class provides a consistent interface for building various AWS resources
    with proper configuration validation, naming conventions, and tagging support.
    All concrete builders should inherit from this class and implement the required
    abstract methods.

    Type Parameters:
        - TBuilder: The concrete builder type that inherits from this class
        - TConfig: The Pydantic model type used for configuration validation

    Class Attributes:
        _resource_type (AWSResourceType): Must be defined by subclasses to specify
            the type of AWS resource being built
        _requires_builder_config (bool): Whether the builder requires configuration
            to be set before building (default: True)
        _requires_usage (bool): Whether the builder requires usage to be specified
            before building (default: False)
    """

    _resource_type: AWSResourceType  # All subclasses must define this
    _requires_builder_config: bool = True
    _requires_usage: bool = False

    def __init__(self) -> None:
        self._setup_logger()
        self.reset()

    def _setup_logger(self) -> None:
        """
        Setup a clean logger for builder operations.

        Creates a logger with the builder's class name and configures it
        with a simple message-only format. Sets logging level to ERROR
        to reduce noise during normal operations.
        """
        self.logger = logging.getLogger(TBuilder.__name__)

        if not self.logger.handlers:
            handler = logging.StreamHandler()
            formatter = logging.Formatter('%(message)s')
            handler.setFormatter(formatter)
            self.logger.addHandler(handler)
            self.logger.setLevel(logging.ERROR)
            self.logger.propagate = False

    @abstractmethod
    def reset(self) -> None:
        """
        Reset the builder to its initial state.

        Clears all configuration, helper references, tags, and other internal
        state. This method must be implemented by subclasses to handle any
        additional state they maintain.

        Note:
            This is called during initialization and can be called manually
            to reuse a builder instance for multiple resources.
        """
        self._application_helper: ApplicationHelper = None
        self._builder_config: Dict[str, Any] = {}
        self._usage: Usage = None
        self._tags: Dict[str, str] = {}
        self._config: TConfig = None

    def set_application_helper(self, app_helper: ApplicationHelper) -> TBuilder:
        """
        Set the application helper for resource naming and configuration.

        Args:
            app_helper (ApplicationHelper): Helper instance containing application
                context and configuration needed for resource creation

        Returns:
            TBuilder: Self reference for method chaining
        """
        self._application_helper = app_helper
        return self

    def set_builder_config(self, config: Dict[str, Any]) -> TBuilder:
        """
        Set the raw configuration dictionary for the builder.

        Args:
            config (Dict[str, Any]): Configuration dictionary containing
                resource-specific settings

        Returns:
            TBuilder: Self reference for method chaining
        """
        self._builder_config = config
        return self

    @abstractmethod
    def _set_config(self) -> None:
        """
        Parse and validate the builder configuration into a typed config object.

        This method should take the raw configuration from _builder_config
        and convert it into a validated Pydantic model instance stored in _config.
        Must be implemented by subclasses to handle their specific configuration
        schema.

        Raises:
            ValidationError: If the configuration is invalid according to the
                Pydantic model schema
        """
        pass

    def set_usage(self, usage: Usage) -> TBuilder:
        """
        Set the usage context for the resource being built.

        Args:
            usage (Usage): Usage enum value indicating the intended use case

        Returns:
            TBuilder: Self reference for method chaining
        """
        self._usage = usage
        return self

    def _get_snc_key_by_alias(self, scope: Construct, from_foundation: bool = False, key_id_suffix: str = None) -> kms.Key:
        """
        Retrieve an organizational KMS key for Sensitive Non Classified (SNC) data encryption.

        Constructs the standardized KMS key alias following organizational naming
        conventions and retrieves the existing key for resource encryption.
        The key alias follows the pattern:
        alias/{domain}[-foundation]-{project}-{environment}-{resource_type}-snc-key

        Args:
            scope (Construct): CDK construct scope for the key lookup
            from_foundation (bool, optional): Whether to use the foundation-provided key
                instead of a project-specific key. Defaults to False.
            key_id_suffix (str, optional): Additional suffix to append to the key ID
                for disambiguation when multiple keys share the same alias pattern.
                Defaults to None.

        Returns:
            kms.Key: KMS Key instance configured for SNC data encryption

        Note:
            The method includes debug print statements for key_alias and key_id
            which should be removed in production code.
        """
        # Build key alias
        key_parts = [f"alias/{self._application_helper.get_domain()}"]
        if from_foundation:
            key_parts.append("foundation")
        key_parts.extend([
            self._application_helper.get_project(),
            self._application_helper.get_target_env(),
            self._resource_type.value,
            "snc-key"
        ])
        key_alias = "-".join(key_parts).lower()
        key_id = key_alias
        if key_id_suffix is not None:
            key_id = f"{key_alias}/{key_id_suffix}"

        return kms.Key.from_lookup(scope, key_id.replace("-"," ").title().replace(" ", ""), alias_name=key_alias)

    def _get_cfn_logical_id(self, resource_type_suffix: str = None, git_branch: str = None, target_env: str = None) -> str:
        """
        Generate a CloudFormation logical ID for the resource.

        Args:
            resource_type_suffix (str, optional): Additional suffix to append
                to the resource type for uniqueness
            git_branch (str, optional): Git branch name to include
                in the logical ID
            target_env (str, optional): Target environment name to include
                in the logical ID

        Returns:
            str: CloudFormation-compliant logical ID for the resource
        """
        return ResourceNaming.get_cfn_logical_id(self._application_helper, self._resource_type, self._usage, 
                                                 resource_type_suffix, git_branch, target_env)

    def _get_name_for_resource(self, resource_name: str = None, git_branch: str = None, max_length: int = None) -> str:
        """
        Generate a properly formatted name for the AWS resource.

        Uses the ResourceNaming utility to create names that follow AWS naming
        conventions and organizational standards. If the name is truncated due
        to length limits, the original name is stored as a tag.

        Args:
            resource_name (str, optional): Base name for the resource
            git_branch (str, optional): CodeCommit branch name to include
            max_length (int, optional): Maximum length constraint for the name

        Returns:
            str: The formatted resource name ready for use in AWS
        """
        full_name, original_name = ResourceNaming.get_name_for_resource(self._application_helper, self._resource_type, self._usage, 
                                             resource_name, git_branch, max_length)
        if original_name is not None:
            self._tags[full_name] = original_name

        return full_name

    def _tag_resource(self, resource: Construct) -> None:
        """
        Apply accumulated tags to the specified AWS resource.

        Adds all tags that have been collected during the build process
        (such as original names before truncation) to the resource.
        Clears the internal tag collection after application.

        Args:
            resource (Construct): The AWS CDK construct to tag
        """
        if self._tags:
            for key, value in self._tags.items():
                Tags.of(resource).add(key, value)
            self._tags = {}

    @abstractmethod
    def build(self) -> Any:
        """
        Build and return the configured AWS resource.

        This is the main method that creates the actual AWS resource based on
        the accumulated configuration. Must be implemented by subclasses to
        handle their specific resource creation logic.

        Returns:
            Any: The created AWS resource (type depends on the specific builder)

        Raises:
            ValueError: If required configuration is missing or invalid
            ValidationError: If the configuration fails validation
        """
        self._control_consistency()

    def _format_validation_error(self, error: ValidationError) -> str:
        """
        Format a Pydantic validation error into a human-readable message.

        Converts ValidationError exceptions into clear, actionable error messages
        with proper formatting and context for debugging configuration issues.

        Args:
            error (ValidationError): The Pydantic validation error to format

        Returns:
            str: Formatted error message with clear field paths and descriptions
        """
        error_messages = []

        for err in error.errors():
            field_path = " -> ".join(str(loc) for loc in err['loc']) if err['loc'] else "Model"
            error_type = err['type']
            message = err['msg']
            input_value = err.get('input', 'Not provided')

            # Custom messages for common error types
            if error_type == 'missing':
                formatted_msg = f"❌ REQUIRED FIELD MISSING: '{field_path}'"
            elif error_type == 'string_type':
                formatted_msg = f"❌ INVALID TYPE for '{field_path}': Expected string, got {type(input_value).__name__} ({input_value})"
            elif error_type == 'value_error':
                # For model-level validation errors, clean up the message
                clean_message = message.replace("Value error, ", "")
                if field_path == "Model":
                    formatted_msg = f"❌ MODEL VALIDATION ERROR: {clean_message}"
                else:
                    formatted_msg = f"❌ VALIDATION ERROR for '{field_path}': {clean_message}"
            else:
                formatted_msg = f"❌ ERROR in '{field_path}': {message} (got: {input_value})"

            error_messages.append(formatted_msg)

        error_messages.append("\n")
        return "\n".join(error_messages)

    def _log_validation_error(self, error: ValidationError, model: BaseModel) -> None:
        """
        Log a formatted validation error to the logger.

        Convenience method that formats a validation error and logs it
        at ERROR level with the model name for context.

        Args:
            error (ValidationError): The validation error that occurred
            model (BaseModel): The Pydantic model that failed validation
        """
        error_msg = self._format_validation_error(error)
        logging.error(f"❌ {model.__name__} validation failed!\n{error_msg}")

    @abstractmethod
    def _control_consistency(self) -> None:
        """
        Validate that all required configuration is present before building.

        Performs consistency checks to ensure the builder is in a valid state
        for resource creation. This includes verifying required helpers,
        configurations, and usage settings based on the builder's requirements.

        Must be implemented by subclasses to add any additional consistency
        checks specific to their resource type.

        Raises:
            ValueError: If any required configuration is missing or invalid
        """
        if not self._application_helper:
            raise ValueError("Application helper must be set before building.")

        if self._requires_builder_config and not self._builder_config:
            raise ValueError("Builder configuration must be set before building.")

        if self._requires_usage:
            if not self._usage:
                raise ValueError("Usage must be set before building.")

            if not isinstance(self._usage, Usage):
                raise ValueError(f"Invalid usage type: {self._usage}. Expected one of {Usage.list()}")

Attributes

_requires_builder_config = True class-attribute instance-attribute

_requires_usage = False class-attribute instance-attribute

_resource_type instance-attribute

Functions

__init__()

Source code in mare_aws_common_lib/builders/abstract_aws_resource_builder.py
47
48
49
def __init__(self) -> None:
    self._setup_logger()
    self.reset()

_control_consistency() abstractmethod

Validate that all required configuration is present before building.

Performs consistency checks to ensure the builder is in a valid state for resource creation. This includes verifying required helpers, configurations, and usage settings based on the builder's requirements.

Must be implemented by subclasses to add any additional consistency checks specific to their resource type.

Raises:

Type Description
ValueError

If any required configuration is missing or invalid

Source code in mare_aws_common_lib/builders/abstract_aws_resource_builder.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
@abstractmethod
def _control_consistency(self) -> None:
    """
    Validate that all required configuration is present before building.

    Performs consistency checks to ensure the builder is in a valid state
    for resource creation. This includes verifying required helpers,
    configurations, and usage settings based on the builder's requirements.

    Must be implemented by subclasses to add any additional consistency
    checks specific to their resource type.

    Raises:
        ValueError: If any required configuration is missing or invalid
    """
    if not self._application_helper:
        raise ValueError("Application helper must be set before building.")

    if self._requires_builder_config and not self._builder_config:
        raise ValueError("Builder configuration must be set before building.")

    if self._requires_usage:
        if not self._usage:
            raise ValueError("Usage must be set before building.")

        if not isinstance(self._usage, Usage):
            raise ValueError(f"Invalid usage type: {self._usage}. Expected one of {Usage.list()}")

_format_validation_error(error)

Format a Pydantic validation error into a human-readable message.

Converts ValidationError exceptions into clear, actionable error messages with proper formatting and context for debugging configuration issues.

Parameters:

Name Type Description Default
error ValidationError

The Pydantic validation error to format

required

Returns:

Name Type Description
str str

Formatted error message with clear field paths and descriptions

Source code in mare_aws_common_lib/builders/abstract_aws_resource_builder.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
def _format_validation_error(self, error: ValidationError) -> str:
    """
    Format a Pydantic validation error into a human-readable message.

    Converts ValidationError exceptions into clear, actionable error messages
    with proper formatting and context for debugging configuration issues.

    Args:
        error (ValidationError): The Pydantic validation error to format

    Returns:
        str: Formatted error message with clear field paths and descriptions
    """
    error_messages = []

    for err in error.errors():
        field_path = " -> ".join(str(loc) for loc in err['loc']) if err['loc'] else "Model"
        error_type = err['type']
        message = err['msg']
        input_value = err.get('input', 'Not provided')

        # Custom messages for common error types
        if error_type == 'missing':
            formatted_msg = f"❌ REQUIRED FIELD MISSING: '{field_path}'"
        elif error_type == 'string_type':
            formatted_msg = f"❌ INVALID TYPE for '{field_path}': Expected string, got {type(input_value).__name__} ({input_value})"
        elif error_type == 'value_error':
            # For model-level validation errors, clean up the message
            clean_message = message.replace("Value error, ", "")
            if field_path == "Model":
                formatted_msg = f"❌ MODEL VALIDATION ERROR: {clean_message}"
            else:
                formatted_msg = f"❌ VALIDATION ERROR for '{field_path}': {clean_message}"
        else:
            formatted_msg = f"❌ ERROR in '{field_path}': {message} (got: {input_value})"

        error_messages.append(formatted_msg)

    error_messages.append("\n")
    return "\n".join(error_messages)

_get_cfn_logical_id(resource_type_suffix=None, git_branch=None, target_env=None)

Generate a CloudFormation logical ID for the resource.

Parameters:

Name Type Description Default
resource_type_suffix str

Additional suffix to append to the resource type for uniqueness

None
git_branch str

Git branch name to include in the logical ID

None
target_env str

Target environment name to include in the logical ID

None

Returns:

Name Type Description
str str

CloudFormation-compliant logical ID for the resource

Source code in mare_aws_common_lib/builders/abstract_aws_resource_builder.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def _get_cfn_logical_id(self, resource_type_suffix: str = None, git_branch: str = None, target_env: str = None) -> str:
    """
    Generate a CloudFormation logical ID for the resource.

    Args:
        resource_type_suffix (str, optional): Additional suffix to append
            to the resource type for uniqueness
        git_branch (str, optional): Git branch name to include
            in the logical ID
        target_env (str, optional): Target environment name to include
            in the logical ID

    Returns:
        str: CloudFormation-compliant logical ID for the resource
    """
    return ResourceNaming.get_cfn_logical_id(self._application_helper, self._resource_type, self._usage, 
                                             resource_type_suffix, git_branch, target_env)

_get_name_for_resource(resource_name=None, git_branch=None, max_length=None)

Generate a properly formatted name for the AWS resource.

Uses the ResourceNaming utility to create names that follow AWS naming conventions and organizational standards. If the name is truncated due to length limits, the original name is stored as a tag.

Parameters:

Name Type Description Default
resource_name str

Base name for the resource

None
git_branch str

CodeCommit branch name to include

None
max_length int

Maximum length constraint for the name

None

Returns:

Name Type Description
str str

The formatted resource name ready for use in AWS

Source code in mare_aws_common_lib/builders/abstract_aws_resource_builder.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def _get_name_for_resource(self, resource_name: str = None, git_branch: str = None, max_length: int = None) -> str:
    """
    Generate a properly formatted name for the AWS resource.

    Uses the ResourceNaming utility to create names that follow AWS naming
    conventions and organizational standards. If the name is truncated due
    to length limits, the original name is stored as a tag.

    Args:
        resource_name (str, optional): Base name for the resource
        git_branch (str, optional): CodeCommit branch name to include
        max_length (int, optional): Maximum length constraint for the name

    Returns:
        str: The formatted resource name ready for use in AWS
    """
    full_name, original_name = ResourceNaming.get_name_for_resource(self._application_helper, self._resource_type, self._usage, 
                                         resource_name, git_branch, max_length)
    if original_name is not None:
        self._tags[full_name] = original_name

    return full_name

_get_snc_key_by_alias(scope, from_foundation=False, key_id_suffix=None)

Retrieve an organizational KMS key for Sensitive Non Classified (SNC) data encryption.

Constructs the standardized KMS key alias following organizational naming conventions and retrieves the existing key for resource encryption. The key alias follows the pattern: alias/{domain}[-foundation]-{project}-{environment}-{resource_type}-snc-key

Parameters:

Name Type Description Default
scope Construct

CDK construct scope for the key lookup

required
from_foundation bool

Whether to use the foundation-provided key instead of a project-specific key. Defaults to False.

False
key_id_suffix str

Additional suffix to append to the key ID for disambiguation when multiple keys share the same alias pattern. Defaults to None.

None

Returns:

Type Description
Key

kms.Key: KMS Key instance configured for SNC data encryption

Note

The method includes debug print statements for key_alias and key_id which should be removed in production code.

Source code in mare_aws_common_lib/builders/abstract_aws_resource_builder.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def _get_snc_key_by_alias(self, scope: Construct, from_foundation: bool = False, key_id_suffix: str = None) -> kms.Key:
    """
    Retrieve an organizational KMS key for Sensitive Non Classified (SNC) data encryption.

    Constructs the standardized KMS key alias following organizational naming
    conventions and retrieves the existing key for resource encryption.
    The key alias follows the pattern:
    alias/{domain}[-foundation]-{project}-{environment}-{resource_type}-snc-key

    Args:
        scope (Construct): CDK construct scope for the key lookup
        from_foundation (bool, optional): Whether to use the foundation-provided key
            instead of a project-specific key. Defaults to False.
        key_id_suffix (str, optional): Additional suffix to append to the key ID
            for disambiguation when multiple keys share the same alias pattern.
            Defaults to None.

    Returns:
        kms.Key: KMS Key instance configured for SNC data encryption

    Note:
        The method includes debug print statements for key_alias and key_id
        which should be removed in production code.
    """
    # Build key alias
    key_parts = [f"alias/{self._application_helper.get_domain()}"]
    if from_foundation:
        key_parts.append("foundation")
    key_parts.extend([
        self._application_helper.get_project(),
        self._application_helper.get_target_env(),
        self._resource_type.value,
        "snc-key"
    ])
    key_alias = "-".join(key_parts).lower()
    key_id = key_alias
    if key_id_suffix is not None:
        key_id = f"{key_alias}/{key_id_suffix}"

    return kms.Key.from_lookup(scope, key_id.replace("-"," ").title().replace(" ", ""), alias_name=key_alias)

_log_validation_error(error, model)

Log a formatted validation error to the logger.

Convenience method that formats a validation error and logs it at ERROR level with the model name for context.

Parameters:

Name Type Description Default
error ValidationError

The validation error that occurred

required
model BaseModel

The Pydantic model that failed validation

required
Source code in mare_aws_common_lib/builders/abstract_aws_resource_builder.py
302
303
304
305
306
307
308
309
310
311
312
313
314
def _log_validation_error(self, error: ValidationError, model: BaseModel) -> None:
    """
    Log a formatted validation error to the logger.

    Convenience method that formats a validation error and logs it
    at ERROR level with the model name for context.

    Args:
        error (ValidationError): The validation error that occurred
        model (BaseModel): The Pydantic model that failed validation
    """
    error_msg = self._format_validation_error(error)
    logging.error(f"❌ {model.__name__} validation failed!\n{error_msg}")

_set_config() abstractmethod

Parse and validate the builder configuration into a typed config object.

This method should take the raw configuration from _builder_config and convert it into a validated Pydantic model instance stored in _config. Must be implemented by subclasses to handle their specific configuration schema.

Raises:

Type Description
ValidationError

If the configuration is invalid according to the Pydantic model schema

Source code in mare_aws_common_lib/builders/abstract_aws_resource_builder.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
@abstractmethod
def _set_config(self) -> None:
    """
    Parse and validate the builder configuration into a typed config object.

    This method should take the raw configuration from _builder_config
    and convert it into a validated Pydantic model instance stored in _config.
    Must be implemented by subclasses to handle their specific configuration
    schema.

    Raises:
        ValidationError: If the configuration is invalid according to the
            Pydantic model schema
    """
    pass

_setup_logger()

Setup a clean logger for builder operations.

Creates a logger with the builder's class name and configures it with a simple message-only format. Sets logging level to ERROR to reduce noise during normal operations.

Source code in mare_aws_common_lib/builders/abstract_aws_resource_builder.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def _setup_logger(self) -> None:
    """
    Setup a clean logger for builder operations.

    Creates a logger with the builder's class name and configures it
    with a simple message-only format. Sets logging level to ERROR
    to reduce noise during normal operations.
    """
    self.logger = logging.getLogger(TBuilder.__name__)

    if not self.logger.handlers:
        handler = logging.StreamHandler()
        formatter = logging.Formatter('%(message)s')
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)
        self.logger.setLevel(logging.ERROR)
        self.logger.propagate = False

_tag_resource(resource)

Apply accumulated tags to the specified AWS resource.

Adds all tags that have been collected during the build process (such as original names before truncation) to the resource. Clears the internal tag collection after application.

Parameters:

Name Type Description Default
resource Construct

The AWS CDK construct to tag

required
Source code in mare_aws_common_lib/builders/abstract_aws_resource_builder.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def _tag_resource(self, resource: Construct) -> None:
    """
    Apply accumulated tags to the specified AWS resource.

    Adds all tags that have been collected during the build process
    (such as original names before truncation) to the resource.
    Clears the internal tag collection after application.

    Args:
        resource (Construct): The AWS CDK construct to tag
    """
    if self._tags:
        for key, value in self._tags.items():
            Tags.of(resource).add(key, value)
        self._tags = {}

build() abstractmethod

Build and return the configured AWS resource.

This is the main method that creates the actual AWS resource based on the accumulated configuration. Must be implemented by subclasses to handle their specific resource creation logic.

Returns:

Name Type Description
Any Any

The created AWS resource (type depends on the specific builder)

Raises:

Type Description
ValueError

If required configuration is missing or invalid

ValidationError

If the configuration fails validation

Source code in mare_aws_common_lib/builders/abstract_aws_resource_builder.py
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
@abstractmethod
def build(self) -> Any:
    """
    Build and return the configured AWS resource.

    This is the main method that creates the actual AWS resource based on
    the accumulated configuration. Must be implemented by subclasses to
    handle their specific resource creation logic.

    Returns:
        Any: The created AWS resource (type depends on the specific builder)

    Raises:
        ValueError: If required configuration is missing or invalid
        ValidationError: If the configuration fails validation
    """
    self._control_consistency()

reset() abstractmethod

Reset the builder to its initial state.

Clears all configuration, helper references, tags, and other internal state. This method must be implemented by subclasses to handle any additional state they maintain.

Note

This is called during initialization and can be called manually to reuse a builder instance for multiple resources.

Source code in mare_aws_common_lib/builders/abstract_aws_resource_builder.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
@abstractmethod
def reset(self) -> None:
    """
    Reset the builder to its initial state.

    Clears all configuration, helper references, tags, and other internal
    state. This method must be implemented by subclasses to handle any
    additional state they maintain.

    Note:
        This is called during initialization and can be called manually
        to reuse a builder instance for multiple resources.
    """
    self._application_helper: ApplicationHelper = None
    self._builder_config: Dict[str, Any] = {}
    self._usage: Usage = None
    self._tags: Dict[str, str] = {}
    self._config: TConfig = None

set_application_helper(app_helper)

Set the application helper for resource naming and configuration.

Parameters:

Name Type Description Default
app_helper ApplicationHelper

Helper instance containing application context and configuration needed for resource creation

required

Returns:

Name Type Description
TBuilder TBuilder

Self reference for method chaining

Source code in mare_aws_common_lib/builders/abstract_aws_resource_builder.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def set_application_helper(self, app_helper: ApplicationHelper) -> TBuilder:
    """
    Set the application helper for resource naming and configuration.

    Args:
        app_helper (ApplicationHelper): Helper instance containing application
            context and configuration needed for resource creation

    Returns:
        TBuilder: Self reference for method chaining
    """
    self._application_helper = app_helper
    return self

set_builder_config(config)

Set the raw configuration dictionary for the builder.

Parameters:

Name Type Description Default
config Dict[str, Any]

Configuration dictionary containing resource-specific settings

required

Returns:

Name Type Description
TBuilder TBuilder

Self reference for method chaining

Source code in mare_aws_common_lib/builders/abstract_aws_resource_builder.py
102
103
104
105
106
107
108
109
110
111
112
113
114
def set_builder_config(self, config: Dict[str, Any]) -> TBuilder:
    """
    Set the raw configuration dictionary for the builder.

    Args:
        config (Dict[str, Any]): Configuration dictionary containing
            resource-specific settings

    Returns:
        TBuilder: Self reference for method chaining
    """
    self._builder_config = config
    return self

set_usage(usage)

Set the usage context for the resource being built.

Parameters:

Name Type Description Default
usage Usage

Usage enum value indicating the intended use case

required

Returns:

Name Type Description
TBuilder TBuilder

Self reference for method chaining

Source code in mare_aws_common_lib/builders/abstract_aws_resource_builder.py
132
133
134
135
136
137
138
139
140
141
142
143
def set_usage(self, usage: Usage) -> TBuilder:
    """
    Set the usage context for the resource being built.

    Args:
        usage (Usage): Usage enum value indicating the intended use case

    Returns:
        TBuilder: Self reference for method chaining
    """
    self._usage = usage
    return self