fix(cloudformation): give a DB instance its security groups and encryption (#7867)

An AWS::RDS::DBInstance created through CloudFormation never received
its VPCSecurityGroups or StorageEncrypted, so describe-db-instances
showed neither. Both now reach the instance on create.

A stack update that changes the groups moves the instance to them in
place, and one that drops them puts a standalone instance on its VPC's
default group, as AWS does; a cluster member keeps its groups. A
rollback puts the previous groups back. StorageEncrypted can only be
set at create, so changing or dropping it replaces the instance: the
old one is deleted once the update commits and kept when it rolls
back. A custom-named instance refuses the change, as on AWS.

Part of #7603

The rollback test of a security group change now starts from two groups
and from none, as well as from one, so a saved list that kept only its
last group, or saved nothing for an instance that had none, fails it.
The line that saves the list now creates the array first, which reads
more plainly.

The docs and the encryption record's Javadoc now say that an instance
created before StorageEncrypted was applied, whose template sets it
through a parameter, does not see a change made only through that
parameter on its first update, as Ec2Tags.ownedKeys already notes for
tags.

The DB instance and DB cluster arms refuse a custom-named replacement
through CfnExceptions.customNamedReplacement, and the private copy is
gone.

The DB cluster's createOnly record and the AssociatedRoles record are
CreateOnlyInputs constants now, beside the DB instance's encryption
record, so all three are read, written, put back on a rollback and
cleared on commit through it. The attribute names are unchanged, so a
stack created before keeps its records, and an update that leaves the
cluster record as it was still saves no copy of it.

One thing changes with it: the roles record an update overwrites is now
saved every time, where it used to be saved only when no saved copy was
there. A committed in-place update used to leave that copy on the
resource, so a stack from then could have its roles record rolled back
to an older one by the first update that fails; a test covers it.

The encryption record's Javadoc and the docs now say that the previous
template resolves on the update, so a change made only through a
parameter, or anything else the update changes, is not seen.

An update whose template changed a cluster member's VPCSecurityGroups
moved the member to the new groups. On AWS the handler sends that change
to ModifyDBInstance and RDS refuses it for a member, whose groups are
its cluster's, so the update fails. It now fails the same way, with
InvalidParameterCombination and RDS's message, before anything on the
instance changes.

The change is read from the template, as AWS's handler reads it, so a
member whose list stays the same still updates, including one a stack
created before Floci applied the groups. Refusing the property outright
would fail a list that matches the cluster's, which the schema allows.
This commit is contained in:
Suja Shaj authored and GitHub committed 2026-11-11 00:49:50 -04:00
1 parent 3270066923
commit 3d3e94dcc6
10 files changed
+888 -168

No files matched your search

@@ -25,6 +25,7 @@ import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -39,8 +40,9 @@ import java.util.function.Function;
* Extracted from the former CloudFormation monolith.
*
* <p>Every type here deletes by physical id alone, so the id-only
* {@link #delete(String, String, String)} serves all seven. {@code DBCluster} is the one type that
* replaces through {@link ReplacementCleanup}; see {@code provisionDbCluster}.
* {@link #delete(String, String, String)} serves all seven. {@code DBCluster} and {@code DBInstance}
* are the types that replace through {@link ReplacementCleanup}; see {@code provisionDbCluster} and
* {@code provisionDbInstance}.
*
* <p>Unlike most extractions this one does not take {@code RdsService} out of the monolith.
* {@code AWS::SecretsManager::SecretTargetAttachment} is still served there and reads an
@@ -60,7 +62,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
* emulate a KMS key, public access, a subnet group placement chosen by the template or a
* restore source on a cluster, so a change to one of these can only be seen against what the
* template said last time. The values the last successful provision resolved are kept on the
* resource under {@link #DB_CLUSTER_CREATE_ONLY_ATTR}, which is how CloudFormation decides too:
* resource under {@link #DB_CLUSTER_CREATE_ONLY}, which is how CloudFormation decides too:
* on the template's change, not on the live entity.
*/
static final List<String> DB_CLUSTER_RECORDED_CREATE_ONLY = List.of(
@@ -82,26 +84,42 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
/**
* The recorded createOnly values of a DB cluster resource, a JSON object keyed by property.
* Internal, like the other {@code __Floci} attributes. A resource provisioned before these were
* recorded has none, and its first update records them without replacing anything.
* recorded has none, and its first update records them without replacing anything. The record
* an update overwrote is kept until the update commits, so a rollback puts it back beside the
* prior cluster.
*/
static final String DB_CLUSTER_CREATE_ONLY_ATTR = "__FlociDbClusterCreateOnly";
/**
* The record an update overwrote, kept until the update commits so a rollback puts it back
* beside the prior cluster; an empty value means there was no record before.
*/
static final String DB_CLUSTER_CREATE_ONLY_PRIOR_ATTR = "__FlociDbClusterCreateOnlyPrior";
private static final CreateOnlyInputs DB_CLUSTER_CREATE_ONLY = new CreateOnlyInputs(
"__FlociDbClusterCreateOnly", "__FlociDbClusterCreateOnlyPrior");
/**
* The {@code AssociatedRoles} the template declared at the last successful provision, a JSON
* array of {@code {RoleArn, FeatureName}}. An update removes only roles this record names and
* the template no longer does, so a role associated outside the stack is left in place.
* the template no longer does, so a role associated outside the stack is left in place. The
* record an update overwrote is kept until the update commits, so a rollback that puts the prior
* cluster or instance back puts its record back too.
*/
static final String ASSOCIATED_ROLES_ATTR = "__FlociAssociatedRoles";
private static final CreateOnlyInputs ASSOCIATED_ROLES = new CreateOnlyInputs(
"__FlociAssociatedRoles", "__FlociAssociatedRolesPrior");
/**
* The roles record an update overwrote, kept until the update commits so a rollback that puts
* the prior cluster back puts its record back too; an empty value means there was none.
* The {@code StorageEncrypted} a DB instance resource was last provisioned with, {@code true} or
* {@code false}. The property is createOnly, so an update that changes it replaces the instance.
* The change is read against this record, as CloudFormation reads the template's change, and not
* against the instance: one a stack created before Floci applied the property is unencrypted
* whatever its template said. Such a resource has no record, so its first update reads the
* previous template's value instead, resolved as well as it still can be, and replaces the
* instance only when that changed. As in {@link Ec2Tags#ownedKeys}, that template resolves on this
* update, so a value taken from a parameter, or from anything else the update changes, reads as the
* new one, and a change made only that way is not seen.
*/
static final String ASSOCIATED_ROLES_PRIOR_ATTR = "__FlociAssociatedRolesPrior";
private static final CreateOnlyInputs DB_INSTANCE_STORAGE_ENCRYPTED = new CreateOnlyInputs(
"__FlociDbInstanceStorageEncrypted", "__FlociDbInstanceStorageEncryptedPrior");
/**
* What an update that kept a DB instance needs for {@link #rollbackUpdate}: the region, the VPC
* security groups the instance had when the update changed them, and whether it changed anything
* else, which has no rollback here.
*/
static final String DB_INSTANCE_PRIOR_IN_PLACE_ATTR = "__FlociDbInstancePriorInPlaceUpdate";
private final RdsService rdsService;
private final CfnDynamicReferences dynamicReferences;
@@ -145,7 +163,8 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
@Override
public void delete(String resourceType, String physicalId, String region) {
switch (resourceType) {
case "AWS::RDS::DBInstance" -> rdsService.deleteDbInstance(physicalId, region);
case "AWS::RDS::DBInstance" -> CfnDeletes.safeDelete("DB instance", physicalId,
() -> rdsService.deleteDbInstance(physicalId, region), "DBInstanceNotFound");
case "AWS::RDS::DBCluster" -> CfnDeletes.safeDelete("DB cluster", physicalId,
() -> rdsService.deleteDbCluster(physicalId, region), "DBClusterNotFoundFault");
case "AWS::RDS::DBProxy" -> deleteDbProxySafe(physicalId, region);
@@ -159,8 +178,8 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
}
}
// ── replacement lifecycle: only AWS::RDS::DBCluster records one, so the other types answer
// "no cleanup owed" through ReplacementCleanup's own empty-record handling ──
// ── replacement lifecycle: only AWS::RDS::DBCluster and AWS::RDS::DBInstance record one, so the
// other types answer "no cleanup owed" through ReplacementCleanup's own empty-record handling ──
@Override
public boolean hasReplacementUpdate(StackResource resource) {
@@ -174,44 +193,82 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
resource.getAttributes().remove(DB_CLUSTER_CREATE_ONLY_PRIOR_ATTR);
// An in-place update owes no cleanup, so the engine calls clearUpdate only after a
// replacement: the records a rollback would have spent go here, or the next update's
// rollback would put back the ones this update replaced.
clearPriorRecords(resource);
return ReplacementCleanup.complete(resource, this::delete);
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(DB_CLUSTER_CREATE_ONLY_PRIOR_ATTR);
resource.getAttributes().remove(ASSOCIATED_ROLES_PRIOR_ATTR);
clearPriorRecords(resource);
ReplacementCleanup.clear(resource);
}
/**
* A replacement is undone through the cleanup record: the resource names the displaced cluster
* again and the replacement is deleted. The createOnly record follows the cluster back, since
* {@link ReplacementCleanup} leaves {@code __Floci} attributes alone. Without a record the
* update was in place, and putting that back needs a snapshot this provisioner does not keep,
* so the engine keeps reporting it as not rolled back, as before.
* or instance again and the replacement is deleted. The createOnly and roles records follow it
* back, since {@link ReplacementCleanup} leaves {@code __Floci} attributes alone, even when the
* replacement's delete fails, as the resource names the displaced one from then on. Without a
* record the update was in place: an instance's VPC security groups are put back, and the
* rollback counts as done when the update changed nothing else. Any other in-place change needs
* a snapshot this provisioner does not keep, so the engine keeps reporting it as not rolled back.
*/
@Override
public boolean rollbackUpdate(StackResource resource) {
boolean replaced = ReplacementCleanup.rollback(resource, this::delete);
String priorRecord = resource.getAttributes().remove(DB_CLUSTER_CREATE_ONLY_PRIOR_ATTR);
if (priorRecord != null) {
if (priorRecord.isEmpty()) {
resource.getAttributes().remove(DB_CLUSTER_CREATE_ONLY_ATTR);
} else {
resource.getAttributes().put(DB_CLUSTER_CREATE_ONLY_ATTR, priorRecord);
}
boolean replaced;
try {
replaced = ReplacementCleanup.rollback(resource, this::delete);
} finally {
restorePriorRecords(resource);
}
String priorRoles = resource.getAttributes().remove(ASSOCIATED_ROLES_PRIOR_ATTR);
if (priorRoles != null) {
if (priorRoles.isEmpty()) {
resource.getAttributes().remove(ASSOCIATED_ROLES_ATTR);
} else {
resource.getAttributes().put(ASSOCIATED_ROLES_ATTR, priorRoles);
}
if (replaced) {
resource.getAttributes().remove(DB_INSTANCE_PRIOR_IN_PLACE_ATTR);
return true;
}
return replaced;
return restoreDbInstanceInPlaceUpdate(resource);
}
private static void restorePriorRecords(StackResource resource) {
DB_CLUSTER_CREATE_ONLY.restorePrior(resource);
ASSOCIATED_ROLES.restorePrior(resource);
DB_INSTANCE_STORAGE_ENCRYPTED.restorePrior(resource);
}
private static void clearPriorRecords(StackResource resource) {
DB_CLUSTER_CREATE_ONLY.clearPrior(resource);
ASSOCIATED_ROLES.clearPrior(resource);
DB_INSTANCE_STORAGE_ENCRYPTED.clearPrior(resource);
resource.getAttributes().remove(DB_INSTANCE_PRIOR_IN_PLACE_ATTR);
}
/**
* Puts back the VPC security groups an update that kept the instance changed, and answers whether
* that undid the whole update. The saved record is dropped only once the groups are back, so an
* instance gone since the update fails the rollback, and a retried one tries again.
*/
private boolean restoreDbInstanceInPlaceUpdate(StackResource resource) {
String saved = resource.getAttributes().get(DB_INSTANCE_PRIOR_IN_PLACE_ATTR);
if (saved == null) {
return false;
}
JsonNode prior;
try {
prior = MAPPER.readTree(saved);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not read the saved in-place update of "
+ resource.getLogicalId(), e);
}
JsonNode groups = prior.path("vpcSecurityGroups");
if (groups.isArray()) {
List<String> groupIds = new ArrayList<>();
groups.forEach(group -> groupIds.add(group.asText()));
rdsService.setDbInstanceVpcSecurityGroups(prior.path("region").asText(), resource.getPhysicalId(),
groupIds);
}
resource.getAttributes().remove(DB_INSTANCE_PRIOR_IN_PLACE_ATTR);
return !prior.path("otherChanges").asBoolean(true);
}
private void provisionDbSubnetGroup(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
@@ -322,12 +379,22 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
r.getAttributes().put("DBClusterParameterGroupName", group.getDbClusterParameterGroupName());
}
/**
* A DB instance on file under the same id is updated in place, unless {@code StorageEncrypted},
* a createOnlyProperty of the {@code AWS::RDS::DBInstance} schema, changed (see
* {@link #DB_INSTANCE_STORAGE_ENCRYPTED}): the replacement is created under a distinct physical
* id and the displaced instance is deleted once the update commits, or kept when a later resource
* fails the update, as {@code provisionDbCluster} does for a cluster. A custom-named instance is
* refused that update, as CloudFormation refuses it.
*/
private void provisionDbInstance(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
ProvisionContext ctx, String region) {
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
String explicitId = resolveOptional(props, "DBInstanceIdentifier", engine);
String priorPhysicalId = r.getPhysicalId();
boolean customNamed = explicitId != null && !explicitId.isBlank();
String id;
if (explicitId != null && !explicitId.isBlank()) {
if (customNamed) {
id = explicitId;
} else if (priorPhysicalId != null) {
id = priorPhysicalId;
@@ -337,11 +404,10 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
// provision() is re-invoked on every UpdateStack for every resource, so a same-id instance
// already on file must be reconciled rather than re-created (createDbInstance throws
// DBInstanceAlreadyExists). Only password, IAM auth and subnet group are reconciled here.
// modifyDbInstance also takes DBInstanceClass, AllocatedStorage and EngineVersion now, but
// threading them through an UpdateStack is a separate change: DBInstanceClass and
// AllocatedStorage are update-in-place on the AWS::RDS::DBInstance schema while Engine is
// create-only, so passing them needs the replacement handling the DB cluster arm has.
// DBInstanceAlreadyExists). Password, IAM auth, subnet group, CA certificate, roles and VPC
// security groups are reconciled here. modifyDbInstance also takes DBInstanceClass,
// AllocatedStorage and EngineVersion now; threading them through an UpdateStack is a
// separate change.
List<DbRoleAssociation> roles = parseAssociatedRoles(props, engine);
String clusterMember = resolveOptional(props, "DBClusterIdentifier", engine);
if (!roles.isEmpty() && clusterMember != null && !clusterMember.isBlank()) {
@@ -350,9 +416,32 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
+ ", a member of DB cluster " + clusterMember
+ "; set AssociatedRoles on the AWS::RDS::DBCluster instead.", 400);
}
Boolean storageEncrypted = parseOptionalStrictBoolProp(props, "StorageEncrypted", engine);
String encryptionRecord = String.valueOf(Boolean.TRUE.equals(storageEncrypted));
List<String> vpcSecurityGroups = resolveStringList(props, "VPCSecurityGroups", engine);
DbInstance instance = sameNameExistingResource(priorPhysicalId, id, rdsService::getDbInstance);
String recordedEncryption = DB_INSTANCE_STORAGE_ENCRYPTED.read(attributesBefore);
if (recordedEncryption == null && instance != null && ctx.priorProperties() != null) {
recordedEncryption = String.valueOf(parseBoolProp(ctx.priorProperties(), "StorageEncrypted", engine));
}
boolean replacing = instance != null && recordedEncryption != null
&& !recordedEncryption.equals(encryptionRecord);
if (replacing) {
if (customNamed) {
throw CfnExceptions.customNamedReplacement(id);
}
id = ctx.generatePhysicalName(r.getLogicalId(), 60, true);
LOG.infov("Replacing DB instance {0} with {1}: StorageEncrypted {2} -> {3}",
priorPhysicalId, id, recordedEncryption, encryptionRecord);
instance = null;
}
boolean created = instance == null;
String caCertificate = resolveOptional(props, "CACertificateIdentifier", engine);
DbInstanceInPlaceState stateBefore = created ? null : DbInstanceInPlaceState.of(instance);
// Worked out before anything changes, so that nothing can fail between the changes a
// rollback cannot undo and the groups, which it can.
List<String> desiredGroups = created ? null
: desiredVpcSecurityGroups(vpcSecurityGroups, clusterMember, id, ctx);
if (instance != null) {
// A null region keeps the default-region lookup sameNameExistingResource made.
instance = rdsService.modifyDbInstance(
@@ -375,13 +464,16 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
resolveOptional(props, "DBParameterGroupName", engine),
resolveOptional(props, "DBSubnetGroupName", engine),
resolveOptional(props, "DBClusterIdentifier", engine),
null, false, false, null, Map.of(), List.of(), null, region, true,
DbInstanceSettings.defaults().withCaCertificateIdentifier(caCertificate));
null, false, false, null, Map.of(), vpcSecurityGroups, null, region, true,
new DbInstanceSettings(storageEncrypted, null, null, null, null, null)
.withCaCertificateIdentifier(caCertificate));
}
// The roles go on before a renamed instance's predecessor is deleted, so a refused list
// deletes only the new instance and the stack still has the old one to roll back to.
instance = reconcileInstanceRoles(r, instance, roles, created, ctx.isUpdate(), region);
if (created) {
// deletes only the new instance and the stack still has the old one to roll back to. A
// replaced instance is kept until the update commits instead.
instance = reconcileInstanceRoles(r, instance, roles, created, region);
ASSOCIATED_ROLES.record(r, ctx, attributesBefore, associatedRolesRecord(roles));
if (created && !replacing) {
deleteRenamedResource(priorPhysicalId, id, rdsService::deleteDbInstance, "DB instance");
}
r.setPhysicalId(instance.getDbInstanceIdentifier());
@@ -401,6 +493,101 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
if (ca.validTill() != null) {
r.getAttributes().put("CertificateDetails.ValidTill", ca.validTill().toString());
}
if (created) {
r.getAttributes().remove(DB_INSTANCE_PRIOR_IN_PLACE_ATTR);
} else {
reconcileInstanceSecurityGroups(r, instance, desiredGroups, stateBefore, ctx);
}
DB_INSTANCE_STORAGE_ENCRYPTED.record(r, ctx, attributesBefore, encryptionRecord);
// A provision that left the resource with a new physical id for its StorageEncrypted replaced
// the instance: the displaced one is deleted once the update commits, or kept if it rolls back.
ReplacementCleanup.record(r, ctx, attributesBefore, replacing);
}
/**
* The VPC security groups a kept instance should have, or null to leave them as they are. A
* declared list is the groups, but a cluster member's groups are its cluster's: a template that
* changes a member's list fails the update, as on AWS, where the handler sends the change to
* ModifyDBInstance and RDS refuses it for a member. The change is read from the template, as
* there, so a member a stack created before Floci applied the list still takes it. A list the
* previous template declared and this one drops puts a standalone instance on its VPC's default
* security group, as AWS's handler does, and leaves them when there is no such group, as there; a
* cluster member keeps its groups, as there too. A list the stack never declared leaves groups set
* outside it alone.
*/
private List<String> desiredVpcSecurityGroups(List<String> declared, String clusterMember, String id,
ProvisionContext ctx) {
boolean member = clusterMember != null && !clusterMember.isBlank();
if (!declared.isEmpty()) {
if (member && ctx.priorProperties() != null && !Set.copyOf(declared).equals(
Set.copyOf(resolveStringList(ctx.priorProperties(), "VPCSecurityGroups", ctx.engine())))) {
throw new AwsException("InvalidParameterCombination", "The specified DB Instance is a member of a"
+ " cluster. Modify vpc security group for the DB Cluster using the ModifyDbCluster API", 400);
}
return declared;
}
if (!ctx.previouslyDeclared("VPCSecurityGroups") || member) {
return null;
}
List<String> defaultGroup = rdsService.defaultVpcSecurityGroupIds(ctx.region(), id);
return defaultGroup.isEmpty() ? null : defaultGroup;
}
/**
* Brings a kept instance's VPC security groups to {@code desired}, the last change of the update:
* when an earlier step fails, the engine restores the resource without calling
* {@link #rollbackUpdate}, so only a change made after every other one can be put back there.
* What the instance had is saved first, with whether the update changed anything else, for
* {@link #rollbackUpdate}.
*/
private void reconcileInstanceSecurityGroups(StackResource r, DbInstance instance, List<String> desired,
DbInstanceInPlaceState stateBefore, ProvisionContext ctx) {
String id = instance.getDbInstanceIdentifier();
List<String> groupsBefore = stateBefore.vpcSecurityGroups();
boolean groupsChange = desired != null && !Set.copyOf(desired).equals(Set.copyOf(groupsBefore));
ObjectNode saved = MAPPER.createObjectNode().put("region", ctx.region());
if (groupsChange) {
ArrayNode priorGroups = saved.putArray("vpcSecurityGroups");
groupsBefore.forEach(priorGroups::add);
}
saved.put("otherChanges", !stateBefore.sameSettingsAs(DbInstanceInPlaceState.of(instance)));
r.getAttributes().put(DB_INSTANCE_PRIOR_IN_PLACE_ATTR, saved.toString());
if (groupsChange) {
rdsService.setDbInstanceVpcSecurityGroups(ctx.region(), id, desired);
}
}
/**
* What an update that keeps a DB instance can change on it: the settings it hands
* {@code modifyDbInstance}, the roles, and the VPC security groups, copied so the instance's later
* changes do not reach them. Only the groups have a rollback here.
*/
private record DbInstanceInPlaceState(String masterPassword, boolean iamAuthentication, String subnetGroup,
String caCertificate, Set<String> roles, List<String> vpcSecurityGroups) {
static DbInstanceInPlaceState of(DbInstance instance) {
Set<String> roles = new HashSet<>();
for (DbRoleAssociation role : instance.getAssociatedRoles()) {
roles.add(role.getRoleArn() + " " + blankToNull(role.getFeatureName()));
}
return new DbInstanceInPlaceState(instance.getMasterPassword(),
instance.isIamDatabaseAuthenticationEnabled(), instance.getDbSubnetGroupName(),
instance.getCaCertificateIdentifier(), roles, List.copyOf(instance.getVpcSecurityGroupIds()));
}
/** Whether {@code other} has the same settings and roles, whatever its groups. */
boolean sameSettingsAs(DbInstanceInPlaceState other) {
return Objects.equals(masterPassword, other.masterPassword)
&& iamAuthentication == other.iamAuthentication
&& Objects.equals(subnetGroup, other.subnetGroup)
&& Objects.equals(caCertificate, other.caCertificate)
&& roles.equals(other.roles);
}
@Override
public String toString() {
return "DbInstanceInPlaceState[groups=" + vpcSecurityGroups + "]";
}
}
/**
@@ -430,8 +617,8 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
id = ctx.generatePhysicalName(r.getLogicalId(), 60, true);
}
// Same re-invocation rationale as provisionDbInstance above; modifyDbCluster only reconciles
// password and IAM auth, mirroring that method's existing scope.
// Same re-invocation rationale as provisionDbInstance above; modifyDbCluster reconciles the
// password, IAM auth and the Serverless v2 scaling.
DbCluster cluster = sameNameExistingResource(priorPhysicalId, id, rdsService::getDbCluster);
String engineMode = resolveOptional(props, "EngineMode", engine);
boolean storageEncrypted = parseBoolProp(props, "StorageEncrypted", engine);
@@ -439,12 +626,10 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
Map<String, String> createOnly = dbClusterRecordedCreateOnly(props, engine);
String replacementReason = cluster == null ? null : dbClusterReplacementReason(cluster,
engineMode, storageEncrypted, databaseName,
readDbClusterCreateOnly(attributesBefore.get(DB_CLUSTER_CREATE_ONLY_ATTR)), createOnly);
readDbClusterCreateOnly(DB_CLUSTER_CREATE_ONLY.read(attributesBefore)), createOnly);
if (replacementReason != null) {
if (customNamed) {
throw new AwsException("ValidationError",
"CloudFormation cannot update a stack when a custom-named resource requires "
+ "replacing. Rename " + id + " and update the stack again.", 400);
throw CfnExceptions.customNamedReplacement(id);
}
id = ctx.generatePhysicalName(r.getLogicalId(), 60, true);
LOG.infov("Replacing DB cluster {0} with {1}: {2}", priorPhysicalId, id, replacementReason);
@@ -486,7 +671,8 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
serverlessV2MinCapacity, serverlessV2MaxCapacity, serverlessV2SecondsUntilAutoPause,
false, null, engineMode, storageEncrypted);
}
cluster = reconcileClusterRoles(r, cluster, roles, created, ctx.isUpdate(), region);
cluster = reconcileClusterRoles(r, cluster, roles, created, region);
ASSOCIATED_ROLES.record(r, ctx, attributesBefore, associatedRolesRecord(roles));
// EnableHttpEndpoint updates with no interruption; a template that leaves it out wants it off.
if (httpEndpoint != cluster.isHttpEndpointEnabled()) {
cluster = rdsService.setHttpEndpoint(region, cluster.getDbClusterIdentifier(), httpEndpoint);
@@ -554,7 +740,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
* this template adds are associated.
*/
private DbCluster reconcileClusterRoles(StackResource r, DbCluster cluster, List<DbRoleAssociation> roles,
boolean created, boolean update, String region) {
boolean created, String region) {
String id = cluster.getDbClusterIdentifier();
if (created) {
if (!roles.isEmpty()) {
@@ -581,7 +767,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
// A role the last template already declared is left as it is. One the template newly
// declares is always added, so a role attached by hand first fails the update with
// DBClusterRoleAlreadyExists, as it does on AWS.
List<DbRoleAssociation> declared = readAssociatedRoles(r.getAttributes().get(ASSOCIATED_ROLES_ATTR));
List<DbRoleAssociation> declared = readAssociatedRoles(ASSOCIATED_ROLES.read(r.getAttributes()));
for (DbRoleAssociation role : roles) {
if (!containsRole(declared, role) || !containsRole(cluster.getAssociatedRoles(), role)) {
cluster = rdsService.addRoleToDbCluster(region, id, role.getRoleArn(), role.getFeatureName());
@@ -593,13 +779,12 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
throw e;
}
}
recordAssociatedRoles(r, roles, update);
return cluster;
}
/** As {@link #reconcileClusterRoles}, for an instance; each role is added on its own. */
private DbInstance reconcileInstanceRoles(StackResource r, DbInstance instance, List<DbRoleAssociation> roles,
boolean created, boolean update, String region) {
boolean created, String region) {
String id = instance.getDbInstanceIdentifier();
if (created) {
try {
@@ -635,7 +820,6 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
throw e;
}
}
recordAssociatedRoles(r, roles, update);
return instance;
}
@@ -698,7 +882,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
/** The roles the last template declared that this one does not. */
private static List<DbRoleAssociation> droppedRoles(StackResource r, List<DbRoleAssociation> roles) {
List<DbRoleAssociation> dropped = new ArrayList<>();
for (DbRoleAssociation previous : readAssociatedRoles(r.getAttributes().get(ASSOCIATED_ROLES_ATTR))) {
for (DbRoleAssociation previous : readAssociatedRoles(ASSOCIATED_ROLES.read(r.getAttributes()))) {
if (!containsRole(roles, previous)) {
dropped.add(previous);
}
@@ -716,11 +900,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
return value == null || value.isBlank() ? null : value;
}
private static void recordAssociatedRoles(StackResource r, List<DbRoleAssociation> roles, boolean update) {
String priorRecord = r.getAttributes().get(ASSOCIATED_ROLES_ATTR);
if (update && !r.getAttributes().containsKey(ASSOCIATED_ROLES_PRIOR_ATTR)) {
r.getAttributes().put(ASSOCIATED_ROLES_PRIOR_ATTR, priorRecord == null ? "" : priorRecord);
}
private static String associatedRolesRecord(List<DbRoleAssociation> roles) {
ArrayNode record = MAPPER.createArrayNode();
for (DbRoleAssociation role : roles) {
ObjectNode entry = record.addObject().put("RoleArn", role.getRoleArn());
@@ -728,7 +908,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
entry.put("FeatureName", role.getFeatureName());
}
}
r.getAttributes().put(ASSOCIATED_ROLES_ATTR, record.toString());
return record.toString();
}
private static List<DbRoleAssociation> readAssociatedRoles(String raw) {
@@ -809,20 +989,21 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
}
/**
* Writes the createOnly record the next update compares against. On an update that changed it
* (a replacement, or the first record of a resource that predates it) the previous record is
* kept beside it until the update commits, so {@link #rollbackUpdate} can put it back.
* Writes the createOnly record the next update compares against. An update that leaves it as it
* was writes nothing. One that changed it (a replacement, or the first record of a resource that
* predates it) keeps the previous record beside it until the update commits, so
* {@link #rollbackUpdate} can put it back.
*/
private static void recordDbClusterCreateOnly(StackResource r, ProvisionContext ctx,
Map<String, String> attributesBefore,
Map<String, String> createOnly) {
String priorRecord = attributesBefore.get(DB_CLUSTER_CREATE_ONLY_ATTR);
if (ctx.isUpdate() && !createOnly.equals(readDbClusterCreateOnly(priorRecord))) {
r.getAttributes().put(DB_CLUSTER_CREATE_ONLY_PRIOR_ATTR, priorRecord == null ? "" : priorRecord);
Map<String, String> recorded = readDbClusterCreateOnly(DB_CLUSTER_CREATE_ONLY.read(attributesBefore));
if (ctx.isUpdate() && createOnly.equals(recorded)) {
return;
}
ObjectNode record = MAPPER.createObjectNode();
createOnly.forEach(record::put);
r.getAttributes().put(DB_CLUSTER_CREATE_ONLY_ATTR, record.toString());
DB_CLUSTER_CREATE_ONLY.record(r, ctx, attributesBefore, record.toString());
}
/** The record as a map, or null when the resource carries none or it cannot be read. */
@@ -1090,12 +1271,17 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
* {@code ValidationError} rather than a silent false.
*/
private boolean parseStrictBoolProp(JsonNode props, String name, CloudFormationTemplateEngine engine) {
return Boolean.TRUE.equals(parseOptionalStrictBoolProp(props, name, engine));
}
/** As {@link #parseStrictBoolProp}, with null for a property the template leaves out. */
private Boolean parseOptionalStrictBoolProp(JsonNode props, String name, CloudFormationTemplateEngine engine) {
if (props == null || !props.has(name)) {
return false;
return null;
}
JsonNode value = engine.resolveNodeOmittingNoValue(props.get(name));
if (value == null || value.isMissingNode() || value.isNull()) {
return false;
return null;
}
if (value.isBoolean()) {
return value.booleanValue();
@@ -3968,6 +3968,38 @@ public class RdsService implements Resettable, ResourceProvider {
return instance;
}
/**
* Gives a DB instance exactly the VPC security groups {@code groupIds}, as CloudFormation sets
* them on an update and puts them back on a rollback. ModifyDBInstance keeps the groups when the
* request names none; here an empty list leaves the instance with none, as one created without.
*/
public synchronized DbInstance setDbInstanceVpcSecurityGroups(String region, String instanceId,
List<String> groupIds) {
String effectiveRegion = effectiveRegion(region);
DbInstance instance = getDbInstance(instanceId, effectiveRegion);
requireAvailableInstance(instance, instanceId);
instance.setVpcSecurityGroupIds(groupIds);
putInstanceForScope(currentAccountId(), effectiveRegion, instanceId, instance);
LOG.infov("DB instance {0} security groups set to {1}", instanceId, groupIds);
return RESPONSE_COPIER.convertValue(instance, DbInstance.class);
}
/**
* The groups AWS's CloudFormation handler gives a standalone DB instance whose template stops
* declaring {@code VPCSecurityGroups}: the default security group of its VPC, or none when EC2
* has no default group for it.
*/
public List<String> defaultVpcSecurityGroupIds(String region, String instanceId) {
String effectiveRegion = effectiveRegion(region);
String vpcId = getDbInstance(instanceId, effectiveRegion).getVpcId();
if (isBlank(vpcId)) {
return List.of();
}
return ec2Service.defaultSecurityGroupOf(effectiveRegion, vpcId)
.map(group -> List.of(group.getGroupId()))
.orElse(List.of());
}
private static void validateInstanceSettings(DbInstanceSettings settings) {
settings.validate();
}