Skip to content

AbstractAWSResourceBuilder

The AbstractAWSResourceBuilder class is the foundational base class for all AWS resource builders in the MARE ecosystem. It implements the builder pattern with generic type safety, providing a consistent interface for creating AWS resources with proper validation, naming conventions, tagging, and organizational compliance. This abstract class ensures all concrete builders follow the same architectural patterns and quality standards.

Dependencies

This abstract builder requires the following components to function properly:

Required Foundation Components

  • ApplicationHelper: Core helper class containing application context, environment configuration, and organizational settings
  • ResourceNaming: Utility class for generating consistent AWS resource names and CloudFormation logical IDs
  • Pydantic Models: Type-safe configuration models that extend BaseModel for validation
  • SNC KMS Keys: Organizational KMS keys for Sensitive Non Classified data encryption (when using SNC functionality)

AWS Permissions Required

  • Resource creation permissions (specific to each concrete implementation)
  • Resource tagging permissions
  • CloudFormation logical ID generation access
  • KMS Key lookup permissions for SNC encryption (when using _get_snc_key_by_alias)

Architecture Overview

The builder uses a generic type system with two type parameters:

  • TBuilder: The concrete builder type that inherits from this class (enables fluent interface)
  • TConfig: The Pydantic model type used for configuration validation

Class Attributes

All concrete builders must define the following class attributes:

Attribute Type Description
_resource_type AWSResourceType Enum value identifying the AWS resource type being built
_requires_builder_config bool Whether configuration is mandatory (default: True)
_requires_usage bool Whether usage context is mandatory (default: False)

Configuration

Concrete builders should define their own Pydantic configuration models that extend BaseModel. The abstract builder handles the validation lifecycle but delegates specific schema definition to implementations.

Internal State Management

The builder maintains the following internal state:

Property Type Description
_application_helper ApplicationHelper Application context and configuration
_builder_config Dict[str, Any] Raw configuration dictionary
_usage Usage Usage context (prod, dev, test, etc.)
_tags Dict[str, str] Accumulated tags for resource application
_config TConfig Validated configuration model instance

Configuration Validation

The builder provides robust validation with detailed error reporting:

  • Type Safety: Uses Pydantic models for compile-time and runtime type checking
  • Error Formatting: Converts validation errors into human-readable messages
  • Consistency Checks: Validates required dependencies before building

Resource Naming

Automatic naming follows organizational standards:

  • CloudFormation IDs: Generated via _get_cfn_logical_id()
  • Resource Names: Created via _get_name_for_resource() with truncation handling
  • Tag Preservation: Original names stored as tags when truncated

Tagging System

Automatic tagging capabilities:

  • Name Preservation: Original names added as tags when truncated
  • Bulk Application: All accumulated tags applied via _tag_resource()
  • Cleanup: Tag collection cleared after application

Logging Integration

Built-in logging with clean formatting:

  • Error Level: Focused on validation failures and critical issues
  • Clean Output: Message-only format without timestamps or levels
  • Validation Errors: Structured error reporting with field paths and context

SNC Key Management

Built-in support for Sensitive Non Classified (SNC) encryption:

  • Key Lookup: Automatic retrieval of organizational KMS keys via _get_snc_key_by_alias
  • Naming Convention: Standardized alias pattern for consistent key management
  • Foundation Support: Option to use foundation-provided keys vs project-specific keys

SNC Key Naming Pattern:

  • Project-specific: alias/{domain}-{project}-{environment}-{resource_type}-snc-key
  • Foundation-provided: alias/{domain}-foundation-{project}-{environment}-{resource_type}-snc-key

Abstract Methods Implementation Guide

Required Abstract Methods

Concrete builders must implement these methods:

reset(self) -> None

Reset all builder state to initial values. Always call super().reset() first:

def reset(self) -> None:
    super().reset()
    # Reset your specific properties
    self._your_property = None

_set_config(self) -> None

Parse and validate raw configuration into typed model:

def _set_config(self) -> None:
    try:
        self._config = YourConfigModel(**self._builder_config)
    except ValidationError as e:
        self._log_validation_error(e, YourConfigModel)
        raise

build(self) -> Any

Create and return the AWS resource. Always call super().build() first:

def build(self, scope: Construct) -> YourResource:
    super().build()  # Validates consistency
    self._set_config()  # Parse configuration

    # Create your resource
    resource = YourResource(...)
    self._tag_resource(resource)
    return resource

_control_consistency(self) -> None

Validate builder state before resource creation. Call super()._control_consistency() first:

def _control_consistency(self) -> None:
    super()._control_consistency()
    # Add your specific validations
    if self._requires_special_condition and not self._special_property:
        raise ValueError("Special property required for this resource type")

Error Handling

Validation Errors

The builder provides detailed validation error formatting:

  • Field Paths: Clear navigation to problematic fields
  • Type Mismatches: Specific expected vs actual type information
  • Missing Fields: Highlighted required field identification
  • Custom Messages: Clean, actionable error descriptions

Consistency Errors

Common consistency validation errors:

  • Missing Application Helper: ValueError when helper not set
  • Missing Configuration: ValueError when required config not provided
  • Invalid Usage: ValueError when usage type is incorrect
  • Resource-Specific: Custom validations from concrete implementations

Notes

  • Always call parent methods in abstract method implementations to maintain the inheritance chain
  • The _config property is only available after _set_config() is called successfully
  • Resource naming automatically handles AWS character limits and organizational standards
  • The builder can be reused by calling reset() between build operations
  • Type safety is enforced at both compile-time (with proper IDE support) and runtime (via Pydantic)
  • All concrete builders should follow the established patterns for consistency across the codebase
  • SNC key functionality requires proper KMS permissions and existing organizational keys