Skip to content

RdsDBConfig

Bases: BaseModel, NameValidationMixin

Configuration model for AWS RDS PostgreSQL database instances.

Comprehensive configuration model that defines all aspects of an RDS PostgreSQL database including instance specifications, storage configuration, monitoring settings, security credentials, network access rules, and backup strategies.

This model validates database configuration parameters, ensures proper resource sizing, and enforces organizational standards for RDS deployments including naming conventions, storage limits, and monitoring requirements.

Attributes:

Name Type Description
db_name str

Name of the database to create within the RDS instance

instance_class str

EC2 instance class family (T3, M5, R5, etc.)

instance_size str

EC2 instance size within the class (MICRO, SMALL, etc.)

allocated_storage_gb int

Initial storage allocation in gigabytes

max_allocated_storage_gb int

Maximum storage for automatic scaling

monitoring_interval int

Enhanced monitoring collection interval in seconds

secret Optional[RdsSecretConfig]

Optional Secrets Manager configuration for credentials

use_iam_authentication bool

Enable IAM database authentication mapping

parameter_group Optional[Dict[str, str]]

Custom database parameter overrides

inbound_rules List[InboundRuleConfig]

Network access rules for the database security group

tag_key str

Primary tag key for backup and operational policies

tag_value str

Primary tag value for backup and operational policies

multi_az bool

Enable Multi-AZ deployment

use_foundation_key bool

Use KMS key from foundation

postgres_engine_version str

Postgres engine version (VER_12_9, ...,VER_17_4,..., VER_18_2)

allow_major_version_upgrade

Allow major upgrade on the postrgres engine version

apply_immediately

Apply the upgrade directly (out of the maintenance window)

Source code in mare_aws_common_lib/models/rds_db_config.py
 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
class RdsDBConfig(BaseModel, NameValidationMixin):
    """Configuration model for AWS RDS PostgreSQL database instances.

    Comprehensive configuration model that defines all aspects of an RDS PostgreSQL
    database including instance specifications, storage configuration, monitoring
    settings, security credentials, network access rules, and backup strategies.

    This model validates database configuration parameters, ensures proper resource
    sizing, and enforces organizational standards for RDS deployments including
    naming conventions, storage limits, and monitoring requirements.

    Attributes:
        db_name: Name of the database to create within the RDS instance
        instance_class: EC2 instance class family (T3, M5, R5, etc.)
        instance_size: EC2 instance size within the class (MICRO, SMALL, etc.)
        allocated_storage_gb: Initial storage allocation in gigabytes
        max_allocated_storage_gb: Maximum storage for automatic scaling
        monitoring_interval: Enhanced monitoring collection interval in seconds
        secret: Optional Secrets Manager configuration for credentials
        use_iam_authentication: Enable IAM database authentication mapping
        parameter_group: Custom database parameter overrides
        inbound_rules: Network access rules for the database security group
        tag_key: Primary tag key for backup and operational policies
        tag_value: Primary tag value for backup and operational policies
        multi_az: Enable  Multi-AZ deployment
        use_foundation_key: Use KMS key from foundation
        postgres_engine_version: Postgres engine version (VER_12_9, ...,VER_17_4,..., VER_18_2)
        allow_major_version_upgrade : Allow major upgrade on the postrgres engine version
        apply_immediately : Apply the upgrade directly (out of the maintenance window)
    """
    model_config = ConfigDict(extra="forbid")

    db_name: str = Field(..., min_length=1, max_length=63, description="Name of the database to create")
    instance_class: str = Field(..., description="RDS instance class (e.g., 'T3', 'M5', 'R5')")
    instance_size: str = Field(..., description="RDS instance size (e.g., 'MICRO', 'SMALL', 'MEDIUM', 'LARGE')")
    allocated_storage_gb: int = Field(..., ge=20, le=65536, description="Initial allocated storage in GB (minimum 20 GB for PostgreSQL)")
    max_allocated_storage_gb: int = Field(..., ge=20, le=65536, description="Maximum allocated storage in GB for autoscaling")
    monitoring_interval: int = Field(default=60, description="Enhanced monitoring interval in seconds")
    secret: Optional[RdsSecretConfig] = Field(default=None, description="Secret configuration for database credentials")
    use_iam_authentication: bool = Field(default=False, description="Whether to enable mapping of AWS Identity and Access Management (IAM) accounts to database accounts")
    parameter_group: Optional[Dict[str, str]] = Field(default=None, description="Database parameter group settings (parameter_name -> value)")
    inbound_rules: List[InboundRuleConfig] = Field(
        default_factory=list,
        description="Additional inbound rules for the database security group"
    )
    tag_key: str = Field(..., description="Tag key for backup strategy")
    tag_value: str = Field(..., description="Tag value for backup strategy")
    multi_az: bool = Field(default=False, description="Enable Multi-AZ deployment for high availability")
    use_foundation_key: bool = Field(default=True, description="Whether to use the KMS SNC key from the foundation")
    performance_insights_enabled: bool = Field(default=True, description="Enable Performance Insights")
    performance_insights_retention_period: int = Field(default=7, description="Performance Insights retention in days")
    postgres_engine_version : str = Field(default="VER_17_4",  description="Postgres engine version ('VER_12_9', ...,'VER_17_4',..., 'VER_18_2')")
    allow_major_version_upgrade : bool = Field(default=False, description="Allow major upgrade on the postrgres engine version")
    apply_immediately : bool = Field(default=False, description="Apply the upgrade directly (out of the maintenance window)")

    @property
    def cdk_instance_class(self) -> ec2.InstanceClass:
        """Convert instance class string to CDK InstanceClass enum.

        Transforms the validated instance class string into the corresponding
        AWS CDK InstanceClass enum for use in RDS instance definitions.

        Returns:
            CDK InstanceClass enum value matching the configured instance class
        """
        return ec2.InstanceClass[self.instance_class.upper()]

    @property
    def cdk_instance_size(self) -> ec2.InstanceClass:
        """Convert instance size string to CDK InstanceSize enum.

        Transforms the validated instance size string into the corresponding
        AWS CDK InstanceSize enum for use in RDS instance definitions.

        Returns:
            CDK InstanceSize enum value matching the configured instance size
        """
        return ec2.InstanceSize[self.instance_size.upper()]

    @property
    def cdk_postgres_engine_version(self) -> rds.PostgresEngineVersion:
        """Convert postgres engine version string to RDS postgres engine version.

        Transforms the validated postgres engine version string into the corresponding
        AWS CDK RDS PostgresEngineVersion for use in RDS engine definitions.

        Returns:
            CDK PostgresEngineVersion value matching the configured postgres engine version
        """

        version_with_dot = self.postgres_engine_version.removeprefix("VER_").replace("_", ".")
        _postgres_engine_version = rds.PostgresEngineVersion.of(version_with_dot, version_with_dot.split(".")[0])
        return _postgres_engine_version

    @field_validator('db_name')
    @classmethod
    def validate_table_name(cls, value: str) -> str:
        """Validate the database name.

        Applies validation rules specific to database naming to ensure the 
        name meets RDS requirements and organizational standards.

        Args:
            value: Raw database name from configuration

        Returns:
            Validated database name

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

    @field_validator('instance_class')
    @classmethod
    def validate_instance_class(cls, value: str) -> str:
        """Validate RDS instance class against available EC2 instance families.

        Ensures the specified instance class is a valid EC2 instance family
        that can be used for RDS deployments.

        Args:
            value: Instance class string (e.g., "t3", "m5", "r5")

        Returns:
            Uppercase validated instance class string

        Raises:
            ValueError: If instance class is not a valid EC2 instance family
        """
        valid_classes = {cls.name for cls in ec2.InstanceClass}
        if value.upper() not in valid_classes:
            raise ValueError(f"Must be one of {sorted(valid_classes)}")

        return value.upper()

    @field_validator('postgres_engine_version')
    @classmethod
    def validate_postgres_engine_version(cls, value: str) -> str:
        """Validate engine version against available Postgres Engine Version.

        Ensures the specified engine version is a valid postgres engine version
        that can be used for RDS deployments.

        Args:
            value: engine version string (e.g., "VER_17_4", "VER_18_2")

        Returns:
            Validated engine version string

        Raises:
            ValueError: If engine version is not a valid postgres engine version
        """

        valid_versions = [
            name for name, val in inspect.getmembers(rds.PostgresEngineVersion)
            if name.startswith("VER_") and isinstance(val, rds.PostgresEngineVersion)
        ]
        if value not in valid_versions:
            raise ValueError(f"Must be one of {sorted(valid_versions)}")

        return value

    @field_validator('instance_size')
    @classmethod
    def validate_instance_size(cls, value: str) -> str:
        """Validate RDS instance size against available EC2 instance sizes.

        Ensures the specified instance size is a valid EC2 instance size
        that can be combined with the instance class for RDS deployments.

        Args:
            value: Instance size string (e.g., "micro", "small", "large")

        Returns:
            Uppercase validated instance size string

        Raises:
            ValueError: If instance size is not a valid EC2 instance size
        """
        valid_sizes = {size.name for size in ec2.InstanceSize}
        if value.upper() not in valid_sizes:
            raise ValueError(f"Must be one of {sorted(valid_sizes)}")

        return value.upper()

    @field_validator('monitoring_interval')
    @classmethod
    def validate_monitoring_interval(cls, value: int) -> int:
        """Validate enhanced monitoring interval against CloudWatch requirements.

        Ensures the monitoring interval is a valid value supported by
        RDS Enhanced Monitoring and CloudWatch metric collection.

        Args:
            value: Monitoring interval in seconds

        Returns:
            Validated monitoring interval

        Raises:
            ValueError: If interval is not a supported monitoring value

        Valid Intervals:
            0 (disabled), 1, 5, 10, 15, 30, 60 seconds
        """
        valid_intervals = {0, 1, 5, 10, 15, 30, 60}
        if value not in valid_intervals:
            raise ValueError(f"Must be one of {sorted(valid_intervals)}")
        return value

    @field_validator('performance_insights_retention_period')
    @classmethod
    def validate_performance_insights_retention(cls, value: int) -> int:
        """Validate Performance Insights retention period against AWS requirements.

        Ensures the retention period is a valid value supported by
        RDS Performance Insights for database performance monitoring.

        Args:
            value: Retention period in days

        Returns:
            Validated retention period

        Raises:
            ValueError: If retention period is not a supported value

        Valid Retention Periods:
            7 (free tier), 31, 93, 186, 372 days
        """
        valid_periods = {7, 31, 93, 186, 372}  # Valid retention periods - 7 is free tier
        if value not in valid_periods:
            raise ValueError(f"Must be one of {sorted(valid_periods)}")
        return value

    @model_validator(mode="after")
    def validate_storage_configuration(self) -> 'RdsDBConfig':
        """Validate storage configuration for consistency and RDS requirements.

        Ensures storage allocation settings are logically consistent and
        meet RDS requirements for PostgreSQL databases including minimum
        storage sizes and autoscaling configuration.

        Returns:
            Self with validated storage configuration

        Raises:
            ValueError: If storage configuration is inconsistent or invalid

        Validation Rules:
            - Maximum allocated storage must be >= initial allocated storage
        """
        if self.max_allocated_storage_gb < self.allocated_storage_gb:
            raise ValueError(
                f"max_allocated_storage_gb ({self.max_allocated_storage_gb}) must be >= "
                f"allocated_storage_gb ({self.allocated_storage_gb})"
            )

        return self

cdk_instance_class property

Convert instance class string to CDK InstanceClass enum.

Transforms the validated instance class string into the corresponding AWS CDK InstanceClass enum for use in RDS instance definitions.

Returns:

Type Description
InstanceClass

CDK InstanceClass enum value matching the configured instance class

cdk_instance_size property

Convert instance size string to CDK InstanceSize enum.

Transforms the validated instance size string into the corresponding AWS CDK InstanceSize enum for use in RDS instance definitions.

Returns:

Type Description
InstanceClass

CDK InstanceSize enum value matching the configured instance size

cdk_postgres_engine_version property

Convert postgres engine version string to RDS postgres engine version.

Transforms the validated postgres engine version string into the corresponding AWS CDK RDS PostgresEngineVersion for use in RDS engine definitions.

Returns:

Type Description
PostgresEngineVersion

CDK PostgresEngineVersion value matching the configured postgres engine version

validate_instance_class(value) classmethod

Validate RDS instance class against available EC2 instance families.

Ensures the specified instance class is a valid EC2 instance family that can be used for RDS deployments.

Parameters:

Name Type Description Default
value str

Instance class string (e.g., "t3", "m5", "r5")

required

Returns:

Type Description
str

Uppercase validated instance class string

Raises:

Type Description
ValueError

If instance class is not a valid EC2 instance family

Source code in mare_aws_common_lib/models/rds_db_config.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
@field_validator('instance_class')
@classmethod
def validate_instance_class(cls, value: str) -> str:
    """Validate RDS instance class against available EC2 instance families.

    Ensures the specified instance class is a valid EC2 instance family
    that can be used for RDS deployments.

    Args:
        value: Instance class string (e.g., "t3", "m5", "r5")

    Returns:
        Uppercase validated instance class string

    Raises:
        ValueError: If instance class is not a valid EC2 instance family
    """
    valid_classes = {cls.name for cls in ec2.InstanceClass}
    if value.upper() not in valid_classes:
        raise ValueError(f"Must be one of {sorted(valid_classes)}")

    return value.upper()

validate_instance_size(value) classmethod

Validate RDS instance size against available EC2 instance sizes.

Ensures the specified instance size is a valid EC2 instance size that can be combined with the instance class for RDS deployments.

Parameters:

Name Type Description Default
value str

Instance size string (e.g., "micro", "small", "large")

required

Returns:

Type Description
str

Uppercase validated instance size string

Raises:

Type Description
ValueError

If instance size is not a valid EC2 instance size

Source code in mare_aws_common_lib/models/rds_db_config.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
@field_validator('instance_size')
@classmethod
def validate_instance_size(cls, value: str) -> str:
    """Validate RDS instance size against available EC2 instance sizes.

    Ensures the specified instance size is a valid EC2 instance size
    that can be combined with the instance class for RDS deployments.

    Args:
        value: Instance size string (e.g., "micro", "small", "large")

    Returns:
        Uppercase validated instance size string

    Raises:
        ValueError: If instance size is not a valid EC2 instance size
    """
    valid_sizes = {size.name for size in ec2.InstanceSize}
    if value.upper() not in valid_sizes:
        raise ValueError(f"Must be one of {sorted(valid_sizes)}")

    return value.upper()

validate_monitoring_interval(value) classmethod

Validate enhanced monitoring interval against CloudWatch requirements.

Ensures the monitoring interval is a valid value supported by RDS Enhanced Monitoring and CloudWatch metric collection.

Parameters:

Name Type Description Default
value int

Monitoring interval in seconds

required

Returns:

Type Description
int

Validated monitoring interval

Raises:

Type Description
ValueError

If interval is not a supported monitoring value

Valid Intervals

0 (disabled), 1, 5, 10, 15, 30, 60 seconds

Source code in mare_aws_common_lib/models/rds_db_config.py
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
@field_validator('monitoring_interval')
@classmethod
def validate_monitoring_interval(cls, value: int) -> int:
    """Validate enhanced monitoring interval against CloudWatch requirements.

    Ensures the monitoring interval is a valid value supported by
    RDS Enhanced Monitoring and CloudWatch metric collection.

    Args:
        value: Monitoring interval in seconds

    Returns:
        Validated monitoring interval

    Raises:
        ValueError: If interval is not a supported monitoring value

    Valid Intervals:
        0 (disabled), 1, 5, 10, 15, 30, 60 seconds
    """
    valid_intervals = {0, 1, 5, 10, 15, 30, 60}
    if value not in valid_intervals:
        raise ValueError(f"Must be one of {sorted(valid_intervals)}")
    return value

validate_performance_insights_retention(value) classmethod

Validate Performance Insights retention period against AWS requirements.

Ensures the retention period is a valid value supported by RDS Performance Insights for database performance monitoring.

Parameters:

Name Type Description Default
value int

Retention period in days

required

Returns:

Type Description
int

Validated retention period

Raises:

Type Description
ValueError

If retention period is not a supported value

Valid Retention Periods

7 (free tier), 31, 93, 186, 372 days

Source code in mare_aws_common_lib/models/rds_db_config.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
@field_validator('performance_insights_retention_period')
@classmethod
def validate_performance_insights_retention(cls, value: int) -> int:
    """Validate Performance Insights retention period against AWS requirements.

    Ensures the retention period is a valid value supported by
    RDS Performance Insights for database performance monitoring.

    Args:
        value: Retention period in days

    Returns:
        Validated retention period

    Raises:
        ValueError: If retention period is not a supported value

    Valid Retention Periods:
        7 (free tier), 31, 93, 186, 372 days
    """
    valid_periods = {7, 31, 93, 186, 372}  # Valid retention periods - 7 is free tier
    if value not in valid_periods:
        raise ValueError(f"Must be one of {sorted(valid_periods)}")
    return value

validate_postgres_engine_version(value) classmethod

Validate engine version against available Postgres Engine Version.

Ensures the specified engine version is a valid postgres engine version that can be used for RDS deployments.

Parameters:

Name Type Description Default
value str

engine version string (e.g., "VER_17_4", "VER_18_2")

required

Returns:

Type Description
str

Validated engine version string

Raises:

Type Description
ValueError

If engine version is not a valid postgres engine version

Source code in mare_aws_common_lib/models/rds_db_config.py
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
@field_validator('postgres_engine_version')
@classmethod
def validate_postgres_engine_version(cls, value: str) -> str:
    """Validate engine version against available Postgres Engine Version.

    Ensures the specified engine version is a valid postgres engine version
    that can be used for RDS deployments.

    Args:
        value: engine version string (e.g., "VER_17_4", "VER_18_2")

    Returns:
        Validated engine version string

    Raises:
        ValueError: If engine version is not a valid postgres engine version
    """

    valid_versions = [
        name for name, val in inspect.getmembers(rds.PostgresEngineVersion)
        if name.startswith("VER_") and isinstance(val, rds.PostgresEngineVersion)
    ]
    if value not in valid_versions:
        raise ValueError(f"Must be one of {sorted(valid_versions)}")

    return value

validate_storage_configuration()

Validate storage configuration for consistency and RDS requirements.

Ensures storage allocation settings are logically consistent and meet RDS requirements for PostgreSQL databases including minimum storage sizes and autoscaling configuration.

Returns:

Type Description
RdsDBConfig

Self with validated storage configuration

Raises:

Type Description
ValueError

If storage configuration is inconsistent or invalid

Validation Rules
  • Maximum allocated storage must be >= initial allocated storage
Source code in mare_aws_common_lib/models/rds_db_config.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
@model_validator(mode="after")
def validate_storage_configuration(self) -> 'RdsDBConfig':
    """Validate storage configuration for consistency and RDS requirements.

    Ensures storage allocation settings are logically consistent and
    meet RDS requirements for PostgreSQL databases including minimum
    storage sizes and autoscaling configuration.

    Returns:
        Self with validated storage configuration

    Raises:
        ValueError: If storage configuration is inconsistent or invalid

    Validation Rules:
        - Maximum allocated storage must be >= initial allocated storage
    """
    if self.max_allocated_storage_gb < self.allocated_storage_gb:
        raise ValueError(
            f"max_allocated_storage_gb ({self.max_allocated_storage_gb}) must be >= "
            f"allocated_storage_gb ({self.allocated_storage_gb})"
        )

    return self

validate_table_name(value) classmethod

Validate the database name.

Applies validation rules specific to database naming to ensure the name meets RDS requirements and organizational standards.

Parameters:

Name Type Description Default
value str

Raw database name from configuration

required

Returns:

Type Description
str

Validated database name

Raises:

Type Description
ValueError

If the database name fails validation rules

Source code in mare_aws_common_lib/models/rds_db_config.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
@field_validator('db_name')
@classmethod
def validate_table_name(cls, value: str) -> str:
    """Validate the database name.

    Applies validation rules specific to database naming to ensure the 
    name meets RDS requirements and organizational standards.

    Args:
        value: Raw database name from configuration

    Returns:
        Validated database name

    Raises:
        ValueError: If the database name fails validation rules
    """
    return cls.validate_name(value, "db")
Example
from mare_aws_common_lib.models import RdsDBConfig

config = RdsDBConfig(
    db_name="user-database",
    instance_class="T3",
    instance_size="MICRO",
    allocated_storage_gb=20,
    max_allocated_storage_gb=100,
    monitoring_interval=60,
    secret=RdsSecretConfig(user_pwd_rotation_days=90),
    parameter_group={"shared_preload_libraries": "pg_stat_statements"},
    inbound_rules=[
        InboundRuleConfig(
            description="App servers",
            ipv4_cidr_block="10.0.1.0/24"
        )
    ],
    tag_key="Environment",
    tag_value="Production"
)

RdsSecretConfig

Bases: BaseModel

Configuration model for RDS database credentials management.

Defines how database credentials are stored and managed in AWS Secrets Manager, including secret creation, sharing across accounts, and automatic password rotation settings for enhanced security.

Attributes:

Name Type Description
base_name Optional[str]

Base name of existing secret (if referencing existing secret)

is_shared bool

Whether the secret is shared across multiple AWS accounts

user_pwd_rotation_days int

Number of days between automatic password rotations

Source code in mare_aws_common_lib/models/rds_db_config.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class RdsSecretConfig(BaseModel):
    """Configuration model for RDS database credentials management.

    Defines how database credentials are stored and managed in AWS Secrets Manager,
    including secret creation, sharing across accounts, and automatic password
    rotation settings for enhanced security.

    Attributes:
        base_name: Base name of existing secret (if referencing existing secret)
        is_shared: Whether the secret is shared across multiple AWS accounts
        user_pwd_rotation_days: Number of days between automatic password rotations
    """
    model_config = ConfigDict(extra="forbid")

    base_name: Optional[str] = Field(default=None, description="Base name of existing secret (if using existing secret)")
    is_shared: bool = Field(default=False, description="Whether the secret is shared across accounts")
    user_pwd_rotation_days: int = Field(default=30, ge=1, le=365, description="Number of days between automatic password rotations")
Example
from mare_aws_common_lib.models import RdsSecretConfig 
secret_config = RdsSecretConfig(
    base_name="rds-secret",
    is_shared=False,
    user_pwd_rotation_days=30
)

InboundRuleConfig

Bases: BaseModel

Configuration model for RDS security group inbound access rules.

Defines network access rules that control which IP addresses or CIDR blocks can connect to the RDS database instance. Each rule specifies a source IP range and description for auditing and management purposes.

Attributes:

Name Type Description
description str

Human-readable description of the access rule

ipv4_cidr_block str

IPv4 CIDR block notation specifying allowed source IPs

Source code in mare_aws_common_lib/models/rds_db_config.py
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
class InboundRuleConfig(BaseModel):
    """Configuration model for RDS security group inbound access rules.

    Defines network access rules that control which IP addresses or CIDR blocks
    can connect to the RDS database instance. Each rule specifies a source
    IP range and description for auditing and management purposes.

    Attributes:
        description: Human-readable description of the access rule
        ipv4_cidr_block: IPv4 CIDR block notation specifying allowed source IPs
    """
    model_config = ConfigDict(extra="forbid")

    description: str = Field(..., min_length=1, description="Description of the inbound rule")
    ipv4_cidr_block: str = Field(..., description="IPv4 CIDR block for the inbound rule")

    @field_validator('ipv4_cidr_block')
    def validate_cidr_block(cls, value):
        cidr_pattern = r'^(\d{1,3}\.){3}\d{1,3}/\d{1,2}$'
        if not re.match(cidr_pattern, value):
            raise ValueError("Invalid IPv4 CIDR block format. Expected format: x.x.x.x/x")

        # Basic validation of IP ranges
        parts = value.split('/')
        ip_parts = parts[0].split('.')
        prefix = int(parts[1])

        if prefix < 0 or prefix > 32:
            raise ValueError("CIDR prefix must be between 0 and 32")

        for part in ip_parts:
            if int(part) < 0 or int(part) > 255:
                raise ValueError("Invalid IP address in CIDR block")

        return value
Example
from mare_aws_common_lib.models import InboundRuleConfig 
inbound_rules_config = [
    InboundRuleConfig(
        description="additonal inbound rule",
        ipv4_cidr_block="xx.xx.xx.xxx/xx"
    )
]