mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(cloudformation): apply AssociatedRoles on RDS clusters and instances (#5656)
* feat(cloudformation): apply AssociatedRoles on RDS clusters and instances AWS::RDS::DBCluster and AWS::RDS::DBInstance ignored AssociatedRoles, so a CDK DatabaseCluster with s3ImportBuckets deployed with no role on the cluster. The roles are now associated when the resource is created, through the same checks as AddRoleToDBCluster and AddRoleToDBInstance; a list RDS refuses fails the resource and deletes the new database. An update adds the roles the template gained and removes the ones the previous template declared and this one drops, so a role associated outside the stack is kept. An Aurora cluster member carrying its own AssociatedRoles is a ValidationError, as the schema calls the property not applicable there. addRolesToNewDbCluster now also refuses a role named twice in its own list. Closes #5638 * fix(cloudformation): follow AWS on repeated roles, and check before changing a database A renamed instance's predecessor was deleted before the new instance took its roles, so a refused list left neither; the roles now go on first. The property is resolved before it is read, so Fn::If around the list or an entry works and AWS::NoValue leaves it out, and any other value that is not a list is a ValidationError rather than "no roles". Repeated roles follow AWS's handlers: an instance skips a role or feature already associated (AWS ignores DBInstanceRoleAlreadyExists), while a cluster's list is checked first on an update too, and a role the template newly declares is always added, so one attached by hand fails the update with DBClusterRoleAlreadyExists. A rolled back cluster replacement also restores the record of which roles the stack declared. * fix(cloudformation): undo a failed role update's own changes An update changed roles one at a time, so when a later step was refused the roles it had already added stayed on the database while the stack restored its old record, and a retry failed on them with DBClusterRoleAlreadyExists. A refused step now removes the roles the update added and puts back the ones it removed before the error is reported. The cluster check also takes the template's engine, now that it checks feature names, and the roles record reader catches only the JSON parse error.
This commit is contained in:
1 parent
f08a443ec9
commit
ad1b225591
5 files changed
+727
No files matched your search
+279
@@ -1,7 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
|
||||
@@ -14,6 +16,7 @@ import io.github.hectorvent.floci.services.rds.model.DbParameterGroup;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbProxy;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbProxyAuth;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbProxyTargetGroup;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbRoleAssociation;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -85,6 +88,18 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
*/
|
||||
static final String DB_CLUSTER_CREATE_ONLY_PRIOR_ATTR = "__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.
|
||||
*/
|
||||
static final String ASSOCIATED_ROLES_ATTR = "__FlociAssociatedRoles";
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
static final String ASSOCIATED_ROLES_PRIOR_ATTR = "__FlociAssociatedRolesPrior";
|
||||
|
||||
private final RdsService rdsService;
|
||||
private final CfnDynamicReferences dynamicReferences;
|
||||
|
||||
@@ -163,6 +178,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
resource.getAttributes().remove(DB_CLUSTER_CREATE_ONLY_PRIOR_ATTR);
|
||||
resource.getAttributes().remove(ASSOCIATED_ROLES_PRIOR_ATTR);
|
||||
ReplacementCleanup.clear(resource);
|
||||
}
|
||||
|
||||
@@ -184,6 +200,14 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
resource.getAttributes().put(DB_CLUSTER_CREATE_ONLY_ATTR, priorRecord);
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
return replaced;
|
||||
}
|
||||
|
||||
@@ -315,7 +339,16 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
// 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.
|
||||
List<DbRoleAssociation> roles = parseAssociatedRoles(props, engine);
|
||||
String clusterMember = resolveOptional(props, "DBClusterIdentifier", engine);
|
||||
if (!roles.isEmpty() && clusterMember != null && !clusterMember.isBlank()) {
|
||||
// The schema: "Amazon Aurora: Not applicable. The associated roles are managed by the DB cluster."
|
||||
throw new AwsException("ValidationError", "AssociatedRoles is not applicable to DB instance " + id
|
||||
+ ", a member of DB cluster " + clusterMember
|
||||
+ "; set AssociatedRoles on the AWS::RDS::DBCluster instead.", 400);
|
||||
}
|
||||
DbInstance instance = sameNameExistingResource(priorPhysicalId, id, rdsService::getDbInstance);
|
||||
boolean created = instance == null;
|
||||
if (instance != null) {
|
||||
instance = rdsService.modifyDbInstance(
|
||||
id,
|
||||
@@ -337,6 +370,11 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
resolveOptional(props, "DBSubnetGroupName", engine),
|
||||
resolveOptional(props, "DBClusterIdentifier", engine),
|
||||
null, false, false, null, Map.of(), region);
|
||||
}
|
||||
// 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) {
|
||||
deleteRenamedResource(priorPhysicalId, id, rdsService::deleteDbInstance, "DB instance");
|
||||
}
|
||||
r.setPhysicalId(instance.getDbInstanceIdentifier());
|
||||
@@ -400,6 +438,11 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
LOG.infov("Replacing DB cluster {0} with {1}: {2}", priorPhysicalId, id, replacementReason);
|
||||
cluster = null;
|
||||
}
|
||||
List<DbRoleAssociation> roles = parseAssociatedRoles(props, engine);
|
||||
if (!roles.isEmpty()) {
|
||||
rdsService.validateClusterRoleAssociations(id, resolveOptional(props, "Engine", engine), roles);
|
||||
}
|
||||
boolean created = cluster == null;
|
||||
if (cluster != null) {
|
||||
cluster = rdsService.modifyDbCluster(
|
||||
id,
|
||||
@@ -426,6 +469,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
serverlessV2MinCapacity, serverlessV2MaxCapacity, serverlessV2SecondsUntilAutoPause,
|
||||
false, null, engineMode, storageEncrypted);
|
||||
}
|
||||
cluster = reconcileClusterRoles(r, cluster, roles, created, ctx.isUpdate(), region);
|
||||
r.setPhysicalId(cluster.getDbClusterIdentifier());
|
||||
r.getAttributes().put("DBClusterIdentifier", cluster.getDbClusterIdentifier());
|
||||
if (cluster.getEndpoint() != null) {
|
||||
@@ -447,6 +491,241 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner {
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore);
|
||||
}
|
||||
|
||||
/**
|
||||
* The template's {@code AssociatedRoles}, in order, with {@code Fn::If} resolved around the list
|
||||
* and its entries. An absent property, or one that resolves to {@code AWS::NoValue}, is an empty
|
||||
* list; any other value that is not a list of objects is a {@code ValidationError}, so a
|
||||
* malformed property never reads as "no roles" and removes the ones the stack declared.
|
||||
*/
|
||||
private List<DbRoleAssociation> parseAssociatedRoles(JsonNode props, CloudFormationTemplateEngine engine) {
|
||||
List<DbRoleAssociation> roles = new ArrayList<>();
|
||||
if (props == null || !props.has("AssociatedRoles")) {
|
||||
return roles;
|
||||
}
|
||||
JsonNode list = engine.resolveNodeOmittingNoValue(props.get("AssociatedRoles"));
|
||||
if (list == null || list.isMissingNode()) {
|
||||
return roles;
|
||||
}
|
||||
if (!list.isArray()) {
|
||||
throw new AwsException("ValidationError", "AssociatedRoles must be a list of roles.", 400);
|
||||
}
|
||||
for (JsonNode role : list) {
|
||||
if (role == null || role.isMissingNode()) {
|
||||
continue;
|
||||
}
|
||||
if (!role.isObject()) {
|
||||
throw new AwsException("ValidationError",
|
||||
"Each AssociatedRoles entry must be an object with a RoleArn.", 400);
|
||||
}
|
||||
roles.add(new DbRoleAssociation(textOrNull(role.get("RoleArn")), textOrNull(role.get("FeatureName"))));
|
||||
}
|
||||
return roles;
|
||||
}
|
||||
|
||||
private static String textOrNull(JsonNode node) {
|
||||
return node == null || node.isNull() || node.isMissingNode() ? null : node.asText();
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings a cluster's roles in line with the template. A new cluster takes them all in one step,
|
||||
* and is deleted again if they are refused, so a failed resource leaves no cluster behind. On an
|
||||
* update the roles the last template declared and this one does not are removed, and the ones
|
||||
* this template adds are associated.
|
||||
*/
|
||||
private DbCluster reconcileClusterRoles(StackResource r, DbCluster cluster, List<DbRoleAssociation> roles,
|
||||
boolean created, boolean update, String region) {
|
||||
String id = cluster.getDbClusterIdentifier();
|
||||
if (created) {
|
||||
if (!roles.isEmpty()) {
|
||||
try {
|
||||
cluster = rdsService.addRolesToNewDbCluster(region, id, roles);
|
||||
} catch (AwsException e) {
|
||||
CfnDeletes.safeDelete("DB cluster", id, () -> rdsService.deleteDbCluster(id, region),
|
||||
"DBClusterNotFoundFault");
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
List<DbRoleAssociation> removed = new ArrayList<>();
|
||||
List<DbRoleAssociation> added = new ArrayList<>();
|
||||
try {
|
||||
List<DbRoleAssociation> current = cluster.getAssociatedRoles();
|
||||
for (DbRoleAssociation dropped : droppedRoles(r, roles)) {
|
||||
if (containsRole(current, dropped)) {
|
||||
cluster = rdsService.removeRoleFromDbCluster(region, id, dropped.getRoleArn(),
|
||||
dropped.getFeatureName());
|
||||
removed.add(dropped);
|
||||
}
|
||||
}
|
||||
// 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));
|
||||
for (DbRoleAssociation role : roles) {
|
||||
if (!containsRole(declared, role) || !containsRole(cluster.getAssociatedRoles(), role)) {
|
||||
cluster = rdsService.addRoleToDbCluster(region, id, role.getRoleArn(), role.getFeatureName());
|
||||
added.add(role);
|
||||
}
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
undoClusterRoleChanges(id, region, added, removed);
|
||||
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) {
|
||||
String id = instance.getDbInstanceIdentifier();
|
||||
if (created) {
|
||||
try {
|
||||
for (DbRoleAssociation role : roles) {
|
||||
instance = addInstanceRole(instance, id, role, region);
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
rdsService.deleteDbInstance(id, region);
|
||||
throw e;
|
||||
}
|
||||
} else {
|
||||
List<DbRoleAssociation> removed = new ArrayList<>();
|
||||
List<DbRoleAssociation> added = new ArrayList<>();
|
||||
try {
|
||||
List<DbRoleAssociation> current = instance.getAssociatedRoles();
|
||||
for (DbRoleAssociation dropped : droppedRoles(r, roles)) {
|
||||
if (containsRole(current, dropped)) {
|
||||
instance = rdsService.removeRoleFromDbInstance(region, id, dropped.getRoleArn(),
|
||||
dropped.getFeatureName());
|
||||
removed.add(dropped);
|
||||
}
|
||||
}
|
||||
for (DbRoleAssociation role : roles) {
|
||||
if (!containsRole(instance.getAssociatedRoles(), role)) {
|
||||
instance = addInstanceRole(instance, id, role, region);
|
||||
if (containsRole(instance.getAssociatedRoles(), role)) {
|
||||
added.add(role);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
undoInstanceRoleChanges(id, region, added, removed);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
recordAssociatedRoles(r, roles, update);
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts a cluster's roles back as they were before a failed update: the roles it added are
|
||||
* removed and the ones it removed are added again, so the cluster matches the record the stack
|
||||
* restores and a retry starts from there. A step that fails here is logged and the rest go on,
|
||||
* so the original refusal is what the stack reports.
|
||||
*/
|
||||
private void undoClusterRoleChanges(String id, String region, List<DbRoleAssociation> added,
|
||||
List<DbRoleAssociation> removed) {
|
||||
for (DbRoleAssociation role : added) {
|
||||
undoStep(() -> rdsService.removeRoleFromDbCluster(region, id, role.getRoleArn(), role.getFeatureName()),
|
||||
"remove", role, "DB cluster", id);
|
||||
}
|
||||
for (DbRoleAssociation role : removed) {
|
||||
undoStep(() -> rdsService.addRoleToDbCluster(region, id, role.getRoleArn(), role.getFeatureName()),
|
||||
"restore", role, "DB cluster", id);
|
||||
}
|
||||
}
|
||||
|
||||
/** As {@link #undoClusterRoleChanges}, for an instance. */
|
||||
private void undoInstanceRoleChanges(String id, String region, List<DbRoleAssociation> added,
|
||||
List<DbRoleAssociation> removed) {
|
||||
for (DbRoleAssociation role : added) {
|
||||
undoStep(() -> rdsService.removeRoleFromDbInstance(region, id, role.getRoleArn(), role.getFeatureName()),
|
||||
"remove", role, "DB instance", id);
|
||||
}
|
||||
for (DbRoleAssociation role : removed) {
|
||||
undoStep(() -> rdsService.addRoleToDbInstance(region, id, role.getRoleArn(), role.getFeatureName()),
|
||||
"restore", role, "DB instance", id);
|
||||
}
|
||||
}
|
||||
|
||||
private static void undoStep(Runnable step, String verb, DbRoleAssociation role, String kind, String id) {
|
||||
try {
|
||||
step.run();
|
||||
} catch (AwsException e) {
|
||||
LOG.warnv("Could not {0} role {1} on {2} {3} while undoing a failed update: {4}",
|
||||
verb, role.getRoleArn(), kind, id, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Associates one instance role. AWS's {@code AWS::RDS::DBInstance} handler ignores
|
||||
* {@code DBInstanceRoleAlreadyExists}, so a role or feature the list repeats, or one already on
|
||||
* the instance, is skipped rather than failing the resource.
|
||||
*/
|
||||
private DbInstance addInstanceRole(DbInstance instance, String id, DbRoleAssociation role, String region) {
|
||||
try {
|
||||
return rdsService.addRoleToDbInstance(region, id, role.getRoleArn(), role.getFeatureName());
|
||||
} catch (AwsException e) {
|
||||
if ("DBInstanceRoleAlreadyExists".equals(e.getErrorCode())) {
|
||||
return instance;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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))) {
|
||||
if (!containsRole(roles, previous)) {
|
||||
dropped.add(previous);
|
||||
}
|
||||
}
|
||||
return dropped;
|
||||
}
|
||||
|
||||
/** Whether {@code roles} holds {@code role}: the same RoleArn for the same feature, or both without one. */
|
||||
private static boolean containsRole(List<DbRoleAssociation> roles, DbRoleAssociation role) {
|
||||
return roles.stream().anyMatch(candidate -> Objects.equals(candidate.getRoleArn(), role.getRoleArn())
|
||||
&& Objects.equals(blankToNull(candidate.getFeatureName()), blankToNull(role.getFeatureName())));
|
||||
}
|
||||
|
||||
private static String blankToNull(String value) {
|
||||
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);
|
||||
}
|
||||
ArrayNode record = MAPPER.createArrayNode();
|
||||
for (DbRoleAssociation role : roles) {
|
||||
ObjectNode entry = record.addObject().put("RoleArn", role.getRoleArn());
|
||||
if (blankToNull(role.getFeatureName()) != null) {
|
||||
entry.put("FeatureName", role.getFeatureName());
|
||||
}
|
||||
}
|
||||
r.getAttributes().put(ASSOCIATED_ROLES_ATTR, record.toString());
|
||||
}
|
||||
|
||||
private static List<DbRoleAssociation> readAssociatedRoles(String raw) {
|
||||
List<DbRoleAssociation> roles = new ArrayList<>();
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return roles;
|
||||
}
|
||||
try {
|
||||
for (JsonNode entry : MAPPER.readTree(raw)) {
|
||||
roles.add(new DbRoleAssociation(entry.path("RoleArn").asText(null),
|
||||
entry.path("FeatureName").asText(null)));
|
||||
}
|
||||
} catch (JsonProcessingException e) {
|
||||
LOG.warnv("Ignoring unreadable AssociatedRoles record: {0}", raw);
|
||||
}
|
||||
return roles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Why the template's createOnly properties call for a replacement of the cluster on file, or
|
||||
* null when they describe it. {@code EngineMode}, {@code StorageEncrypted} and
|
||||
|
||||
@@ -9782,6 +9782,8 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
*/
|
||||
public synchronized DbCluster addRolesToNewDbCluster(String region, String clusterId,
|
||||
List<DbRoleAssociation> roles) {
|
||||
// The features are checked below against the cluster's own engine.
|
||||
validateClusterRoleAssociations(clusterId, null, roles);
|
||||
String effectiveRegion = effectiveRegion(region);
|
||||
DbCluster cluster = getDbCluster(clusterId, effectiveRegion);
|
||||
requireAvailableCluster(cluster, clusterId);
|
||||
|
||||
Reference in new issue
Block a user