Skip to content

EcsConfig

Bases: BaseModel, NameValidationMixin, PathValidationMixin

Configuration model for comprehensive ECS service deployment.

Defines the complete infrastructure setup for an ECS Fargate service including Application Load Balancer with SSL termination, ECS cluster and service configuration, container specifications, CloudFront integration, Route53 DNS management, and optional EFS persistent storage mounting for stateful applications.

Enforces AWS Fargate CPU/memory constraints, organizational naming standards, and validates cross-service integration requirements for production deployments.

Attributes:

Name Type Description
alb_name str

Application Load Balancer identifier for naming

alb_domain_prefix str

DNS subdomain prefix for ALB endpoint

service_name str

ECS service identifier for resource naming

cluster_name str

ECS cluster identifier with validation

use_iam_authentication bool

Enable IAM database authentication for applications

ecr_repo_source_env str

Environment name for ECR repository image sourcing

ecr_repo_base_name Optional[str]

Internal ECR repository reference (mutually exclusive with container_repo)

container_repo Optional[str]

External Docker repository URL (mutually exclusive with ecr_repo_base_name)

application_port int

Primary application listening port (1-65535)

admin_port Optional[int]

Administrative interface port (conditional on admin_active)

admin_active bool

Enable administrative interface and related infrastructure

health_check_path Optional[str]

Application health check endpoint path

health_check_cmd Optional[str]

Container-level health check command override

cpu int

Fargate CPU units allocation (256, 512, 1024, 2048, 4096)

memory_limit_mib int

Fargate memory allocation in MiB (varies by CPU)

desired_count int

Target number of running task instances (0-10)

ssl_certificate_id str

ACM certificate identifier for HTTPS termination

eu_west_cloudront_prefix_list_id str

CloudFront prefix list for EU traffic routing

route53 Route53Config

DNS configuration and domain management

parameters AppParametersConfig

Container environment variables and secrets configuration

efs_config Optional[EcsEfsConfig]

Optional EFS persistent storage configuration

Source code in mare_aws_common_lib/models/ecs_config.py
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
class EcsConfig(BaseModel, NameValidationMixin, PathValidationMixin):
    """Configuration model for comprehensive ECS service deployment.

    Defines the complete infrastructure setup for an ECS Fargate service including
    Application Load Balancer with SSL termination, ECS cluster and service configuration,
    container specifications, CloudFront integration, Route53 DNS management, and
    optional EFS persistent storage mounting for stateful applications.

    Enforces AWS Fargate CPU/memory constraints, organizational naming standards,
    and validates cross-service integration requirements for production deployments.

    Attributes:
        alb_name: Application Load Balancer identifier for naming
        alb_domain_prefix: DNS subdomain prefix for ALB endpoint
        service_name: ECS service identifier for resource naming
        cluster_name: ECS cluster identifier with validation
        use_iam_authentication: Enable IAM database authentication for applications
        ecr_repo_source_env: Environment name for ECR repository image sourcing
        ecr_repo_base_name: Internal ECR repository reference (mutually exclusive with container_repo)
        container_repo: External Docker repository URL (mutually exclusive with ecr_repo_base_name)
        application_port: Primary application listening port (1-65535)
        admin_port: Administrative interface port (conditional on admin_active)
        admin_active: Enable administrative interface and related infrastructure
        health_check_path: Application health check endpoint path
        health_check_cmd: Container-level health check command override
        cpu: Fargate CPU units allocation (256, 512, 1024, 2048, 4096)
        memory_limit_mib: Fargate memory allocation in MiB (varies by CPU)
        desired_count: Target number of running task instances (0-10)
        ssl_certificate_id: ACM certificate identifier for HTTPS termination
        eu_west_cloudront_prefix_list_id: CloudFront prefix list for EU traffic routing
        route53: DNS configuration and domain management
        parameters: Container environment variables and secrets configuration
        efs_config: Optional EFS persistent storage configuration
    """
    model_config = ConfigDict(extra="forbid")

    # ALB Configuration
    alb_name: str = Field(..., description="Name for the Application Load Balancer")
    alb_domain_prefix: str = Field(..., description="Domain prefix for ALB DNS record")

    # ECS Service Configuration
    service_name: str = Field(..., description="Name for the ECS service")
    cluster_name: str = Field(..., description="Name for the ECS cluster")
    use_iam_authentication: bool = Field(default=False, description="Whether to use IAM RDS authentication for the application")

    # Container Configuration
    ecr_repo_source_env: str = Field(default="devops", description="Environment name for container image retrieval from ECR")
    ecr_repo_base_name: Optional[str] = Field(default=None, description="ECR repository base name")
    container_repo: Optional[str] = Field(None, description="External public docker image repository")
    application_port: int = Field(..., description="Port on which the application listens on")
    admin_port: Optional[int] = Field(None, description="Admin port for the application server")
    admin_active: bool = Field(default=False, description="Whether admin functionality of the application server is active")
    health_check_path: Optional[str] = Field(None, description="The path of the application health check endpoint")
    health_check_cmd: Optional[str] = Field(None, description="The base cmd to be run at the container level for the application health check")

    # Task Definition Configuration
    cpu: int = Field(..., description="CPU units for the task")
    memory_limit_mib: int = Field(..., description="Memory limit in MiB")
    desired_count: int = Field(default=1, description="The desired number of instantiations of the task definition to keep running on the service")

    # SSL Configuration
    ssl_certificate_id: str = Field(..., description="SSL certificate ID for HTTPS")

    # CloudFront Configuration
    eu_west_cloudront_prefix_list_id: str = Field(..., description="CloudFront prefix list ID for EU West region")

    # Route53 Configuration
    route53: Route53Config = Field(..., description="Route 53 configuration for domain setup")

    # App Parameters Configuraion
    parameters: AppParametersConfig = Field(..., description="Application parameters for the container definition")

    # Environment Files Configuration
    environment_files: Optional[List[EnvironmentFileConfig]] = Field(
        default=None, 
        description="S3 environment files to load into containers at startup"
    )

    # EFS Configuration
    efs_config: Optional[EcsEfsConfig] = Field(default=None, description="EFS configuration for the ECS service")

    @field_validator("alb_name", "service_name")
    @classmethod
    def validate_resource_names(cls, value: str) -> str:
        """Validate ALB and ECS service names against organizational standards.

        Ensures that Application Load Balancer and ECS service names conform to
        AWS resource naming requirements and organizational naming conventions.
        This validation prevents deployment failures due to invalid characters,
        length constraints, or format violations.

        Args:
            value: Raw resource name from configuration

        Returns:
            Validated resource name conforming to naming standards

        Raises:
            ValueError: If the name contains invalid characters, exceeds length
                    limits, or violates organizational naming patterns
        """
        return cls.validate_name(value)

    @field_validator("ecr_repo_base_name")
    @classmethod
    def validate_ecr_repo_name(cls, value: str) -> str:
        """Validate ECR repository base name format and constraints.

        Ensures ECR repository names comply with AWS ECR naming requirements
        including character restrictions, length limits, and format patterns.
        Only validates when a value is provided since this field is optional.

        Args:
            value: ECR repository base name or None

        Returns:
            Validated repository name or None if not provided

        Raises:
            ValueError: If repository name contains invalid characters or
                    violates ECR naming conventions
        """
        if value is not None:
            return cls.validate_name(value)
        return value

    @field_validator("alb_domain_prefix")
    @classmethod
    def validate_domain_prefix(cls, value: str) -> str:
        """Validate ALB domain prefix for DNS compatibility.

        Ensures the domain prefix follows DNS naming standards and organizational
        conventions for subdomain creation. This prefix will be combined with the
        base domain name to create the full FQDN for the Application Load Balancer.

        Args:
            value: Domain prefix string for ALB DNS record

        Returns:
            Validated domain prefix suitable for DNS record creation

        Raises:
            ValueError: If prefix contains invalid DNS characters, starts/ends
                    with invalid characters, or violates domain naming rules
        """
        return cls.validate_name(value)

    @field_validator("application_port", "admin_port")
    @classmethod
    def validate_ports(cls, value: int) -> int:
        """Validate network port numbers for application and admin interfaces.

        Ensures port numbers fall within the valid TCP/UDP port range and
        are suitable for containerized application deployment. Validates both
        application and admin ports using the same constraints.

        Args:
            value: Port number for application or admin interface

        Returns:
            Validated port number within acceptable range

        Raises:
            ValueError: If port number is outside valid range (1-65535)
                    or conflicts with reserved system ports
        """
        if value is not None:
            if not 1 <= value <= 65535:
                raise ValueError(f"Port {value} must be between 1 and 65535")
        return value

    @field_validator("desired_count")
    @classmethod
    def validate_desired_count(cls, value: int) -> int:
        """Validate ECS service desired count for reasonable deployment sizing.

        Ensures the desired count of running tasks is within reasonable bounds
        for typical ECS deployments. Prevents accidental over-provisioning while
        allowing for legitimate high-availability configurations.

        Args:
            value: Target number of running task instances

        Returns:
            Validated desired count within acceptable range

        Raises:
            ValueError: If desired count is negative or unreasonably high
        """
        if value < 0:
            raise ValueError("desired_count must be non-negative")
        if value > 10:  # Reasonable upper limit/
            raise ValueError("desired_count seems unusually high, please verify")
        return value

    @field_validator("health_check_path")
    @classmethod
    def validate_health_check_path(cls, value: str) -> str:
        """Validate the health check path.

        Ensures the health check path follows proper URL path formatting
        and organizational standards for service health endpoints.

        Args:
            value: Raw health check path from configuration

        Returns:
            Validated health check path

        Raises:
            ValueError: If the health check path fails validation rules
        """
        return cls.validate_path_pattern(value)

    @field_validator("cluster_name")
    @classmethod
    def validate_cluster_name(cls, value: str) -> str:
        """Validate the ECS cluster name.

        Applies organizational naming standards to ECS cluster names to ensure
        consistency and compliance with AWS resource naming requirements.

        Args:
            value: Raw cluster name from configuration

        Returns:
            Validated cluster name

        Raises:
            ValueError: If the cluster name fails validation rules
        """
        return cls.validate_name(value)

    @model_validator(mode="after")
    def validate_container_repo_exclusivity(self) -> 'EcsConfig':
        """Validate that container_repo and ecr_repo_base_name are mutually exclusive.

        Ensures that only one container image source is specified to prevent
        conflicting image repository configurations. When container_repo is specified,
        ecr_repo_base_name must not be provided, and vice versa. Applications should use
        either an external public Docker repository or an internal ECR repository,
        but not both simultaneously.

        Returns:
            Self after validation

        Raises:
            ValueError: If both container_repo and ecr_repo_base_name are specified
        """
        if self.container_repo is not None and self.ecr_repo_base_name is not None:
            raise ValueError(
                "Cannot specify both 'container_repo' and 'ecr_repo_base_name'. "
                "Choose either an external Docker repository or an ECR repository."
            )
        return self

    @model_validator(mode="after")
    def validate_admin_config(self) -> 'EcsConfig':
        """Validate administrative interface configuration consistency.

        Ensures that when administrative functionality is enabled, the required
        admin port is specified to prevent incomplete administrative setup.

        Returns:
            Self after validation

        Raises:
            ValueError: If admin is active but no admin port is specified
        """
        if self.admin_active and self.admin_port is None:
            raise ValueError("'admin_port' must be set when 'admin_active' is True.")
        return self

    @model_validator(mode="after")
    def validate_cpu_memory_combination(self) -> 'EcsConfig':
        """Validate CPU and memory allocation against AWS Fargate constraints.

        Enforces AWS Fargate's specific CPU/memory combination requirements to
        prevent deployment failures due to unsupported resource configurations.
        Validates against the official Fargate task sizing matrix.

        Returns:
            Self after validation

        Raises:
            ValueError: If CPU/memory combination is not supported by AWS Fargate
        """
        allowed_combinations = {
            256: [512, 1024, 2048],
            512: [1024, 2048, 3072, 4096],
            1024: list(range(2048, 8193, 1024)),
            2048: list(range(4096, 16385, 1024)),
            4096: list(range(8192, 30721, 1024)),
        }

        if self.cpu not in allowed_combinations:
            raise ValueError(f"invalid CPU value: {self.cpu}. Must be one of: {list(allowed_combinations.keys())}")

        if self.memory_limit_mib not in allowed_combinations[self.cpu]:
            raise ValueError(
                f"invalid memory value {self.memory_limit_mib} for CPU {self.cpu}. "
                f"Must be one of: {allowed_combinations[self.cpu]}"
            )
        return self

    @model_validator(mode="after")
    def validate_efs_volume_references(self) -> 'EcsConfig':
        """Validate referential integrity between EFS volumes and container mount points.

        Ensures that all container mount points reference existing EFS volume definitions
        within the same configuration, preventing runtime errors during ECS task startup.
        This validation enforces a consistent mapping between volume definitions and
        their usage in container mount specifications.

        Returns:
            Self with validated EFS volume-to-mount-point relationships

        Raises:
            ValueError: When a mount point references a non-existent volume name.
                    The error message includes:
                    - The problematic volume name that was referenced
                    - A sorted list of all available volume names for easy correction
        """
        if self.efs_config:
            volume_names = {vol.volume_name for vol in self.efs_config.volumes}
            for mount_point in self.efs_config.mount_points:
                if mount_point.volume_name not in volume_names:
                    raise ValueError(f"Mount point references unknown volume '{mount_point.volume_name}'. Available volumes: {sorted(volume_names)}")
        return self

validate_admin_config()

Validate administrative interface configuration consistency.

Ensures that when administrative functionality is enabled, the required admin port is specified to prevent incomplete administrative setup.

Returns:

Type Description
EcsConfig

Self after validation

Raises:

Type Description
ValueError

If admin is active but no admin port is specified

Source code in mare_aws_common_lib/models/ecs_config.py
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
@model_validator(mode="after")
def validate_admin_config(self) -> 'EcsConfig':
    """Validate administrative interface configuration consistency.

    Ensures that when administrative functionality is enabled, the required
    admin port is specified to prevent incomplete administrative setup.

    Returns:
        Self after validation

    Raises:
        ValueError: If admin is active but no admin port is specified
    """
    if self.admin_active and self.admin_port is None:
        raise ValueError("'admin_port' must be set when 'admin_active' is True.")
    return self

validate_cluster_name(value) classmethod

Validate the ECS cluster name.

Applies organizational naming standards to ECS cluster names to ensure consistency and compliance with AWS resource naming requirements.

Parameters:

Name Type Description Default
value str

Raw cluster name from configuration

required

Returns:

Type Description
str

Validated cluster name

Raises:

Type Description
ValueError

If the cluster name fails validation rules

Source code in mare_aws_common_lib/models/ecs_config.py
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
@field_validator("cluster_name")
@classmethod
def validate_cluster_name(cls, value: str) -> str:
    """Validate the ECS cluster name.

    Applies organizational naming standards to ECS cluster names to ensure
    consistency and compliance with AWS resource naming requirements.

    Args:
        value: Raw cluster name from configuration

    Returns:
        Validated cluster name

    Raises:
        ValueError: If the cluster name fails validation rules
    """
    return cls.validate_name(value)

validate_container_repo_exclusivity()

Validate that container_repo and ecr_repo_base_name are mutually exclusive.

Ensures that only one container image source is specified to prevent conflicting image repository configurations. When container_repo is specified, ecr_repo_base_name must not be provided, and vice versa. Applications should use either an external public Docker repository or an internal ECR repository, but not both simultaneously.

Returns:

Type Description
EcsConfig

Self after validation

Raises:

Type Description
ValueError

If both container_repo and ecr_repo_base_name are specified

Source code in mare_aws_common_lib/models/ecs_config.py
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
@model_validator(mode="after")
def validate_container_repo_exclusivity(self) -> 'EcsConfig':
    """Validate that container_repo and ecr_repo_base_name are mutually exclusive.

    Ensures that only one container image source is specified to prevent
    conflicting image repository configurations. When container_repo is specified,
    ecr_repo_base_name must not be provided, and vice versa. Applications should use
    either an external public Docker repository or an internal ECR repository,
    but not both simultaneously.

    Returns:
        Self after validation

    Raises:
        ValueError: If both container_repo and ecr_repo_base_name are specified
    """
    if self.container_repo is not None and self.ecr_repo_base_name is not None:
        raise ValueError(
            "Cannot specify both 'container_repo' and 'ecr_repo_base_name'. "
            "Choose either an external Docker repository or an ECR repository."
        )
    return self

validate_cpu_memory_combination()

Validate CPU and memory allocation against AWS Fargate constraints.

Enforces AWS Fargate's specific CPU/memory combination requirements to prevent deployment failures due to unsupported resource configurations. Validates against the official Fargate task sizing matrix.

Returns:

Type Description
EcsConfig

Self after validation

Raises:

Type Description
ValueError

If CPU/memory combination is not supported by AWS Fargate

Source code in mare_aws_common_lib/models/ecs_config.py
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
@model_validator(mode="after")
def validate_cpu_memory_combination(self) -> 'EcsConfig':
    """Validate CPU and memory allocation against AWS Fargate constraints.

    Enforces AWS Fargate's specific CPU/memory combination requirements to
    prevent deployment failures due to unsupported resource configurations.
    Validates against the official Fargate task sizing matrix.

    Returns:
        Self after validation

    Raises:
        ValueError: If CPU/memory combination is not supported by AWS Fargate
    """
    allowed_combinations = {
        256: [512, 1024, 2048],
        512: [1024, 2048, 3072, 4096],
        1024: list(range(2048, 8193, 1024)),
        2048: list(range(4096, 16385, 1024)),
        4096: list(range(8192, 30721, 1024)),
    }

    if self.cpu not in allowed_combinations:
        raise ValueError(f"invalid CPU value: {self.cpu}. Must be one of: {list(allowed_combinations.keys())}")

    if self.memory_limit_mib not in allowed_combinations[self.cpu]:
        raise ValueError(
            f"invalid memory value {self.memory_limit_mib} for CPU {self.cpu}. "
            f"Must be one of: {allowed_combinations[self.cpu]}"
        )
    return self

validate_desired_count(value) classmethod

Validate ECS service desired count for reasonable deployment sizing.

Ensures the desired count of running tasks is within reasonable bounds for typical ECS deployments. Prevents accidental over-provisioning while allowing for legitimate high-availability configurations.

Parameters:

Name Type Description Default
value int

Target number of running task instances

required

Returns:

Type Description
int

Validated desired count within acceptable range

Raises:

Type Description
ValueError

If desired count is negative or unreasonably high

Source code in mare_aws_common_lib/models/ecs_config.py
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
@field_validator("desired_count")
@classmethod
def validate_desired_count(cls, value: int) -> int:
    """Validate ECS service desired count for reasonable deployment sizing.

    Ensures the desired count of running tasks is within reasonable bounds
    for typical ECS deployments. Prevents accidental over-provisioning while
    allowing for legitimate high-availability configurations.

    Args:
        value: Target number of running task instances

    Returns:
        Validated desired count within acceptable range

    Raises:
        ValueError: If desired count is negative or unreasonably high
    """
    if value < 0:
        raise ValueError("desired_count must be non-negative")
    if value > 10:  # Reasonable upper limit/
        raise ValueError("desired_count seems unusually high, please verify")
    return value

validate_domain_prefix(value) classmethod

Validate ALB domain prefix for DNS compatibility.

Ensures the domain prefix follows DNS naming standards and organizational conventions for subdomain creation. This prefix will be combined with the base domain name to create the full FQDN for the Application Load Balancer.

Parameters:

Name Type Description Default
value str

Domain prefix string for ALB DNS record

required

Returns:

Type Description
str

Validated domain prefix suitable for DNS record creation

Raises:

Type Description
ValueError

If prefix contains invalid DNS characters, starts/ends with invalid characters, or violates domain naming rules

Source code in mare_aws_common_lib/models/ecs_config.py
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
@field_validator("alb_domain_prefix")
@classmethod
def validate_domain_prefix(cls, value: str) -> str:
    """Validate ALB domain prefix for DNS compatibility.

    Ensures the domain prefix follows DNS naming standards and organizational
    conventions for subdomain creation. This prefix will be combined with the
    base domain name to create the full FQDN for the Application Load Balancer.

    Args:
        value: Domain prefix string for ALB DNS record

    Returns:
        Validated domain prefix suitable for DNS record creation

    Raises:
        ValueError: If prefix contains invalid DNS characters, starts/ends
                with invalid characters, or violates domain naming rules
    """
    return cls.validate_name(value)

validate_ecr_repo_name(value) classmethod

Validate ECR repository base name format and constraints.

Ensures ECR repository names comply with AWS ECR naming requirements including character restrictions, length limits, and format patterns. Only validates when a value is provided since this field is optional.

Parameters:

Name Type Description Default
value str

ECR repository base name or None

required

Returns:

Type Description
str

Validated repository name or None if not provided

Raises:

Type Description
ValueError

If repository name contains invalid characters or violates ECR naming conventions

Source code in mare_aws_common_lib/models/ecs_config.py
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
@field_validator("ecr_repo_base_name")
@classmethod
def validate_ecr_repo_name(cls, value: str) -> str:
    """Validate ECR repository base name format and constraints.

    Ensures ECR repository names comply with AWS ECR naming requirements
    including character restrictions, length limits, and format patterns.
    Only validates when a value is provided since this field is optional.

    Args:
        value: ECR repository base name or None

    Returns:
        Validated repository name or None if not provided

    Raises:
        ValueError: If repository name contains invalid characters or
                violates ECR naming conventions
    """
    if value is not None:
        return cls.validate_name(value)
    return value

validate_efs_volume_references()

Validate referential integrity between EFS volumes and container mount points.

Ensures that all container mount points reference existing EFS volume definitions within the same configuration, preventing runtime errors during ECS task startup. This validation enforces a consistent mapping between volume definitions and their usage in container mount specifications.

Returns:

Type Description
EcsConfig

Self with validated EFS volume-to-mount-point relationships

Raises:

Type Description
ValueError

When a mount point references a non-existent volume name. The error message includes: - The problematic volume name that was referenced - A sorted list of all available volume names for easy correction

Source code in mare_aws_common_lib/models/ecs_config.py
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
@model_validator(mode="after")
def validate_efs_volume_references(self) -> 'EcsConfig':
    """Validate referential integrity between EFS volumes and container mount points.

    Ensures that all container mount points reference existing EFS volume definitions
    within the same configuration, preventing runtime errors during ECS task startup.
    This validation enforces a consistent mapping between volume definitions and
    their usage in container mount specifications.

    Returns:
        Self with validated EFS volume-to-mount-point relationships

    Raises:
        ValueError: When a mount point references a non-existent volume name.
                The error message includes:
                - The problematic volume name that was referenced
                - A sorted list of all available volume names for easy correction
    """
    if self.efs_config:
        volume_names = {vol.volume_name for vol in self.efs_config.volumes}
        for mount_point in self.efs_config.mount_points:
            if mount_point.volume_name not in volume_names:
                raise ValueError(f"Mount point references unknown volume '{mount_point.volume_name}'. Available volumes: {sorted(volume_names)}")
    return self

validate_health_check_path(value) classmethod

Validate the health check path.

Ensures the health check path follows proper URL path formatting and organizational standards for service health endpoints.

Parameters:

Name Type Description Default
value str

Raw health check path from configuration

required

Returns:

Type Description
str

Validated health check path

Raises:

Type Description
ValueError

If the health check path fails validation rules

Source code in mare_aws_common_lib/models/ecs_config.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
@field_validator("health_check_path")
@classmethod
def validate_health_check_path(cls, value: str) -> str:
    """Validate the health check path.

    Ensures the health check path follows proper URL path formatting
    and organizational standards for service health endpoints.

    Args:
        value: Raw health check path from configuration

    Returns:
        Validated health check path

    Raises:
        ValueError: If the health check path fails validation rules
    """
    return cls.validate_path_pattern(value)

validate_ports(value) classmethod

Validate network port numbers for application and admin interfaces.

Ensures port numbers fall within the valid TCP/UDP port range and are suitable for containerized application deployment. Validates both application and admin ports using the same constraints.

Parameters:

Name Type Description Default
value int

Port number for application or admin interface

required

Returns:

Type Description
int

Validated port number within acceptable range

Raises:

Type Description
ValueError

If port number is outside valid range (1-65535) or conflicts with reserved system ports

Source code in mare_aws_common_lib/models/ecs_config.py
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
@field_validator("application_port", "admin_port")
@classmethod
def validate_ports(cls, value: int) -> int:
    """Validate network port numbers for application and admin interfaces.

    Ensures port numbers fall within the valid TCP/UDP port range and
    are suitable for containerized application deployment. Validates both
    application and admin ports using the same constraints.

    Args:
        value: Port number for application or admin interface

    Returns:
        Validated port number within acceptable range

    Raises:
        ValueError: If port number is outside valid range (1-65535)
                or conflicts with reserved system ports
    """
    if value is not None:
        if not 1 <= value <= 65535:
            raise ValueError(f"Port {value} must be between 1 and 65535")
    return value

validate_resource_names(value) classmethod

Validate ALB and ECS service names against organizational standards.

Ensures that Application Load Balancer and ECS service names conform to AWS resource naming requirements and organizational naming conventions. This validation prevents deployment failures due to invalid characters, length constraints, or format violations.

Parameters:

Name Type Description Default
value str

Raw resource name from configuration

required

Returns:

Type Description
str

Validated resource name conforming to naming standards

Raises:

Type Description
ValueError

If the name contains invalid characters, exceeds length limits, or violates organizational naming patterns

Source code in mare_aws_common_lib/models/ecs_config.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
@field_validator("alb_name", "service_name")
@classmethod
def validate_resource_names(cls, value: str) -> str:
    """Validate ALB and ECS service names against organizational standards.

    Ensures that Application Load Balancer and ECS service names conform to
    AWS resource naming requirements and organizational naming conventions.
    This validation prevents deployment failures due to invalid characters,
    length constraints, or format violations.

    Args:
        value: Raw resource name from configuration

    Returns:
        Validated resource name conforming to naming standards

    Raises:
        ValueError: If the name contains invalid characters, exceeds length
                limits, or violates organizational naming patterns
    """
    return cls.validate_name(value)
Example
from mare_aws_common_lib.models import EcsConfig, AppParametersConfig, ContainerSecretConfig, SecretValueFrom, Route53Config

config = EcsConfig(
    # ALB Configuration
    alb_name="my-app-alb",
    alb_domain_prefix="api",

    # ECS Service Configuration
    service_name="my-application-service",
    cluster_name="production-cluster",

    # Container Configuration
    ecr_repo_base_name="my-app",
    application_port=8080,
    admin_port=9090,
    admin_active=True,

    # Task Definition Configuration
    cpu=512,
    memory_limit_mib=1024,
    desired_count=2,

    # SSL Configuration
    ssl_certificate_id="arn:aws:acm:eu-west-1:123456789012:certificate/12345678-1234-1234-1234-123456789012",

    # CloudFront Configuration
    eu_west_cloudront_prefix_list_id="pl-12345678",

    # Route53 Configuration
    route53=Route53Config(
        hosted_zone_id="Z1234567890ABC",
        domain_name="example.com",
        create_alias_record=True
    ),

    # Application Parameters
    parameters=AppParametersConfig(
        environment={
            "NODE_ENV": "production",
            "LOG_LEVEL": "info",
            "PORT": "8080"
        },
        secrets={
            "DATABASE_URL": ContainerSecretConfig(
                value_from=SecretValueFrom.SECRET,
                arn="arn:aws:secretsmanager:eu-west-1:123456789012:secret:db-credentials-AbCdEf"
            ),
            "API_KEY": ContainerSecretConfig(
                value_from=SecretValueFrom.PARAM,
                name="my-app-api-key",
                suffix="PROD"
            )
        }
    )
)

AppParametersConfig

Bases: BaseModel

Configuration model for application runtime parameters.

Encapsulates both environment variables and secrets that need to be injected into ECS containers at runtime, providing a centralized configuration point for application-specific parameters and sensitive data references.

Attributes:

Name Type Description
environment Dict[str, str]

Plain text environment variables as key-value pairs

secrets Dict[str, ContainerSecretConfig]

Secret configurations mapped to environment variable names

Source code in mare_aws_common_lib/models/ecs_config.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
class AppParametersConfig(BaseModel):
    """Configuration model for application runtime parameters.

    Encapsulates both environment variables and secrets that need to be injected
    into ECS containers at runtime, providing a centralized configuration point
    for application-specific parameters and sensitive data references.

    Attributes:
        environment: Plain text environment variables as key-value pairs
        secrets: Secret configurations mapped to environment variable names
    """
    model_config = ConfigDict(extra="forbid")

    environment: Dict[str, str] = Field(default_factory=dict, description="Environment variables for the container")
    secrets: Dict[str, ContainerSecretConfig] = Field(default_factory=dict, description="Secret configurations for the container")
Example
from mare_aws_common_lib.models import AppParametersConfig, ContainerSecretConfig, SecretValueFrom

app_param_config = AppParametersConfig(
    environment={
        "NODE_ENV": "production",
        "LOG_LEVEL": "debug",
        "PORT": "8080",
        "CACHE_TTL": "3600",
        "ENABLE_METRICS": "true"
    },
    secrets={
        # Secret from AWS Secrets Manager
        "DATABASE_URL": ContainerSecretConfig(
            value_from=SecretValueFrom.SECRET,
            arn="arn:aws:secretsmanager:eu-west-1:123456789012:secret:db-credentials-AbCdEf"
        ),
        # Parameter from Systems Manager Parameter Store
        "API_KEY": ContainerSecretConfig(
            value_from=SecretValueFrom.PARAM,
            name="my-app-api-key"
        ),
        # Parameter with suffix for environment variable naming
        "REDIS_PASSWORD": ContainerSecretConfig(
            value_from=SecretValueFrom.PARAM,
            name="redis-password",
            suffix="PROD"
        )
    }
)

ContainerSecretConfig

Bases: BaseModel, NameValidationMixin

Configuration model for container secrets in ECS task definitions.

Defines how secrets are sourced and injected into ECS containers, supporting both AWS Systems Manager Parameter Store and AWS Secrets Manager as sources. Provides flexible naming and ARN-based reference patterns for different secret management workflows.

Attributes:

Name Type Description
value_from SecretValueFrom

Source type for the secret (Parameter Store or Secrets Manager)

name Optional[str]

Parameter name for SSM Parameter Store references

arn Optional[str]

Full ARN for AWS Secrets Manager references

suffix Optional[str]

Optional environment variable name suffix for disambiguation

Source code in mare_aws_common_lib/models/ecs_config.py
18
19
20
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
class ContainerSecretConfig(BaseModel, NameValidationMixin):
    """Configuration model for container secrets in ECS task definitions.

    Defines how secrets are sourced and injected into ECS containers, supporting
    both AWS Systems Manager Parameter Store and AWS Secrets Manager as sources.
    Provides flexible naming and ARN-based reference patterns for different
    secret management workflows.

    Attributes:
        value_from: Source type for the secret (Parameter Store or Secrets Manager)
        name: Parameter name for SSM Parameter Store references
        arn: Full ARN for AWS Secrets Manager references
        suffix: Optional environment variable name suffix for disambiguation
    """
    model_config = ConfigDict(extra="forbid")

    value_from: SecretValueFrom = Field(..., description="The source of the secret: 'param' or 'secret'")
    name: Optional[str] = Field(None, description="The name of the parameter (for SSM) or secret alias")
    arn: Optional[str] = Field(None, description="The ARN of the secret")
    suffix: Optional[str] = Field(None, description="Optional suffix for the environment variable name")

    @field_validator("name")
    @classmethod
    def validate_parameter_name(cls, value: str) -> str:
        """Validate parameter name format."""
        if value is not None:
            cls.validate_name(value, mode="PARAMETER")
        return value

    @field_validator("arn")
    @classmethod  
    def validate_arn_format(cls, value: str) -> str:
        """Validate ARN format."""
        if value is not None:
            str_value = str(value)
            # Skip validation for CDK tokens
            if "${Token[" in str_value or any(pattern in str_value for pattern in ["Ref", "Fn::", "!Ref"]):
                return value

            if not re.match(r'^arn:aws[a-zA-Z-]*:secretsmanager:[a-z0-9-]+:\d{12}:secret:', value):
                raise ValueError("arn must be a valid AWS Secrets Manager ARN")
        return value

    @model_validator(mode="after")
    def validate_source_fields(self) -> 'ContainerSecretConfig':
        """Validate that required fields match the selected secret source.

        Ensures that Parameter Store secrets have a name field and Secrets Manager
        secrets have an ARN field, preventing misconfigured secret references.

        Returns:
            Self after validation

        Raises:
            ValueError: If required fields are missing for the selected source type
        """
        if self.value_from == SecretValueFrom.PARAM and not self.name:
            raise ValueError("'name' must be provided when 'value_from' is 'param'.")
        if self.value_from == SecretValueFrom.SECRET and not self.arn:
            raise ValueError("'arn' must be provided when 'value_from' is 'secret'.")
        return self

    @model_validator(mode="after")
    def validate_suffix(self) -> 'ContainerSecretConfig':
        """Validate environment variable suffix format.

        Ensures that any provided suffix follows environment variable naming
        conventions with alphanumeric characters and underscores only.

        Returns:
            Self after validation

        Raises:
            ValueError: If suffix contains invalid characters
        """
        if self.suffix and not re.fullmatch(r"[a-zA-Z0-9_]+", self.suffix):
            raise ValueError("suffix must contain only letters, numbers, and underscores.")
        return self

validate_arn_format(value) classmethod

Validate ARN format.

Source code in mare_aws_common_lib/models/ecs_config.py
47
48
49
50
51
52
53
54
55
56
57
58
59
@field_validator("arn")
@classmethod  
def validate_arn_format(cls, value: str) -> str:
    """Validate ARN format."""
    if value is not None:
        str_value = str(value)
        # Skip validation for CDK tokens
        if "${Token[" in str_value or any(pattern in str_value for pattern in ["Ref", "Fn::", "!Ref"]):
            return value

        if not re.match(r'^arn:aws[a-zA-Z-]*:secretsmanager:[a-z0-9-]+:\d{12}:secret:', value):
            raise ValueError("arn must be a valid AWS Secrets Manager ARN")
    return value

validate_parameter_name(value) classmethod

Validate parameter name format.

Source code in mare_aws_common_lib/models/ecs_config.py
39
40
41
42
43
44
45
@field_validator("name")
@classmethod
def validate_parameter_name(cls, value: str) -> str:
    """Validate parameter name format."""
    if value is not None:
        cls.validate_name(value, mode="PARAMETER")
    return value

validate_source_fields()

Validate that required fields match the selected secret source.

Ensures that Parameter Store secrets have a name field and Secrets Manager secrets have an ARN field, preventing misconfigured secret references.

Returns:

Type Description
ContainerSecretConfig

Self after validation

Raises:

Type Description
ValueError

If required fields are missing for the selected source type

Source code in mare_aws_common_lib/models/ecs_config.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@model_validator(mode="after")
def validate_source_fields(self) -> 'ContainerSecretConfig':
    """Validate that required fields match the selected secret source.

    Ensures that Parameter Store secrets have a name field and Secrets Manager
    secrets have an ARN field, preventing misconfigured secret references.

    Returns:
        Self after validation

    Raises:
        ValueError: If required fields are missing for the selected source type
    """
    if self.value_from == SecretValueFrom.PARAM and not self.name:
        raise ValueError("'name' must be provided when 'value_from' is 'param'.")
    if self.value_from == SecretValueFrom.SECRET and not self.arn:
        raise ValueError("'arn' must be provided when 'value_from' is 'secret'.")
    return self

validate_suffix()

Validate environment variable suffix format.

Ensures that any provided suffix follows environment variable naming conventions with alphanumeric characters and underscores only.

Returns:

Type Description
ContainerSecretConfig

Self after validation

Raises:

Type Description
ValueError

If suffix contains invalid characters

Source code in mare_aws_common_lib/models/ecs_config.py
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
@model_validator(mode="after")
def validate_suffix(self) -> 'ContainerSecretConfig':
    """Validate environment variable suffix format.

    Ensures that any provided suffix follows environment variable naming
    conventions with alphanumeric characters and underscores only.

    Returns:
        Self after validation

    Raises:
        ValueError: If suffix contains invalid characters
    """
    if self.suffix and not re.fullmatch(r"[a-zA-Z0-9_]+", self.suffix):
        raise ValueError("suffix must contain only letters, numbers, and underscores.")
    return self
Example
from mare_aws_common_lib.models import ContainerSecretConfig, SecretValueFrom

# Secret from AWS Secrets Manager using ARN
secrets_manager_config = ContainerSecretConfig(
    value_from=SecretValueFrom.SECRET,
    arn="arn:aws:secretsmanager:eu-west-1:123456789012:secret:database-credentials-AbCdEf"
)

# Parameter from Systems Manager Parameter Store using name
parameter_store_config = ContainerSecretConfig(
    value_from=SecretValueFrom.PARAM,
    name="my-app-api-key"
)

# Parameter Store with optional name field (alias)
parameter_with_alias = ContainerSecretConfig(
    value_from=SecretValueFrom.PARAM,
    name="database-password-prod"
)

# Parameter Store with suffix for environment variable naming
parameter_with_suffix = ContainerSecretConfig(
    value_from=SecretValueFrom.PARAM,
    name="redis-password",
    suffix="CACHE"  # Results in environment variable like REDIS_PASSWORD_CACHE
)

EcsEfsConfig

Bases: BaseModel

Configuration model for EFS integration with ECS containers.

Comprehensive configuration for mounting Elastic File System volumes into ECS containers, supporting multiple EFS systems, access points, and container-level permissions management for persistent storage requirements.

This configuration enables: - Multiple EFS volume attachments from different file systems - Container user/group specification for permission alignment - Flexible mount point configuration with read/write controls - Cross-EFS system volume referencing within a single task

Attributes:

Name Type Description
container_user Optional[str]

User:Group specification for container process (e.g., '1000:1000')

volumes List[EfsVolumeConfig]

List of EFS file systems to attach as volumes

mount_points List[EfsMountPointConfig]

List of container mount point configurations

Source code in mare_aws_common_lib/models/ecs_config.py
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
class EcsEfsConfig(BaseModel):
    """Configuration model for EFS integration with ECS containers.

    Comprehensive configuration for mounting Elastic File System volumes into
    ECS containers, supporting multiple EFS systems, access points, and
    container-level permissions management for persistent storage requirements.

    This configuration enables:
    - Multiple EFS volume attachments from different file systems
    - Container user/group specification for permission alignment
    - Flexible mount point configuration with read/write controls
    - Cross-EFS system volume referencing within a single task

    Attributes:
        container_user: User:Group specification for container process (e.g., '1000:1000')
        volumes: List of EFS file systems to attach as volumes
        mount_points: List of container mount point configurations
    """

    model_config = ConfigDict(extra="forbid")

    # Container user configuration
    container_user: Optional[str] = Field(
        default=None, 
        description="User:Group to run container as (e.g., '1000:1000') to match EFS permissions"
    )
    # Multiple EFS volumes (can be from different EFS systems)
    volumes: List[EfsVolumeConfig] = Field(
        default_factory=list,
        description="List of EFS volumes to attach"
    )
    # Mount points (can reference volumes from different EFS systems)
    mount_points: List[EfsMountPointConfig] = Field(
        default_factory=list, 
        description="List of mount points for containers"
    )

    @field_validator("container_user")
    @classmethod
    def validate_container_user(cls, value: str) -> str:
        """Validate container user format (uid:gid)."""
        if value is not None:
            if not re.match(r'^\d+:\d+$', value):
                raise ValueError("container_user must be in format 'uid:gid' (e.g., '1000:1000')")
        return value

validate_container_user(value) classmethod

Validate container user format (uid:gid).

Source code in mare_aws_common_lib/models/ecs_config.py
212
213
214
215
216
217
218
219
@field_validator("container_user")
@classmethod
def validate_container_user(cls, value: str) -> str:
    """Validate container user format (uid:gid)."""
    if value is not None:
        if not re.match(r'^\d+:\d+$', value):
            raise ValueError("container_user must be in format 'uid:gid' (e.g., '1000:1000')")
    return value
Example
from mare_aws_common_lib.models import EcsEfsConfig, EfsVolumeConfig, EfsMountPointConfig

# Complete EFS configuration with multiple volumes and mount points
efs_config = EcsEfsConfig(
    container_user="1000:1000",  # Run container as specific user for EFS permissions
    volumes=[
        # Shared data volume with access point
        EfsVolumeConfig(
            efs_parameter_key_suffix="SHARED",
            volume_name="shared-data",
            ap_parameter_key_suffix="APP_DATA"
        ),
        # Log volume with root access
        EfsVolumeConfig(
            efs_parameter_key_suffix="LOGS",
            volume_name="app-logs"
        ),
        # Configuration volume from different EFS system
        EfsVolumeConfig(
            efs_parameter_key_suffix="CONFIG",
            volume_name="app-config",
            ap_parameter_key_suffix="READONLY"
        )
    ],
    mount_points=[
        # Application data mount (read-write)
        EfsMountPointConfig(
            volume_name="shared-data",
            container_path="/app/data",
            read_only=False
        ),
        # Log directory mount (read-write)
        EfsMountPointConfig(
            volume_name="app-logs", 
            container_path="/var/log/app",
            read_only=False
        ),
        # Configuration mount (read-only)
        EfsMountPointConfig(
            volume_name="app-config",
            container_path="/etc/app/config",
            read_only=True
        )
    ]
)

# Minimal EFS configuration with single volume
minimal_efs_config = EcsEfsConfig(
    volumes=[
        EfsVolumeConfig(
            efs_parameter_key_suffix="DATA",
            volume_name="persistent-storage"
        )
    ],
    mount_points=[
        EfsMountPointConfig(
            volume_name="persistent-storage",
            container_path="/app/storage",
            read_only=False
        )
    ]
)

EfsVolumeConfig

Bases: BaseModel, NameValidationMixin

Configuration model for EFS volume attachment to ECS tasks.

Defines how an EFS file system is mounted as a volume in ECS task definitions, supporting both root access and access point patterns for fine-grained permissions and path management.

Attributes:

Name Type Description
efs_parameter_key_suffix str

SSM parameter key suffix containing the EFS file system ID

volume_name str

Logical name for the volume reference in task definition

ap_parameter_key_suffix Optional[str]

Optional SSM parameter key suffix for EFS access point ID

Source code in mare_aws_common_lib/models/ecs_config.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
class EfsVolumeConfig(BaseModel, NameValidationMixin):
    """Configuration model for EFS volume attachment to ECS tasks.

    Defines how an EFS file system is mounted as a volume in ECS task definitions,
    supporting both root access and access point patterns for fine-grained
    permissions and path management.

    Attributes:
        efs_parameter_key_suffix: SSM parameter key suffix containing the EFS file system ID
        volume_name: Logical name for the volume reference in task definition
        ap_parameter_key_suffix: Optional SSM parameter key suffix for EFS access point ID
    """
    model_config = ConfigDict(extra="forbid")

    efs_parameter_key_suffix: str = Field(..., description="SSM parameter key suffix for EFS file system ID")
    volume_name: str = Field(..., description="Name for the volume in the task definition")
    ap_parameter_key_suffix: Optional[str] = Field(default=None, description="SSM parameter key suffix for the access point ID")

    @field_validator("volume_name")
    @classmethod
    def validate_volume_name(cls, value: str) -> str:
        return cls.validate_name(value)
Example
from mare_aws_common_lib.models import EfsVolumeConfig

volume_with_access_point = EfsVolumeConfig(
    efs_parameter_key_suffix="SHARED",
    volume_name="shared-data",
    ap_parameter_key_suffix="APP_DATA"
)

root_access_volume = EfsVolumeConfig(
    efs_parameter_key_suffix="LOGS",
    volume_name="application-logs"
)

EfsMountPointConfig

Bases: BaseModel, PathValidationMixin, NameValidationMixin

Configuration model for EFS mount point specifications in ECS containers.

Defines how EFS volumes are mounted into container filesystems, specifying the mount location, access permissions, and volume reference. Each mount point creates a binding between a defined EFS volume and a specific path within the container's filesystem namespace.

Mount points enable containers to access persistent storage with configurable permissions, supporting both read-write and read-only access patterns for different use cases such as shared configuration, application data, or logs.

Attributes:

Name Type Description
volume_name str

Reference to an EFS volume defined in the task definition

container_path str

Absolute filesystem path where the volume will be mounted

read_only bool

Access mode restriction for the mounted filesystem

Note

The volume_name must exactly match a volume_name from an EfsVolumeConfig in the same ECS configuration to establish proper volume binding during task execution.

Source code in mare_aws_common_lib/models/ecs_config.py
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
class EfsMountPointConfig(BaseModel, PathValidationMixin, NameValidationMixin):
    """Configuration model for EFS mount point specifications in ECS containers.

    Defines how EFS volumes are mounted into container filesystems, specifying
    the mount location, access permissions, and volume reference. Each mount point
    creates a binding between a defined EFS volume and a specific path within
    the container's filesystem namespace.

    Mount points enable containers to access persistent storage with configurable
    permissions, supporting both read-write and read-only access patterns for
    different use cases such as shared configuration, application data, or logs.

    Attributes:
        volume_name: Reference to an EFS volume defined in the task definition
        container_path: Absolute filesystem path where the volume will be mounted
        read_only: Access mode restriction for the mounted filesystem

    Note:
        The volume_name must exactly match a volume_name from an EfsVolumeConfig
        in the same ECS configuration to establish proper volume binding during
        task execution.
    """
    model_config = ConfigDict(extra="forbid")

    volume_name: str = Field(..., description="Name of the EFS volume to mount")
    container_path: str = Field(..., description="Path where EFS will be mounted in container")
    read_only: bool = Field(default=False, description="Whether mount is read-only")

    @field_validator("container_path")
    @classmethod
    def validate_container_path(cls, value: str) -> str:
        """Validate container mount path."""
        return cls.validate_path_pattern(value)

    @field_validator("volume_name")
    @classmethod
    def validate_volume_reference(cls, value: str) -> str:
        return cls.validate_name(value)

validate_container_path(value) classmethod

Validate container mount path.

Source code in mare_aws_common_lib/models/ecs_config.py
164
165
166
167
168
@field_validator("container_path")
@classmethod
def validate_container_path(cls, value: str) -> str:
    """Validate container mount path."""
    return cls.validate_path_pattern(value)
Example
from mare_aws_common_lib.models import EfsMountPointConfig

data_mount = EfsMountPointConfig(
    volume_name="shared-data", 
    container_path="/app/data",
    read_only=False            
)

config_mount = EfsMountPointConfig(
    volume_name="app-config",
    container_path="/etc/app/config",
    read_only=True
)

EnvironmentFileConfig

Bases: BaseModel, NameValidationMixin

Configuration model for S3-based environment files.

Defines S3 location for environment files that should be loaded into ECS containers at startup. Supports flexible path specifications and automatic ARN construction for simpler configuration management.

Attributes:

Name Type Description
bucket_name

S3 bucket name containing the environment file

file_path str

Path to the file within the bucket (with or without leading slash)

Source code in mare_aws_common_lib/models/ecs_config.py
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
class EnvironmentFileConfig(BaseModel, NameValidationMixin):
    """Configuration model for S3-based environment files.

    Defines S3 location for environment files that should be loaded into
    ECS containers at startup. Supports flexible path specifications and
    automatic ARN construction for simpler configuration management.

    Attributes:
        bucket_name: S3 bucket name containing the environment file
        file_path: Path to the file within the bucket (with or without leading slash)
    """
    model_config = ConfigDict(extra="forbid")

    bucket_base_name: str = Field(..., description="S3 bucket name")
    file_path: str = Field(..., description="Path to the environment file in the bucket")

    @field_validator("bucket_base_name")
    @classmethod
    def validate_bucket_name(cls, value: str) -> str:
        """Validate the bucket base name.

        Applies validation rules to bucket naming to ensure the 
        name meets AWS requirements and organizational standards.

        Args:
            value: Raw bucket base name from configuration

        Returns:
            Validated bucket base name

        Raises:
            ValueError: If the bucket name fails validation rules
        """
        return cls.validate_name(value)

    @field_validator("file_path")
    @classmethod
    def validate_file_path(cls, value: str) -> str:
        """Validate and normalize file path for S3 object keys.

        Ensures file paths are valid S3 object keys and normalizes them
        by removing leading slashes for consistent S3 access patterns.
        The validation checks for path structure compliance and removes
        problematic characters that could cause S3 access issues.

        Args:
            value: File path within the bucket (e.g., '/config/app.env' or 'config/app.env')

        Returns:
            Normalized file path without leading slash (e.g., 'config/app.env')

        Raises:
            ValueError: If file path is empty after normalization or contains
                    invalid characters such as newlines, carriage returns,
                    or null bytes that would cause S3 access failures
        """
        normalized_path = value.lstrip('/')
        if not normalized_path:
            raise ValueError("file_path cannot be empty")

        if any(char in normalized_path for char in ['\n', '\r', '\0']):
            raise ValueError("file_path contains invalid characters")

        return normalized_path

validate_bucket_name(value) classmethod

Validate the bucket base name.

Applies validation rules to bucket naming to ensure the name meets AWS requirements and organizational standards.

Parameters:

Name Type Description Default
value str

Raw bucket base name from configuration

required

Returns:

Type Description
str

Validated bucket base name

Raises:

Type Description
ValueError

If the bucket name fails validation rules

Source code in mare_aws_common_lib/models/ecs_config.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
@field_validator("bucket_base_name")
@classmethod
def validate_bucket_name(cls, value: str) -> str:
    """Validate the bucket base name.

    Applies validation rules to bucket naming to ensure the 
    name meets AWS requirements and organizational standards.

    Args:
        value: Raw bucket base name from configuration

    Returns:
        Validated bucket base name

    Raises:
        ValueError: If the bucket name fails validation rules
    """
    return cls.validate_name(value)

validate_file_path(value) classmethod

Validate and normalize file path for S3 object keys.

Ensures file paths are valid S3 object keys and normalizes them by removing leading slashes for consistent S3 access patterns. The validation checks for path structure compliance and removes problematic characters that could cause S3 access issues.

Parameters:

Name Type Description Default
value str

File path within the bucket (e.g., '/config/app.env' or 'config/app.env')

required

Returns:

Type Description
str

Normalized file path without leading slash (e.g., 'config/app.env')

Raises:

Type Description
ValueError

If file path is empty after normalization or contains invalid characters such as newlines, carriage returns, or null bytes that would cause S3 access failures

Source code in mare_aws_common_lib/models/ecs_config.py
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
@field_validator("file_path")
@classmethod
def validate_file_path(cls, value: str) -> str:
    """Validate and normalize file path for S3 object keys.

    Ensures file paths are valid S3 object keys and normalizes them
    by removing leading slashes for consistent S3 access patterns.
    The validation checks for path structure compliance and removes
    problematic characters that could cause S3 access issues.

    Args:
        value: File path within the bucket (e.g., '/config/app.env' or 'config/app.env')

    Returns:
        Normalized file path without leading slash (e.g., 'config/app.env')

    Raises:
        ValueError: If file path is empty after normalization or contains
                invalid characters such as newlines, carriage returns,
                or null bytes that would cause S3 access failures
    """
    normalized_path = value.lstrip('/')
    if not normalized_path:
        raise ValueError("file_path cannot be empty")

    if any(char in normalized_path for char in ['\n', '\r', '\0']):
        raise ValueError("file_path contains invalid characters")

    return normalized_path
Example
from mare_aws_common_lib.models import EnvironmentFileConfig

env_file = EnvironmentFileConfig(
    bucket_base_name="my-bucket", 
    container_path="/my_file.env"
)