Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(cloudformation): update RDS DB clusters and instances in place (#1939)

iot-rocket58891caab1b4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 08587f02..4afdca46 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
+- **CloudFormation — `AWS::RDS::DBCluster` and `AWS::RDS::DBInstance` update in place** — a stack update re-ran the create, which gave the resource a new endpoint, resource id and create time and emptied the cluster's member list; the properties the create stores now change on the existing record, a create-only or `Engine` change replaces the resource or, under a custom identifier, is refused, a cluster `MasterUsername` change leaves the cluster as it is, change sets report which properties replace, and a stack-created cluster can now be described and answers `Fn::GetAtt DBClusterResourceId`. Contributed by @iot-rocket.
- **CloudFormation — `AWS::Pipes::Pipe` and `AWS::Scheduler::ScheduleGroup` update in place** — a pipe keeps its stream position and `CreationTime` when `Description`, `Target`, `RoleArn`, `DesiredState` or `Tags` change, gets `Description` and `Tags` on create and refuses a create-only source change under an explicit `Name`, and a schedule group takes template and stack tag changes while keeping tags added through `TagResource`.
- **CloudFormation — EKS cluster and node group updates** — `AWS::EKS::Cluster` applies `Version`, `Logging`, `ResourcesVpcConfig`, `AccessConfig.AuthenticationMode` and `Tags` in place and `AWS::EKS::Nodegroup` applies `ScalingConfig`, `Labels`, `Taints`, `UpdateConfig`, `LaunchTemplate`, `Version`, `ReleaseVersion` and `Tags`, where every such change used to report `UPDATE_COMPLETE` and was dropped.
- **SES — a sandboxed account sends only to verified or simulator recipients** — SES v2 `PutAccountDetails` with `ProductionAccessEnabled=false` puts the account (per region) in the sandbox, as on AWS, and `GetAccount` reports it with the submitted `Details`. A sandboxed send to a recipient that is neither a verified address or domain identity nor a `@simulator.amazonses.com` address fails with `MessageRejected` "Email address is not verified. The following identities failed the check in region …" for v1 `SendEmail`, `SendRawEmail` and `SendTemplatedEmail` and v2 `SendEmail`; bulk sends reject only the affected entries. Accounts stay in production by default. Reported by @skialpine.
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 6d690f0a..0bab3850 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -782,6 +782,18 @@ _CUSTOM_NAME_REPLACEMENT = {
"name": "UserId",
"requires_replacement": lambda old, new: old.get("UserName") != new.get("UserName"),
},
+ # The schemas' createOnlyProperties, plus Engine: only conditionally
+ # create-only there, yet a change of engine replaces the resource.
+ "AWS::RDS::DBCluster": {
+ "name": "DBClusterIdentifier",
+ "requires_replacement": lambda old, new: any(
+ old.get(p) != new.get(p) for p in _RDS_DB_CLUSTER_CREATE_ONLY + ("Engine",)),
+ },
+ "AWS::RDS::DBInstance": {
+ "name": "DBInstanceIdentifier",
+ "requires_replacement": lambda old, new: any(
+ old.get(p) != new.get(p) for p in _RDS_DB_INSTANCE_CREATE_ONLY + ("Engine",)),
+ },
# Type and WorkflowName are "Update requires: Replacement" in the
# aws-resource-glue-trigger reference.
"AWS::Glue::Trigger": {
@@ -880,14 +892,13 @@ def _delete_predecessor(delete_fn, *args, **kwargs):
retaining set): the engine then records the DELETE_SKIPPED event and the
predecessor stays, as on AWS. Every update handler that creates the
replacement itself removes the old resource through this, so the policy
- cannot be forgotten at one site, with five exceptions. Four have a
- deterministic generated name (the DynamoDB table, the Location tracker,
- the IoT thing type and the Glue trigger): the replacement takes the name
- back, so there is nothing left to retain. The fifth is the Lambda
- permission's degenerate ``Id`` branch,
- which removes and re-puts one statement under a Sid that cannot change:
- the physical id is kept, nothing is replaced, and the policy does not
- apply.
+ cannot be forgotten at one site, with these exceptions. The DynamoDB
+ table, the Location tracker, the IoT thing type, the Glue trigger and the
+ RDS DB cluster and instance have a deterministic generated name: the
+ replacement takes the name back, so there is nothing left to retain. The
+ other is the Lambda permission's degenerate ``Id`` branch, which removes
+ and re-puts one statement under a Sid that cannot change: the physical id
+ is kept, nothing is replaced, and the policy does not apply.
"""
if _RETAIN_REPLACED.get():
return
@@ -10309,45 +10320,112 @@ def _cf_kvs_delete(physical_id, props):
# RDS DBCluster
# ---------------------------------------------------------------------------
+# The type schema's createOnlyProperties and conditionalCreateOnlyProperties.
+_RDS_DB_CLUSTER_CREATE_ONLY = (
+ "ClusterScalabilityType", "DBClusterIdentifier", "DBSubnetGroupName", "DBSystemId",
+ "DatabaseName", "EngineMode", "KmsKeyId", "PubliclyAccessible", "RestoreToTime",
+ "RestoreType", "SnapshotIdentifier", "SourceDBClusterIdentifier",
+ "SourceDbClusterResourceId", "SourceRegion", "StorageEncrypted", "UseLatestRestorableTime",
+)
+_RDS_DB_CLUSTER_CONDITIONAL = ("AvailabilityZones", "Engine", "GlobalClusterIdentifier",
+ "MasterUsername")
+
+
+def _rds_db_cluster_fields(props):
+ """The DBCluster record fields that a stack update changes in place."""
+ engine = props.get("Engine", "aurora-postgresql")
+ return {
+ "Engine": engine,
+ "EngineVersion": props.get("EngineVersion") or _rds._default_engine_version(engine),
+ "Port": int(props.get("Port") or _rds._default_port(engine)),
+ "BackupRetentionPeriod": int(props.get("BackupRetentionPeriod", 1)),
+ "PreferredBackupWindow": props.get("PreferredBackupWindow", "03:00-04:00"),
+ "PreferredMaintenanceWindow": props.get("PreferredMaintenanceWindow", "sun:05:00-sun:06:00"),
+ "ServerlessV2ScalingConfiguration": props.get("ServerlessV2ScalingConfiguration"),
+ "VpcSecurityGroups": [{"VpcSecurityGroupId": sg, "Status": "active"}
+ for sg in props.get("VpcSecurityGroupIds") or []],
+ "DeletionProtection": _cfn_bool(props.get("DeletionProtection", False)),
+ "CopyTagsToSnapshot": _cfn_bool(props.get("CopyTagsToSnapshot", False)),
+ "IAMDatabaseAuthenticationEnabled": _cfn_bool(props.get("EnableIAMDatabaseAuthentication", False)),
+ "HttpEndpointEnabled": _cfn_bool(props.get("EnableHttpEndpoint", False)),
+ "_MasterUserPassword": props.get("MasterUserPassword", "password"),
+ }
+
+
+def _rds_apply_changed(record, old_fields, new_fields):
+ """Write the fields whose template value changed; values set through the RDS API stay."""
+ record.update({k: v for k, v in new_fields.items() if old_fields.get(k) != v})
+
+
+def _rds_cluster_resource_id():
+ """A new DbClusterResourceId in the shape RDS reports it."""
+ return f"cluster-{new_uuid().replace('-', '')[:20].upper()}"
+
+
+def _rds_db_cluster_attrs(cluster):
+ """The Fn::GetAtt attributes of a DB cluster record."""
+ return {
+ "Arn": cluster["DBClusterArn"],
+ "DBClusterArn": cluster["DBClusterArn"],
+ "DBClusterResourceId": cluster["DbClusterResourceId"],
+ "Endpoint.Address": cluster["Endpoint"],
+ "Endpoint.Port": str(cluster["Port"]),
+ "ReadEndpoint.Address": cluster["ReaderEndpoint"],
+ }
+
+
def _rds_db_cluster_create(logical_id, props, stack_name):
cluster_id = props.get("DBClusterIdentifier") or _physical_name(stack_name, logical_id, lowercase=True, max_len=63)
- engine = props.get("Engine", "aurora-postgresql")
- engine_version = props.get("EngineVersion") or _rds._default_engine_version(engine)
- master_user = props.get("MasterUsername", "admin")
arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:cluster:{cluster_id}"
suffix = new_uuid()[:8]
+ created = now_iso()
- _rds._clusters[cluster_id] = {
+ cluster = _rds._clusters[cluster_id] = {
"DBClusterIdentifier": cluster_id,
"DBClusterArn": arn,
- "Engine": engine,
- "EngineVersion": engine_version,
+ "DbClusterResourceId": _rds_cluster_resource_id(),
"EngineMode": props.get("EngineMode", "provisioned"),
"Status": "available",
- "MasterUsername": master_user,
+ "MasterUsername": props.get("MasterUsername", "admin"),
"DatabaseName": props.get("DatabaseName", ""),
"Endpoint": f"{cluster_id}.cluster-{suffix}.{get_region()}.rds.amazonaws.com",
"ReaderEndpoint": f"{cluster_id}.cluster-ro-{suffix}.{get_region()}.rds.amazonaws.com",
- "Port": int(props.get("Port", 5432)),
"MultiAZ": props.get("MultiAZ", False),
"AvailabilityZones": [f"{get_region()}a", f"{get_region()}b", f"{get_region()}c"],
"DBClusterMembers": [],
- "VpcSecurityGroups": [],
"DBSubnetGroup": props.get("DBSubnetGroupName", "default"),
"StorageEncrypted": props.get("StorageEncrypted", False),
- "DeletionProtection": props.get("DeletionProtection", False),
- "CopyTagsToSnapshot": props.get("CopyTagsToSnapshot", False),
"AllocatedStorage": 1,
- "ClusterCreateTime": now_iso(),
- "BackupRetentionPeriod": int(props.get("BackupRetentionPeriod", 1)),
- }
- return cluster_id, {
- "Arn": arn,
- "ClusterResourceId": f"cluster-{new_uuid()[:20]}",
- "Endpoint.Address": f"{cluster_id}.cluster-{suffix}.{get_region()}.rds.amazonaws.com",
- "Endpoint.Port": str(int(props.get("Port", 5432))),
- "ReadEndpoint.Address": f"{cluster_id}.cluster-ro-{suffix}.{get_region()}.rds.amazonaws.com",
+ "ClusterCreateTime": created,
+ "EarliestRestorableTime": created,
+ "LatestRestorableTime": created,
+ **_rds_db_cluster_fields(props),
}
+ return cluster_id, _rds_db_cluster_attrs(cluster)
+
+
+def _rds_db_cluster_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update a DB cluster in place; a create-only property replaces it."""
+ cluster = _rds._clusters.get(physical_id)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ new_props.get("DBClusterIdentifier") or _physical_name(
+ stack_name, logical_id or physical_id, lowercase=True, max_len=63),
+ physical_id if cluster is not None else None,
+ _rds_db_cluster_create, _rds_db_cluster_delete,
+ )
+ if replaced is not None:
+ return replaced
+ if _requires_replacement("AWS::RDS::DBCluster", old_props, new_props):
+ # The generated name is deterministic, so the replacement takes it back.
+ _rds_db_cluster_delete(physical_id, old_props)
+ return _rds_db_cluster_create(logical_id or physical_id, new_props, stack_name)
+ # A record saved before the create stored these fields gets them first, so the update cannot fail half-way.
+ cluster.setdefault("DbClusterResourceId", _rds_cluster_resource_id())
+ for key in ("EarliestRestorableTime", "LatestRestorableTime"):
+ cluster.setdefault(key, cluster["ClusterCreateTime"])
+ _rds_apply_changed(cluster, _rds_db_cluster_fields(old_props), _rds_db_cluster_fields(new_props))
+ return physical_id, _rds_db_cluster_attrs(cluster)
def _rds_db_cluster_delete(physical_id, props):
@@ -10364,6 +10442,75 @@ def _rds_db_cluster_snapshot(physical_id, props):
# RDS DBInstance
# ---------------------------------------------------------------------------
+_RDS_DB_INSTANCE_CREATE_ONLY = (
+ "BackupTarget", "CharacterSetName", "CustomIAMInstanceProfile", "DBClusterIdentifier",
+ "DBInstanceIdentifier", "DBName", "DBSubnetGroupName", "DBSystemId", "KmsKeyId",
+ "MasterUsername", "NcharCharacterSetName", "SourceRegion", "StorageEncrypted", "Timezone",
+)
+_RDS_DB_INSTANCE_CONDITIONAL = (
+ "AutoMinorVersionUpgrade", "AvailabilityZone", "BackupRetentionPeriod",
+ "DBClusterSnapshotIdentifier", "DBParameterGroupName", "DBSnapshotIdentifier", "Engine",
+ "MultiAZ", "PerformanceInsightsKMSKeyId", "PreferredMaintenanceWindow", "RestoreTime",
+ "SourceDBClusterIdentifier", "SourceDBInstanceAutomatedBackupsArn",
+ "SourceDBInstanceIdentifier", "SourceDbiResourceId", "UseLatestRestorableTime",
+)
+
+
+def _rds_db_instance_port(props):
+ return int(props.get("Port") or _rds._default_port(props.get("Engine", "postgres")))
+
+
+def _rds_db_instance_fields(props):
+ """The DBInstance record fields that a stack update changes in place."""
+ engine = props.get("Engine", "postgres")
+ engine_version = props.get("EngineVersion") or _rds._default_engine_version(engine)
+ vpc_sgs = props.get("VPCSecurityGroups") or props.get("VpcSecurityGroupIds") or []
+ if isinstance(vpc_sgs, str):
+ vpc_sgs = [vpc_sgs]
+ return {
+ "Engine": engine,
+ "LicenseModel": _rds._license_model(engine),
+ "OptionGroupMemberships": [{
+ "OptionGroupName": f"default:{engine}-{engine_version.split('.')[0]}",
+ "Status": "in-sync",
+ }],
+ "DBInstanceClass": props.get("DBInstanceClass", "db.t3.micro"),
+ "EngineVersion": engine_version,
+ "AllocatedStorage": int(props.get("AllocatedStorage") or 20),
+ "StorageType": props.get("StorageType", "gp2"),
+ "PreferredBackupWindow": props.get("PreferredBackupWindow", "03:00-04:00"),
+ "BackupRetentionPeriod": int(props.get("BackupRetentionPeriod", 1)),
+ "VpcSecurityGroups": [{"VpcSecurityGroupId": sg, "Status": "active"} for sg in vpc_sgs],
+ "DBParameterGroups": [{
+ "DBParameterGroupName": props.get("DBParameterGroupName")
+ or f"default.{engine}{engine_version.split('.')[0]}",
+ "ParameterApplyStatus": "in-sync",
+ }],
+ "AvailabilityZone": props.get("AvailabilityZone", f"{get_region()}a"),
+ "PreferredMaintenanceWindow": props.get("PreferredMaintenanceWindow", "sun:05:00-sun:06:00"),
+ "MultiAZ": _cfn_bool(props.get("MultiAZ", False)),
+ "AutoMinorVersionUpgrade": _cfn_bool(props.get("AutoMinorVersionUpgrade", True)),
+ "PubliclyAccessible": _cfn_bool(props.get("PubliclyAccessible", False)),
+ "CopyTagsToSnapshot": _cfn_bool(props.get("CopyTagsToSnapshot", False)),
+ "MonitoringInterval": int(props.get("MonitoringInterval", 0)),
+ "MonitoringRoleArn": props.get("MonitoringRoleArn", ""),
+ "PromotionTier": int(props.get("PromotionTier", 1)),
+ "IAMDatabaseAuthenticationEnabled": _cfn_bool(props.get("EnableIAMDatabaseAuthentication", False)),
+ "DeletionProtection": _cfn_bool(props.get("DeletionProtection", False)),
+ "PerformanceInsightsEnabled": _cfn_bool(props.get("EnablePerformanceInsights", False)),
+ }
+
+
+def _rds_db_instance_attrs(instance):
+ """The Fn::GetAtt attributes of a DB instance record."""
+ return {
+ "Endpoint.Address": instance["Endpoint"]["Address"],
+ "Endpoint.Port": str(instance["Endpoint"]["Port"]),
+ "DbiResourceId": instance["DbiResourceId"],
+ "DBInstanceArn": instance["DBInstanceArn"],
+ }
+
+
def _rds_db_instance_create(logical_id, props, stack_name):
"""Provision an AWS::RDS::DBInstance.
@@ -10375,9 +10522,6 @@ def _rds_db_instance_create(logical_id, props, stack_name):
db_id = props.get("DBInstanceIdentifier") or _physical_name(
stack_name, logical_id, lowercase=True, max_len=63
)
- engine = props.get("Engine", "postgres")
- engine_version = props.get("EngineVersion") or _rds._default_engine_version(engine)
- db_class = props.get("DBInstanceClass", "db.t3.micro")
master_user = props.get("MasterUsername", "admin")
master_pass = props.get("MasterUserPassword", "password")
db_name = props.get("DBName", "")
@@ -10391,21 +10535,9 @@ def _rds_db_instance_create(logical_id, props, stack_name):
if not db_name:
db_name = parent.get("DatabaseName", "")
- port = int(props.get("Port") or _rds._default_port(engine))
- allocated_storage = int(props.get("AllocatedStorage") or 20)
- storage_type = props.get("StorageType", "gp2")
subnet_group_name = props.get("DBSubnetGroupName", "default")
arn = f"arn:aws:rds:{get_region()}:{get_account_id()}:db:{db_id}"
- dbi_resource_id = f"db-{new_uuid().replace('-', '')[:20].upper()}"
- param_group_name = (
- props.get("DBParameterGroupName")
- or f"default.{engine}{engine_version.split('.')[0]}"
- )
-
- vpc_sgs = props.get("VPCSecurityGroups") or props.get("VpcSecurityGroupIds") or []
- if isinstance(vpc_sgs, str):
- vpc_sgs = [vpc_sgs]
- vpc_sg_list = [{"VpcSecurityGroupId": sg, "Status": "active"} for sg in vpc_sgs]
+ fields = _rds_db_instance_fields(props)
subnet_group = _rds._subnet_groups.get(subnet_group_name, {
"DBSubnetGroupName": subnet_group_name,
@@ -10418,60 +10550,31 @@ def _rds_db_instance_create(logical_id, props, stack_name):
instance = {
"DBInstanceIdentifier": db_id,
- "DBInstanceClass": db_class,
- "Engine": engine,
- "EngineVersion": engine_version,
"DBInstanceStatus": "available",
"MasterUsername": master_user,
"_MasterUserPassword": master_pass,
"DBName": db_name or "mydb",
"Endpoint": {
"Address": f"{db_id}.{new_uuid()[:8]}.{get_region()}.rds.amazonaws.com",
- "Port": port,
+ "Port": _rds_db_instance_port(props),
"HostedZoneId": "Z2R2ITUGPM61AM",
},
- "AllocatedStorage": allocated_storage,
"InstanceCreateTime": _rds._format_time(time.time()),
- "PreferredBackupWindow": props.get("PreferredBackupWindow", "03:00-04:00"),
- "BackupRetentionPeriod": int(props.get("BackupRetentionPeriod", 1)),
"DBSecurityGroups": [],
- "VpcSecurityGroups": vpc_sg_list,
- "DBParameterGroups": [{
- "DBParameterGroupName": param_group_name,
- "ParameterApplyStatus": "in-sync",
- }],
- "AvailabilityZone": props.get("AvailabilityZone", f"{get_region()}a"),
"DBSubnetGroup": subnet_group,
- "PreferredMaintenanceWindow": props.get("PreferredMaintenanceWindow", "sun:05:00-sun:06:00"),
"PendingModifiedValues": {},
- "MultiAZ": bool(props.get("MultiAZ", False)),
- "AutoMinorVersionUpgrade": bool(props.get("AutoMinorVersionUpgrade", True)),
"ReadReplicaDBInstanceIdentifiers": [],
"ReadReplicaSourceDBInstanceIdentifier": "",
- "LicenseModel": _rds._license_model(engine),
- "OptionGroupMemberships": [{
- "OptionGroupName": f"default:{engine}-{engine_version.split('.')[0]}",
- "Status": "in-sync",
- }],
- "PubliclyAccessible": bool(props.get("PubliclyAccessible", False)),
- "StorageType": storage_type,
- "StorageEncrypted": bool(props.get("StorageEncrypted", False)),
+ "StorageEncrypted": _cfn_bool(props.get("StorageEncrypted", False)),
"KmsKeyId": props.get("KmsKeyId", ""),
- "DbiResourceId": dbi_resource_id,
+ "DbiResourceId": f"db-{new_uuid().replace('-', '')[:20].upper()}",
"CACertificateIdentifier": "rds-ca-rsa2048-g1",
- "CopyTagsToSnapshot": bool(props.get("CopyTagsToSnapshot", False)),
- "MonitoringInterval": int(props.get("MonitoringInterval", 0)),
- "MonitoringRoleArn": props.get("MonitoringRoleArn", ""),
- "PromotionTier": int(props.get("PromotionTier", 1)),
"DBInstanceArn": arn,
"DBClusterIdentifier": cluster_id,
- "IAMDatabaseAuthenticationEnabled": bool(props.get("EnableIAMDatabaseAuthentication", False)),
- "DeletionProtection": bool(props.get("DeletionProtection", False)),
- "PerformanceInsightsEnabled": bool(props.get("EnablePerformanceInsights", False)),
"TagList": props.get("Tags", []),
+ "LatestRestorableTime": _rds._format_time(time.time()),
+ **fields,
}
- import time as _time
- instance["LatestRestorableTime"] = _rds._format_time(_time.time())
_rds._instances[db_id] = instance
if cluster_id and cluster_id in _rds._clusters:
@@ -10481,15 +10584,39 @@ def _rds_db_instance_create(logical_id, props, stack_name):
"DBInstanceIdentifier": db_id,
"IsClusterWriter": True,
"DBClusterParameterGroupStatus": "in-sync",
- "PromotionTier": int(props.get("PromotionTier", 1)),
+ "PromotionTier": fields["PromotionTier"],
})
- return db_id, {
- "Endpoint.Address": instance["Endpoint"]["Address"],
- "Endpoint.Port": str(port),
- "DbiResourceId": dbi_resource_id,
- "DBInstanceArn": arn,
- }
+ return db_id, _rds_db_instance_attrs(instance)
+
+
+def _rds_db_instance_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ """Update a DB instance in place; a create-only property replaces it."""
+ instance = _rds._instances.get(physical_id)
+ replaced = _rename_replacement(
+ physical_id, old_props, new_props, stack_name, logical_id,
+ new_props.get("DBInstanceIdentifier") or _physical_name(
+ stack_name, logical_id or physical_id, lowercase=True, max_len=63),
+ physical_id if instance is not None else None,
+ _rds_db_instance_create, _rds_db_instance_delete,
+ )
+ if replaced is not None:
+ return replaced
+ if _requires_replacement("AWS::RDS::DBInstance", old_props, new_props):
+ # The generated name is deterministic, so the replacement takes it back.
+ _rds_db_instance_delete(physical_id, old_props)
+ return _rds_db_instance_create(logical_id or physical_id, new_props, stack_name)
+ _rds_apply_changed(instance, _rds_db_instance_fields(old_props), _rds_db_instance_fields(new_props))
+ if _rds_db_instance_port(old_props) != _rds_db_instance_port(new_props):
+ instance["Endpoint"]["Port"] = _rds_db_instance_port(new_props)
+ if new_props.get("MasterUserPassword") not in (None, old_props.get("MasterUserPassword")):
+ instance["_MasterUserPassword"] = new_props["MasterUserPassword"]
+ _reconcile_tag_list(instance.setdefault("TagList", []), old_props, new_props)
+ cluster = _rds._clusters.get(instance.get("DBClusterIdentifier") or "")
+ for member in (cluster or {}).get("DBClusterMembers", []):
+ if member.get("DBInstanceIdentifier") == physical_id:
+ member["PromotionTier"] = instance["PromotionTier"]
+ return physical_id, _rds_db_instance_attrs(instance)
def _rds_db_instance_snapshot(physical_id, props):
@@ -12716,6 +12843,8 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {
),
"AWS::ElastiCache::User": ("UserId", "UserName"),
"AWS::ElastiCache::UserGroup": ("UserGroupId",),
+ "AWS::RDS::DBCluster": _RDS_DB_CLUSTER_CREATE_ONLY,
+ "AWS::RDS::DBInstance": _RDS_DB_INSTANCE_CREATE_ONLY,
# Table, Partition and Connection replace on nested members
# (TableInput.Name, PartitionInput.Values, ConnectionInput.Name).
"AWS::Glue::Database": ("DatabaseName",),
@@ -12728,6 +12857,8 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {
_CONDITIONALLY_REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {
"AWS::DynamoDB::Table": ("KeySchema",),
"AWS::Lambda::Function": ("DurableConfig",),
+ "AWS::RDS::DBCluster": _RDS_DB_CLUSTER_CONDITIONAL,
+ "AWS::RDS::DBInstance": _RDS_DB_INSTANCE_CONDITIONAL,
"AWS::ElastiCache::CacheCluster": ("NumCacheNodes",),
"AWS::ElastiCache::ReplicationGroup": ("AuthToken", "NodeGroupConfiguration", "NumNodeGroups"),
}
@@ -13424,9 +13555,11 @@ _RESOURCE_HANDLERS = {
"update": _cw_dashboard_update,
"delete": _cw_dashboard_delete,
},
- "AWS::RDS::DBCluster": {"create": _rds_db_cluster_create, "delete": _rds_db_cluster_delete,
+ "AWS::RDS::DBCluster": {"create": _rds_db_cluster_create, "update": _rds_db_cluster_update,
+ "update_with_logical_id": True, "delete": _rds_db_cluster_delete,
"snapshot": _rds_db_cluster_snapshot},
- "AWS::RDS::DBInstance": {"create": _rds_db_instance_create, "delete": _rds_db_instance_delete,
+ "AWS::RDS::DBInstance": {"create": _rds_db_instance_create, "update": _rds_db_instance_update,
+ "update_with_logical_id": True, "delete": _rds_db_instance_delete,
"snapshot": _rds_db_instance_snapshot},
"AWS::IoT::TopicRule": {
"create": _iot_topic_rule_create,
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index eb13d7df..f4a8a769 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -26316,6 +26316,265 @@ def test_cfn_rds_instance_in_a_cluster_defaults_to_delete(cfn, rds):
_delete_cfn_test_stack(cfn, stack_name)
+def _rds_cluster_stack(retention=1, tier=1, **cluster_props):
+ """An Aurora cluster with one member, exporting the cluster's GetAtt identity."""
+ return {"Resources": {
+ "Cluster": {"Type": "AWS::RDS::DBCluster", "DeletionPolicy": "Delete", "Properties": {
+ "Engine": "aurora-postgresql", "MasterUsername": "admin",
+ "MasterUserPassword": "password123", "BackupRetentionPeriod": retention,
+ **cluster_props}},
+ "Member": {"Type": "AWS::RDS::DBInstance", "Properties": {
+ "DBClusterIdentifier": {"Ref": "Cluster"}, "Engine": "aurora-postgresql",
+ "DBInstanceClass": "db.serverless", "PromotionTier": tier}},
+ }, "Outputs": {
+ "ResourceId": {"Value": {"Fn::GetAtt": ["Cluster", "DBClusterResourceId"]}},
+ "Endpoint": {"Value": {"Fn::GetAtt": ["Cluster", "Endpoint.Address"]}},
+ }}
+
+
+_RDS_CLUSTER_IDENTITY = ("DBClusterArn", "DbClusterResourceId", "Endpoint", "ClusterCreateTime")
+_RDS_INSTANCE_IDENTITY = ("DBInstanceArn", "DbiResourceId", "Endpoint", "InstanceCreateTime")
+
+
+def _rds_ids(stack, rds):
+ """The cluster and member records of a _rds_cluster_stack."""
+ cluster = rds.describe_db_clusters(DBClusterIdentifier=stack["Cluster"])["DBClusters"][0]
+ member = rds.describe_db_instances(DBInstanceIdentifier=stack["Member"])["DBInstances"][0]
+ return cluster, member
+
+
+def _rds_physical_ids(cfn, stack_name):
+ return {r["LogicalResourceId"]: r["PhysicalResourceId"]
+ for r in cfn.describe_stack_resources(StackName=stack_name)["StackResources"]}
+
+
+def test_cfn_update_rds_cluster_and_member_in_place(cfn, rds):
+ """A cluster property change and a member property change are applied
+ to the existing records: identifiers, endpoints, resource ids, create
+ times and the cluster's member list stay."""
+ stack_name = f"cfn-rds-upd-{_uuid_mod.uuid4().hex[:8]}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_rds_cluster_stack()))
+ try:
+ created = _wait_stack(cfn, stack_name)
+ assert created["StackStatus"] == "CREATE_COMPLETE", created.get("StackStatusReason")
+ ids = _rds_physical_ids(cfn, stack_name)
+ cluster, member = _rds_ids(ids, rds)
+ assert _output(created, "ResourceId") == cluster["DbClusterResourceId"]
+ assert _output(created, "Endpoint") == cluster["Endpoint"]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(_rds_cluster_stack(retention=2)))
+ updated = _wait_stack(cfn, stack_name)
+ assert updated["StackStatus"] == "UPDATE_COMPLETE", updated.get("StackStatusReason")
+ assert _rds_physical_ids(cfn, stack_name) == ids
+ after, _ = _rds_ids(ids, rds)
+ assert after["BackupRetentionPeriod"] == 2
+ assert {k: after[k] for k in _RDS_CLUSTER_IDENTITY} == {k: cluster[k] for k in _RDS_CLUSTER_IDENTITY}
+ assert [m["DBInstanceIdentifier"] for m in after["DBClusterMembers"]] == [ids["Member"]]
+ assert updated["Outputs"] == created["Outputs"]
+
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=json.dumps(_rds_cluster_stack(retention=2, tier=2)))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert _rds_physical_ids(cfn, stack_name) == ids
+ after, member_after = _rds_ids(ids, rds)
+ assert member_after["PromotionTier"] == 2
+ assert ({k: member_after[k] for k in _RDS_INSTANCE_IDENTITY}
+ == {k: member[k] for k in _RDS_INSTANCE_IDENTITY})
+ assert [m["PromotionTier"] for m in after["DBClusterMembers"]] == [2]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_update_rds_cluster_rolls_back_in_place(cfn, rds):
+ """A cluster change followed by a failing resource is sent back to the
+ previous value on the same cluster, with its member still listed."""
+ stack_name = f"cfn-rds-rb-{_uuid_mod.uuid4().hex[:8]}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_rds_cluster_stack()))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ ids = _rds_physical_ids(cfn, stack_name)
+ cluster, _ = _rds_ids(ids, rds)
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_with_failing_resource(
+ json.dumps(_rds_cluster_stack(retention=2)), "Cluster"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ after, _ = _rds_ids(ids, rds)
+ assert after["BackupRetentionPeriod"] == 1
+ assert {k: after[k] for k in _RDS_CLUSTER_IDENTITY} == {k: cluster[k] for k in _RDS_CLUSTER_IDENTITY}
+ assert [m["DBInstanceIdentifier"] for m in after["DBClusterMembers"]] == [ids["Member"]]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_update_rds_instance_in_place(cfn, rds):
+ """A standalone instance keeps its identity over a BackupRetentionPeriod change; a "false" string reads false."""
+ stack_name = f"cfn-rds-inst-{_uuid_mod.uuid4().hex[:8]}"
+
+ def template(retention):
+ return json.dumps({"Resources": {"Db": {
+ "Type": "AWS::RDS::DBInstance", "DeletionPolicy": "Delete", "Properties": {
+ "Engine": "postgres", "DBInstanceClass": "db.t4g.micro", "AllocatedStorage": "20",
+ "MasterUsername": "admin", "MasterUserPassword": "password123",
+ "StorageEncrypted": "false", "BackupRetentionPeriod": retention}}}})
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(1))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ db_id = _rds_physical_ids(cfn, stack_name)["Db"]
+ before = rds.describe_db_instances(DBInstanceIdentifier=db_id)["DBInstances"][0]
+ assert before["StorageEncrypted"] is False
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(2))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert _rds_physical_ids(cfn, stack_name)["Db"] == db_id
+ after = rds.describe_db_instances(DBInstanceIdentifier=db_id)["DBInstances"][0]
+ assert after["BackupRetentionPeriod"] == 2
+ assert {k: after[k] for k in _RDS_INSTANCE_IDENTITY} == {k: before[k] for k in _RDS_INSTANCE_IDENTITY}
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_update_rds_cluster_master_username_change_is_not_applied(cfn, rds):
+ """A cluster MasterUsername change completes without touching the cluster."""
+ stack_name = f"cfn-rds-user-{_uuid_mod.uuid4().hex[:8]}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_rds_cluster_stack()))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ ids = _rds_physical_ids(cfn, stack_name)
+ cluster, _ = _rds_ids(ids, rds)
+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(_rds_cluster_stack(MasterUsername="owner")))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ assert _rds_physical_ids(cfn, stack_name) == ids
+ after, _ = _rds_ids(ids, rds)
+ assert after["MasterUsername"] == "admin"
+ assert {k: after[k] for k in _RDS_CLUSTER_IDENTITY} == {k: cluster[k] for k in _RDS_CLUSTER_IDENTITY}
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
[email protected]("rtype,props,before,after", [
+ ("AWS::RDS::DBCluster", {}, "aurora-postgresql", "aurora-mysql"),
+ ("AWS::RDS::DBInstance", {"DBInstanceClass": "db.t4g.micro", "AllocatedStorage": "20"}, "postgres", "mysql"),
+])
+def test_cfn_update_rds_engine_change_replaces(cfn, rds, rtype, props, before, after):
+ """Engine is only conditionally create-only, yet under a generated
+ identifier an Engine change replaces the resource."""
+ stack_name = f"cfn-rds-eng-{_uuid_mod.uuid4().hex[:8]}"
+ cluster = rtype == "AWS::RDS::DBCluster"
+
+ def template(engine):
+ return json.dumps({"Resources": {"R": {"Type": rtype, "DeletionPolicy": "Delete", "Properties": {
+ "Engine": engine, "MasterUsername": "admin", "MasterUserPassword": "password123", **props}}}})
+
+ def describe():
+ physical_id = _rds_physical_ids(cfn, stack_name)["R"]
+ if cluster:
+ return rds.describe_db_clusters(DBClusterIdentifier=physical_id)["DBClusters"][0]
+ return rds.describe_db_instances(DBInstanceIdentifier=physical_id)["DBInstances"][0]
+
+ resource_id = "DbClusterResourceId" if cluster else "DbiResourceId"
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(before))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ old = describe()
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(after))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ new = describe()
+ assert new["Engine"] == after
+ assert new[resource_id] != old[resource_id]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_update_rds_cluster_keeps_values_the_template_did_not_change(cfn, rds):
+ """A stack update writes only the properties it changes, so a value set
+ through ModifyDBCluster stays."""
+ stack_name = f"cfn-rds-oob-{_uuid_mod.uuid4().hex[:8]}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_rds_cluster_stack()))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ ids = _rds_physical_ids(cfn, stack_name)
+ rds.modify_db_cluster(DBClusterIdentifier=ids["Cluster"], BackupRetentionPeriod=7, ApplyImmediately=True)
+ cfn.update_stack(StackName=stack_name,
+ TemplateBody=json.dumps(_rds_cluster_stack(CopyTagsToSnapshot=True)))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ after, _ = _rds_ids(ids, rds)
+ assert (after["CopyTagsToSnapshot"], after["BackupRetentionPeriod"]) == (True, 7)
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
[email protected]("rtype,name_prop,props,prop,values", [
+ ("AWS::RDS::DBCluster", "DBClusterIdentifier", {"Engine": "aurora-postgresql"}, "DatabaseName", ("one", "two")),
+ ("AWS::RDS::DBCluster", "DBClusterIdentifier", {}, "Engine", ("aurora-postgresql", "aurora-mysql")),
+ ("AWS::RDS::DBInstance", "DBInstanceIdentifier",
+ {"Engine": "postgres", "DBInstanceClass": "db.t4g.micro", "AllocatedStorage": "20"}, "DBName", ("one", "two")),
+])
+def test_cfn_update_rds_custom_named_create_only_change_is_refused(cfn, rtype, name_prop, props, prop, values):
+ """A create-only change under an explicit, unchanged identifier would
+ replace the resource, which CloudFormation refuses."""
+ name = f"cfn-rds-named-{_uuid_mod.uuid4().hex[:8]}"
+
+ def template(value):
+ return json.dumps({"Resources": {"R": {"Type": rtype, "DeletionPolicy": "Delete", "Properties": {
+ name_prop: name, "MasterUsername": "admin", "MasterUserPassword": "password123",
+ **props, prop: value}}}})
+
+ cfn.create_stack(StackName=name, TemplateBody=template(values[0]))
+ try:
+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ cfn.update_stack(StackName=name, TemplateBody=template(values[1]))
+ assert _wait_stack(cfn, name)["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE"
+ assert (f"CloudFormation cannot update a stack when a custom-named resource requires "
+ f"replacing. Rename {name} and update the stack again.") in _stack_event_reasons(cfn, name)
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
+def test_cfn_update_rds_cluster_create_only_change_replaces(cfn, rds):
+ """Under a generated identifier a DatabaseName change replaces the cluster."""
+ stack_name = f"cfn-rds-repl-{_uuid_mod.uuid4().hex[:8]}"
+
+ def template(db_name):
+ return json.dumps({"Resources": {"Cluster": {
+ "Type": "AWS::RDS::DBCluster", "DeletionPolicy": "Delete", "Properties": {
+ "Engine": "aurora-postgresql", "DatabaseName": db_name}}}})
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("one"))
+ try:
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"
+ cluster_id = _rds_physical_ids(cfn, stack_name)["Cluster"]
+ before = rds.describe_db_clusters(DBClusterIdentifier=cluster_id)["DBClusters"][0]
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("two"))
+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"
+ after = rds.describe_db_clusters(
+ DBClusterIdentifier=_rds_physical_ids(cfn, stack_name)["Cluster"])["DBClusters"][0]
+ assert after["DatabaseName"] == "two"
+ assert after["DbClusterResourceId"] != before["DbClusterResourceId"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_update_rds_cluster_saved_without_its_resource_id():
+ """A cluster record saved before the create stored DbClusterResourceId updates in place and gets one."""
+ from ministack.services import rds as _rds_store
+ handler = _RESOURCE_HANDLERS["AWS::RDS::DBCluster"]
+ stack_name = f"cfn-rds-saved-{_uuid_mod.uuid4().hex[:8]}"
+ old = {"Engine": "aurora-postgresql", "MasterUsername": "admin", "BackupRetentionPeriod": 1}
+ new = dict(old, BackupRetentionPeriod=2)
+ cluster_id, _ = handler["create"]("Cluster", old, stack_name)
+ try:
+ record = _rds_store._clusters[cluster_id]
+ for key in ("DbClusterResourceId", "EarliestRestorableTime", "LatestRestorableTime"):
+ record.pop(key)
+ physical_id, attrs = handler["update"](cluster_id, old, new, stack_name, "Cluster")
+ assert physical_id == cluster_id
+ assert record["BackupRetentionPeriod"] == 2
+ assert attrs["DBClusterResourceId"] == record["DbClusterResourceId"]
+ assert record["DbClusterResourceId"].startswith("cluster-")
+ assert record["LatestRestorableTime"] == record["ClusterCreateTime"]
+ finally:
+ handler["delete"](cluster_id, new)
+
def _template(resource_type, properties):
return {"Resources": {"R": {"Type": resource_type, "Properties": properties}}}
@@ -26367,6 +26626,13 @@ def _requirements(change):
("AWS::DynamoDB::Table", {"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}]},
{"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}, {"AttributeName": "sk", "KeyType": "RANGE"}]},
"Conditionally"),
+ ("AWS::RDS::DBCluster", {}, {"DatabaseName": "two"}, "Always"),
+ ("AWS::RDS::DBCluster", {"BackupRetentionPeriod": 1}, {"BackupRetentionPeriod": 2}, "Never"),
+ ("AWS::RDS::DBCluster", {"Engine": "aurora-postgresql"}, {"Engine": "aurora-mysql"}, "Conditionally"),
+ ("AWS::RDS::DBCluster", {}, {"Port": 5433}, "Never"),
+ ("AWS::RDS::DBInstance", {}, {"DBName": "two"}, "Always"),
+ ("AWS::RDS::DBInstance", {"BackupRetentionPeriod": 1}, {"BackupRetentionPeriod": 2}, "Conditionally"),
+ ("AWS::RDS::DBInstance", {"AllocatedStorage": "20"}, {"AllocatedStorage": "30"}, "Never"),
("AWS::Lambda::Function", {"DurableConfig": {"ExecutionTimeout": 60}},
{"DurableConfig": {"ExecutionTimeout": 120}}, "Conditionally"),
("AWS::Lambda::Function", {"DurableConfig": {"ExecutionTimeout": 60}}, {}, "Conditionally"),