fix(cloudformation): skip unchanged resources during updates (#4442)

* fix(cloudformation): skip unchanged resources during updates

* fix(cloudformation): refresh dependent resources during updates (#4442)

* fix(cloudformation): support SQS rollback and scope dependent updates to replaced resources

- Implement replacement and in-place update rollback in SqsCfnProvisioner

- Scope dependent updates during stack update to only resources depending on replaced resources

- Compute and include dependent modified resources in ChangeSets to align DescribeChangeSet with execution

- Prevent unmodified resources such as S3 buckets from losing configuration when referenced resources update in-place

* fix(cloudformation): load create-only properties from schemas and handle condition changes

* fix(cloudformation): skip resources on outputs-only update and include create-only schema in native image

* fix(cloudformation): accurately assert unchanged queue events on outputs-only update

* fix(cloudformation): supply location constraint when creating nested stack templates bucket

* fix(cloudformation): revisit dependents on attribute changes and treat empty schema create-only lists as authoritative

* fix(cloudformation): preview in-place attribute dependents in changesets and support ASG rollback

- Include dependents of in-place modified resources with changed attributes in ChangeSet previews

- Snapshot and roll back in-place AutoScalingGroup updates on stack failure

- Implement LaunchTemplate update rollback to cleanly unwind launch template versions

* fix(cloudformation): restore ASG defaults during rollback

* fix(cloudformation): skip unchanged resources for empty updates

* fix(cloudformation): reconcile resources on identical updates and tolerate null attributes

* fix(cloudformation): skip unchanged resources on identical updates
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-01 23:05:38 -04:00
1 parent 2170c89d88
commit 60985b9a80
20 files changed
+2644 -9

No files matched your search

@@ -0,0 +1,68 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jboss.logging.Logger;
import java.io.InputStream;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
/**
* Registry of schema-defined createOnlyProperties for CloudFormation resource types.
*/
public final class CfnCreateOnlyProperties {
private static final Logger LOG = Logger.getLogger(CfnCreateOnlyProperties.class);
private static final String RESOURCE_NAME = "cloudformation/create-only-properties.json";
private static final Map<String, Set<String>> PROPERTIES = load();
private CfnCreateOnlyProperties() {
}
private static Map<String, Set<String>> load() {
try (InputStream in = CfnCreateOnlyProperties.class.getClassLoader().getResourceAsStream(RESOURCE_NAME)) {
if (in == null) {
LOG.warnv("Resource {0} not found on classpath", RESOURCE_NAME);
return Collections.emptyMap();
}
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(in, new TypeReference<Map<String, Set<String>>>() {});
} catch (Exception e) {
LOG.warnv(e, "Failed to load {0}", RESOURCE_NAME);
return Collections.emptyMap();
}
}
public static boolean isCreateOnly(String resourceType, String propertyName) {
Set<String> createOnly = PROPERTIES.get(resourceType);
if (createOnly != null) {
// The schema list is authoritative for this resource type, including when it is empty.
if (createOnly.contains(propertyName)) {
return true;
}
for (String prop : createOnly) {
if (prop.startsWith(propertyName + "/")) {
return true;
}
}
return false;
}
if ("Name".equals(propertyName)
|| propertyName.endsWith("Identifier")
|| "FifoQueue".equals(propertyName)
|| "FifoTopic".equals(propertyName)) {
return true;
}
String typeSuffix = resourceType.contains("::")
? resourceType.substring(resourceType.lastIndexOf("::") + 2)
: resourceType;
return propertyName.equals(typeSuffix + "Name");
}
public static Set<String> getCreateOnlyProperties(String resourceType) {
return PROPERTIES.getOrDefault(resourceType, Collections.emptySet());
}
}
@@ -54,6 +54,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* CloudFormation stack lifecycle management — Create, Update, Delete stacks via ChangeSets.
@@ -474,6 +475,7 @@ public class CloudFormationService implements ResourceProvider {
return List.of();
}
Stack stack = getStackOrThrow(cs.getStackName(), region);
String accountId = ownerAccount(stack);
try {
JsonNode newTemplate = parseTemplate(cs.getTemplateBody());
// Merge Fn::Transform/AWS::Include snippets before SAM expansion, matching AWS order:
@@ -488,9 +490,12 @@ public class CloudFormationService implements ResourceProvider {
JsonNode newResources = newTemplate.path("Resources");
boolean createType = "CREATE".equalsIgnoreCase(cs.getChangeSetType())
|| stack.getTemplateBody() == null;
JsonNode oldResources = createType
? objectMapper.createObjectNode()
: parseTemplate(stack.getTemplateBody()).path("Resources");
JsonNode oldTemplate = createType
? null
: parseTemplate(stack.getTemplateBody());
JsonNode oldResources = oldTemplate != null
? oldTemplate.path("Resources")
: objectMapper.createObjectNode();
Map<String, String> oldParams = stack.parametersSnapshot();
// Prefer the SSM-resolved values captured by the last executeTemplate run; fall back to
@@ -537,11 +542,25 @@ public class CloudFormationService implements ResourceProvider {
// deleteRemovedOrConditionFalseResources), so the preview must evaluate Conditions too
// rather than only scanning each resource's own Ref/Sub usage. A resource is "active" in
// the deployed stack precisely when it's present in stack.getResources() - the same
// ground truth execution uses - so no separate old-conditions evaluation is needed.
Map<String, Boolean> oldConditions = oldTemplate != null
? resolveConditions(oldTemplate, oldResolvedParams, stack, region, regionResolver.getAccountId())
: Map.of();
Map<String, Boolean> newConditions = resolveConditions(
newTemplate, newResolvedParams, null, region, regionResolver.getAccountId());
Set<String> changedConditions = new HashSet<>();
newConditions.forEach((name, val) -> {
if (!Objects.equals(val, oldConditions.get(name))) {
changedConditions.add(name);
}
});
oldConditions.forEach((name, val) -> {
if (!newConditions.containsKey(name)) {
changedConditions.add(name);
}
});
Set<String> deployedIds = stack.resourcesSnapshot().keySet();
Set<String> replacedResourceIds = new HashSet<>();
List<ResourceChange> changes = new ArrayList<>();
newResources.fields().forEachRemaining(e -> {
String logicalId = e.getKey();
@@ -568,11 +587,19 @@ public class CloudFormationService implements ResourceProvider {
// it now.
changes.add(new ResourceChange("Add", logicalId, null, resourceType, null));
} else if (newActive
&& (!oldDef.equals(newDef) || referencesAnyParameter(newDef, changedParams))) {
&& (!oldDef.equals(newDef)
|| ("AWS::CloudFormation::Stack".equals(resourceType) && isNestedStackChanged(stack, logicalId, newDef, region, accountId))
|| referencesAnyParameter(newDef, changedParams)
|| referencesAnyCondition(newDef, changedConditions))) {
boolean typeChanged = !oldDef.path("Type").asText().equals(resourceType);
boolean replacement = typeChanged
|| requiresReplacement(resourceType, oldDef.path("Properties"), newDef.path("Properties"), changedParams, changedConditions);
if (replacement) {
replacedResourceIds.add(logicalId);
}
changes.add(new ResourceChange("Modify", logicalId,
resourcePhysicalId(stack, logicalId), resourceType,
typeChanged ? "True" : "False"));
replacement ? "True" : "False"));
}
});
oldResources.fields().forEachRemaining(e -> {
@@ -582,6 +609,96 @@ public class CloudFormationService implements ResourceProvider {
e.getValue().path("Type").asText(), null));
}
});
Set<String> alreadyChangedIds = changes.stream()
.map(ResourceChange::logicalResourceId)
.collect(Collectors.toCollection(LinkedHashSet::new));
Map<String, Set<String>> inPlaceChangedAttributes = new HashMap<>();
for (ResourceChange change : changes) {
if ("Modify".equals(change.action()) && !replacedResourceIds.contains(change.logicalResourceId())) {
String logicalId = change.logicalResourceId();
JsonNode oldDef = oldResources.get(logicalId);
JsonNode newDef = newResources.get(logicalId);
String resourceType = newDef != null ? newDef.path("Type").asText() : "";
Set<String> attrs = expectedChangedAttributes(resourceType, oldDef, newDef);
if (!attrs.isEmpty()) {
inPlaceChangedAttributes.put(logicalId, attrs);
}
}
}
if (!replacedResourceIds.isEmpty() || !inPlaceChangedAttributes.isEmpty()) {
Set<String> allResourceIds = new LinkedHashSet<>();
newResources.fieldNames().forEachRemaining(allResourceIds::add);
List<String> sortedLogicalIds = topologicalSort(newResources, newConditions);
boolean anyNewChange = true;
while (anyNewChange) {
anyNewChange = false;
for (String logicalId : sortedLogicalIds) {
JsonNode newDef = newResources.get(logicalId);
String newConditionName = newDef.path("Condition").asText(null);
boolean newActive = newConditionName == null
|| newConditions.getOrDefault(newConditionName, false);
if (!newActive || !deployedIds.contains(logicalId)) {
continue;
}
Set<String> propertyDependencies = new LinkedHashSet<>();
collectDependencies(newDef.path("Properties"), allResourceIds, propertyDependencies, newConditions);
boolean dependsOnReplaced = propertyDependencies.stream().anyMatch(replacedResourceIds::contains);
boolean referencesChangedAttr = false;
if (!dependsOnReplaced) {
for (Map.Entry<String, Set<String>> entry : inPlaceChangedAttributes.entrySet()) {
if (referencesAnyAttribute(newDef.path("Properties"), entry.getKey(), entry.getValue(), newConditions)) {
referencesChangedAttr = true;
break;
}
}
}
if (dependsOnReplaced || referencesChangedAttr) {
String resourceType = newDef.path("Type").asText();
JsonNode oldDef = oldResources.get(logicalId);
boolean typeChanged = oldDef != null && !oldDef.path("Type").asText().equals(resourceType);
boolean createOnlyReferencesReplaced = false;
JsonNode props = newDef.path("Properties");
if (props != null && props.isObject()) {
for (Iterator<String> it = props.fieldNames(); it.hasNext(); ) {
String field = it.next();
if (CfnCreateOnlyProperties.isCreateOnly(resourceType, field)) {
Set<String> fieldDeps = new LinkedHashSet<>();
collectDependencies(props.get(field), allResourceIds, fieldDeps, newConditions);
if (fieldDeps.stream().anyMatch(replacedResourceIds::contains)) {
createOnlyReferencesReplaced = true;
break;
}
}
}
}
boolean replacement = typeChanged
|| (oldDef != null && requiresReplacement(resourceType, oldDef.path("Properties"), newDef.path("Properties"), changedParams, changedConditions))
|| createOnlyReferencesReplaced;
if (replacement && replacedResourceIds.add(logicalId)) {
anyNewChange = true;
}
if (!alreadyChangedIds.contains(logicalId)) {
alreadyChangedIds.add(logicalId);
changes.add(new ResourceChange("Modify", logicalId,
resourcePhysicalId(stack, logicalId), resourceType,
replacement ? "True" : "False"));
anyNewChange = true;
Set<String> attrs = expectedChangedAttributes(resourceType, oldDef, newDef);
if (!attrs.isEmpty()) {
inPlaceChangedAttributes.put(logicalId, attrs);
}
}
}
}
}
}
return changes;
} catch (AwsException e) {
throw e;
@@ -606,6 +723,49 @@ public class CloudFormationService implements ResourceProvider {
return false;
}
/** True if a resource's definition references any of the given condition names. */
private boolean referencesAnyCondition(JsonNode resourceDef, Set<String> conditionNames) {
if (conditionNames.isEmpty()) {
return false;
}
String json = resourceDef.toString();
for (String name : conditionNames) {
if (json.contains("\"Condition\":\"" + name + "\"")
|| json.contains("\"Fn::If\":[\"" + name + "\"")
|| json.contains("[\"" + name + "\"")) {
return true;
}
}
return false;
}
private boolean requiresReplacement(String resourceType, JsonNode oldProps, JsonNode newProps,
Set<String> changedParams, Set<String> changedConditions) {
if (oldProps == null || newProps == null || oldProps.isMissingNode() || newProps.isMissingNode()) {
return false;
}
for (Iterator<String> it = newProps.fieldNames(); it.hasNext(); ) {
String field = it.next();
if (CfnCreateOnlyProperties.isCreateOnly(resourceType, field)) {
JsonNode oldVal = oldProps.get(field);
JsonNode newVal = newProps.get(field);
if (oldVal != null && !oldVal.equals(newVal)) {
return true;
}
if (newVal != null && (referencesAnyParameter(newVal, changedParams) || referencesAnyCondition(newVal, changedConditions))) {
return true;
}
}
}
for (Iterator<String> it = oldProps.fieldNames(); it.hasNext(); ) {
String field = it.next();
if (CfnCreateOnlyProperties.isCreateOnly(resourceType, field) && !newProps.has(field)) {
return true;
}
}
return false;
}
public record ResourceChange(String action, String logicalResourceId, String physicalResourceId,
String resourceType, String replacement) {}
@@ -1249,6 +1409,9 @@ public class CloudFormationService implements ResourceProvider {
boolean updateCommitted = false;
Set<String> attemptedResourceIds = new LinkedHashSet<>();
try {
Set<String> changedResourceIds = isCreate
? Set.of()
: changedResourceIds(stack, templateBody, params, region);
JsonNode template = parseTemplate(templateBody);
stack.setOriginalTemplateBody(templateBody);
@@ -1295,7 +1458,7 @@ public class CloudFormationService implements ResourceProvider {
Map<String, Map<String, String>> resourceAttrs = new LinkedHashMap<>();
// First pass: collect existing physicalIds
for (var r : stack.resourcesSnapshot().values()) {
for (StackResource r : stack.resourcesSnapshot().values()) {
if (r.getPhysicalId() != null) {
physicalIds.put(r.getLogicalId(), r.getPhysicalId());
resourceAttrs.put(r.getLogicalId(), r.getAttributes());
@@ -1307,6 +1470,9 @@ public class CloudFormationService implements ResourceProvider {
List<String> sortedLogicalIds = topologicalSort(resources, conditions);
for (String logicalId : sortedLogicalIds) {
if (!isCreate && !changedResourceIds.contains(logicalId)) {
continue;
}
JsonNode resDef = resources.get(logicalId);
String type = resDef.path("Type").asText();
String deletionPolicy = resDef.path("DeletionPolicy").asText(null);
@@ -1320,6 +1486,15 @@ public class CloudFormationService implements ResourceProvider {
StackResource resource = stack.getResources().get(logicalId);
StackResource previousResource = resource;
String priorId = previousResource != null ? previousResource.getPhysicalId() : null;
Map<String, String> priorAttrs = new HashMap<>();
if (previousResource != null && previousResource.getAttributes() != null) {
for (Map.Entry<String, String> entry : previousResource.getAttributes().entrySet()) {
if (entry.getValue() != null) {
priorAttrs.put(entry.getKey(), entry.getValue());
}
}
}
if (resource == null) {
resource = new StackResource();
resource.setLogicalId(logicalId);
@@ -1366,6 +1541,51 @@ public class CloudFormationService implements ResourceProvider {
physicalIds.put(logicalId, resource.getPhysicalId());
resourceAttrs.put(logicalId, resource.getAttributes());
if (!isCreate) {
boolean replaced = dispatcher.hasReplacementUpdate(resource)
|| (priorId != null && !priorId.equals(resource.getPhysicalId()));
if (replaced) {
Set<String> allResourceIds = new LinkedHashSet<>();
resources.fieldNames().forEachRemaining(allResourceIds::add);
for (String candidateId : sortedLogicalIds) {
if (!changedResourceIds.contains(candidateId)) {
Set<String> deps = new LinkedHashSet<>();
collectDependencies(resources.path(candidateId).path("Properties"),
allResourceIds, deps, conditions);
if (deps.contains(logicalId)) {
changedResourceIds.add(candidateId);
}
}
}
} else {
// In-place updates can still change attributes (e.g. LatestVersionNumber of LaunchTemplate)
Map<String, String> newAttrs = resource.getAttributes();
Set<String> changedAttrNames = new HashSet<>();
if (newAttrs != null) {
for (Map.Entry<String, String> entry : newAttrs.entrySet()) {
if (!Objects.equals(entry.getValue(), priorAttrs.get(entry.getKey()))) {
changedAttrNames.add(entry.getKey());
}
}
}
for (String priorKey : priorAttrs.keySet()) {
if (newAttrs == null || !newAttrs.containsKey(priorKey)) {
changedAttrNames.add(priorKey);
}
}
if (!changedAttrNames.isEmpty()) {
for (String candidateId : sortedLogicalIds) {
if (!changedResourceIds.contains(candidateId)) {
if (referencesAnyAttribute(resources.path(candidateId).path("Properties"),
logicalId, changedAttrNames, conditions)) {
changedResourceIds.add(candidateId);
}
}
}
}
}
}
addEvent(stack, logicalId, resource.getPhysicalId(), type,
resource.getStatus(), resource.getStatusReason());
@@ -1516,6 +1736,55 @@ public class CloudFormationService implements ResourceProvider {
}
}
private Set<String> changedResourceIds(Stack stack, String templateBody, Map<String, String> params,
String region) {
ChangeSet changeSet = new ChangeSet();
changeSet.setStackName(stack.getStackName());
changeSet.setStackId(stack.getStackId());
changeSet.setChangeSetType("UPDATE");
changeSet.setTemplateBody(templateBody);
changeSet.setParameters(params);
Set<String> changedResourceIds = new LinkedHashSet<>();
for (ResourceChange change : computeChangeSetChanges(changeSet, region)) {
if ("Add".equals(change.action()) || "Modify".equals(change.action())) {
changedResourceIds.add(change.logicalResourceId());
}
}
return changedResourceIds;
}
private boolean isNestedStackChanged(Stack parentStack, String logicalId, JsonNode newDef,
String region, String accountId) {
if (parentStack == null) {
return false;
}
StackResource existingResource = parentStack.getResources().get(logicalId);
if (existingResource == null || existingResource.getPhysicalId() == null) {
return true;
}
Stack childStack = resolveStack(existingResource.getPhysicalId(), region, accountId);
if (childStack == null) {
return true;
}
String templateUrl = newDef.path("Properties").path("TemplateURL").asText(null);
if (templateUrl == null || templateUrl.isBlank()) {
return false;
}
try {
String newChildTemplate = fetchTemplateFromS3(templateUrl);
String currentChildTemplate = childStack.getOriginalTemplateBody() != null
? childStack.getOriginalTemplateBody()
: childStack.getTemplateBody();
return newChildTemplate != null && !newChildTemplate.equals(currentChildTemplate);
} catch (Exception ignored) {
// Safe to ignore: if TemplateURL is inaccessible and parent definition didn't change,
// treat the nested stack as unchanged so the parent update is not blocked.
return false;
}
}
/**
* Handles a resource that failed to provision.
*
@@ -2923,6 +3192,128 @@ public class CloudFormationService implements ResourceProvider {
}
}
private Set<String> expectedChangedAttributes(String resourceType, JsonNode oldDef, JsonNode newDef) {
Set<String> changedAttrs = new HashSet<>();
if ("AWS::EC2::LaunchTemplate".equals(resourceType)) {
changedAttrs.add("LatestVersionNumber");
}
JsonNode oldProps = oldDef != null ? oldDef.path("Properties") : null;
JsonNode newProps = newDef != null ? newDef.path("Properties") : null;
if (oldProps != null && newProps != null && oldProps.isObject() && newProps.isObject()) {
newProps.fieldNames().forEachRemaining(field -> {
if (!Objects.equals(newProps.get(field), oldProps.get(field))) {
changedAttrs.add(field);
}
});
}
return changedAttrs;
}
/**
* Checks whether a template node references any changed attribute of targetLogicalId
* (via Fn::GetAtt or Fn::Sub). Used to pull in dependent resources when a resource
* is updated in-place with modified attributes (e.g. LatestVersionNumber of LaunchTemplate).
*/
private boolean referencesAnyAttribute(JsonNode node, String targetLogicalId, Set<String> targetAttrNames,
Map<String, Boolean> conditions) {
if (node == null || node.isNull() || node.isMissingNode()) {
return false;
}
if (node.isObject()) {
if (node.has("Fn::GetAtt")) {
JsonNode getAtt = node.get("Fn::GetAtt");
String logicalId = null;
if (getAtt.isArray() && getAtt.size() >= 2) {
logicalId = getAtt.get(0).asText();
StringBuilder sb = new StringBuilder();
for (int i = 1; i < getAtt.size(); i++) {
if (i > 1) {
sb.append('.');
}
sb.append(getAtt.get(i).asText());
}
if (targetLogicalId.equals(logicalId)
&& (targetAttrNames.contains(sb.toString()) || targetAttrNames.contains(getAtt.get(1).asText()))) {
return true;
}
} else if (getAtt.isTextual()) {
String[] parts = getAtt.textValue().split("\\.", 2);
logicalId = parts[0];
String attrName = parts.length > 1 ? parts[1] : null;
if (targetLogicalId.equals(logicalId) && attrName != null && targetAttrNames.contains(attrName)) {
return true;
}
}
}
if (node.has("Fn::If")) {
JsonNode fnIf = node.get("Fn::If");
if (fnIf.isArray() && fnIf.size() == 3) {
if (conditions != null && conditions.containsKey(fnIf.get(0).asText())) {
boolean condition = conditions.get(fnIf.get(0).asText());
return referencesAnyAttribute(fnIf.get(condition ? 1 : 2), targetLogicalId, targetAttrNames, conditions);
}
return referencesAnyAttribute(fnIf.get(1), targetLogicalId, targetAttrNames, conditions)
|| referencesAnyAttribute(fnIf.get(2), targetLogicalId, targetAttrNames, conditions);
}
}
if (node.has("Fn::Sub")) {
if (subReferencesAttribute(node.get("Fn::Sub"), targetLogicalId, targetAttrNames, conditions)) {
return true;
}
}
for (Iterator<JsonNode> it = node.elements(); it.hasNext(); ) {
if (referencesAnyAttribute(it.next(), targetLogicalId, targetAttrNames, conditions)) {
return true;
}
}
return false;
} else if (node.isArray()) {
for (JsonNode item : node) {
if (referencesAnyAttribute(item, targetLogicalId, targetAttrNames, conditions)) {
return true;
}
}
}
return false;
}
private boolean subReferencesAttribute(JsonNode sub, String targetLogicalId, Set<String> targetAttrNames,
Map<String, Boolean> conditions) {
String template;
Set<String> explicitVars = new HashSet<>();
if (sub.isTextual()) {
template = sub.textValue();
} else if (sub.isArray() && sub.size() >= 1) {
template = sub.get(0).asText();
if (sub.size() >= 2 && sub.get(1).isObject()) {
sub.get(1).fieldNames().forEachRemaining(explicitVars::add);
if (referencesAnyAttribute(sub.get(1), targetLogicalId, targetAttrNames, conditions)) {
return true;
}
}
} else {
return false;
}
Matcher matcher = SUB_VAR_PATTERN.matcher(template);
while (matcher.find()) {
String varName = matcher.group(1);
if (varName.startsWith("AWS::") || explicitVars.contains(varName)) {
continue;
}
int dot = varName.indexOf('.');
if (dot > 0) {
String resourcePart = varName.substring(0, dot);
String attrPart = varName.substring(dot + 1);
if (targetLogicalId.equals(resourcePart) && targetAttrNames.contains(attrPart)) {
return true;
}
}
}
return false;
}
private static String stackStorageKey(String stackName, String region) {
return region + ":" + stackName;
}
@@ -1,6 +1,8 @@
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 io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
import io.github.hectorvent.floci.services.autoscaling.model.AsgOptionalFields;
@@ -41,6 +43,7 @@ public class AutoScalingGroupCfnProvisioner implements CfnResourceProvisioner {
private static final String LAUNCH_CONFIGURATION = "AWS::AutoScaling::LaunchConfiguration";
private static final Logger LOG = Logger.getLogger(AutoScalingGroupCfnProvisioner.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private final AutoScalingService autoScalingService;
@@ -72,6 +75,81 @@ public class AutoScalingGroupCfnProvisioner implements CfnResourceProvisioner {
}
}
@Override
public boolean rollbackUpdate(StackResource resource) {
if (GROUP.equals(resource.getResourceType())) {
String rawSnapshot = resource.getAttributes().remove(CfnRollback.ASG_UPDATE_SNAPSHOT_ATTR);
if (rawSnapshot != null) {
try {
AsgSnapshot snapshot = MAPPER.readValue(rawSnapshot, AsgSnapshot.class);
// UpdateAutoScalingGroup treats null as "leave unchanged". Restore an unset
// snapshot member with its API default instead; -1 removes DefaultInstanceWarmup.
AsgOptionalFields optionalFields = new AsgOptionalFields(
snapshot.desiredCapacityType() != null ? snapshot.desiredCapacityType() : "units",
snapshot.capacityRebalance() != null ? snapshot.capacityRebalance() : false,
snapshot.maxInstanceLifetime() != null ? snapshot.maxInstanceLifetime() : 0,
snapshot.defaultInstanceWarmup() != null
? snapshot.defaultInstanceWarmup()
: AsgOptionalFields.DEFAULT_INSTANCE_WARMUP_REMOVAL_SENTINEL
);
autoScalingService.updateAutoScalingGroup(
snapshot.region(),
snapshot.name(),
snapshot.launchConfigName(),
snapshot.launchTemplateId(),
snapshot.launchTemplateName(),
snapshot.launchTemplateVersion(),
snapshot.mixedInstancesPolicy(),
snapshot.minSize(),
snapshot.maxSize(),
snapshot.desiredCapacity(),
snapshot.cooldown(),
snapshot.availabilityZones(),
snapshot.subnetIds(),
snapshot.healthCheckType(),
snapshot.healthCheckGracePeriod(),
snapshot.terminationPolicies(),
optionalFields
);
return true;
} catch (Exception e) {
LOG.errorv("Could not restore Auto Scaling group update snapshot for {0}: {1}",
resource.getLogicalId(), e.getMessage());
return false;
}
}
}
return false;
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.ASG_UPDATE_SNAPSHOT_ATTR);
}
public record AsgSnapshot(
String region,
String name,
String launchConfigName,
String launchTemplateId,
String launchTemplateName,
String launchTemplateVersion,
MixedInstancesPolicy mixedInstancesPolicy,
Integer minSize,
Integer maxSize,
Integer desiredCapacity,
Integer cooldown,
List<String> availabilityZones,
List<String> subnetIds,
String healthCheckType,
Integer healthCheckGracePeriod,
List<String> terminationPolicies,
String desiredCapacityType,
Boolean capacityRebalance,
Integer maxInstanceLifetime,
Integer defaultInstanceWarmup
) {}
private static IllegalStateException unsupported(String resourceType) {
return new IllegalStateException(
"AutoScalingGroupCfnProvisioner received an unsupported type: " + resourceType);
@@ -154,6 +232,35 @@ public class AutoScalingGroupCfnProvisioner implements CfnResourceProvisioner {
AutoScalingGroup existing = existingEntity(ctx, name, n -> requireAutoScalingGroup(region, n));
AutoScalingGroup asg;
if (existing != null) {
AsgSnapshot snapshot = new AsgSnapshot(
region,
name,
existing.getLaunchConfigurationName(),
existing.getLaunchTemplateId(),
existing.getLaunchTemplateName(),
existing.getLaunchTemplateVersion(),
existing.getMixedInstancesPolicy(),
existing.getMinSize(),
existing.getMaxSize(),
existing.getDesiredCapacity(),
existing.getDefaultCooldown(),
existing.getAvailabilityZones() != null ? List.copyOf(existing.getAvailabilityZones()) : List.of(),
existing.getSubnetIds() != null ? List.copyOf(existing.getSubnetIds()) : List.of(),
existing.getHealthCheckType(),
existing.getHealthCheckGracePeriod(),
existing.getTerminationPolicies() != null ? List.copyOf(existing.getTerminationPolicies()) : List.of(),
existing.getDesiredCapacityType(),
existing.getCapacityRebalance(),
existing.getMaxInstanceLifetime(),
existing.getDefaultInstanceWarmup()
);
try {
r.getAttributes().put(CfnRollback.ASG_UPDATE_SNAPSHOT_ATTR, MAPPER.writeValueAsString(snapshot));
} catch (JsonProcessingException e) {
LOG.warnv("Could not serialize Auto Scaling group update snapshot for {0}: {1}",
r.getLogicalId(), e.getMessage());
}
autoScalingService.updateAutoScalingGroup(region, name,
blankToNull(launchConfigName),
blankToNull(launchTemplateId), blankToNull(launchTemplateName), blankToNull(launchTemplateVersion),
@@ -122,6 +122,24 @@ public final class CfnRollback {
*/
public static final String REPLACEMENT_CLEANUP_ATTR = "__FlociReplacementCleanup";
/**
* Holds the attributes and tags a queue carried before an in-place update changed them,
* so a failed stack update can restore them.
*/
public static final String SQS_UPDATE_SNAPSHOT_ATTR = "__FlociSqsUpdateSnapshot";
/**
* Holds the configuration an Auto Scaling group carried before an in-place update changed it,
* so a failed stack update can restore it.
*/
public static final String ASG_UPDATE_SNAPSHOT_ATTR = "__FlociAsgUpdateSnapshot";
/**
* Holds the version a launch template created during an in-place update and the prior version,
* so a failed stack update can roll it back.
*/
public static final String LAUNCH_TEMPLATE_UPDATE_SNAPSHOT_ATTR = "__FlociLaunchTemplateUpdateSnapshot";
private CfnRollback() {
}
@@ -82,7 +82,11 @@ public class CloudTrailCfnProvisioner implements CfnResourceProvisioner {
resource.setPhysicalId(trail.trailArn());
resource.getAttributes().put("Arn", trail.trailArn());
resource.getAttributes().put("SnsTopicArn", trail.snsTopicArn());
if (trail.snsTopicArn() != null) {
resource.getAttributes().put("SnsTopicArn", trail.snsTopicArn());
} else {
resource.getAttributes().remove("SnsTopicArn");
}
}
@Override
@@ -1,6 +1,8 @@
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 io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.Ec2UserDataDecoder;
@@ -8,6 +10,7 @@ import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.List;
@@ -20,6 +23,9 @@ import java.util.Set;
@ApplicationScoped
public class Ec2LaunchTemplateCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(Ec2LaunchTemplateCfnProvisioner.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private final Ec2Service ec2Service;
@Inject
@@ -73,7 +79,17 @@ public class Ec2LaunchTemplateCfnProvisioner implements CfnResourceProvisioner {
// AWS::EC2::LaunchTemplate behaves when only its LaunchTemplateData changes.
LaunchTemplate lt;
if (existing != null && name.equals(existing.getLaunchTemplateName())) {
String priorLatest = existing.getLatestVersionNumber();
String priorDefault = existing.getDefaultVersionNumber();
lt = ec2Service.createLaunchTemplateVersion(ctx.region(), previousId, null, null, data);
LaunchTemplateSnapshot snapshot = new LaunchTemplateSnapshot(
ctx.region(), lt.getLaunchTemplateId(), lt.getLatestVersionNumber(), priorLatest, priorDefault);
try {
r.getAttributes().put(CfnRollback.LAUNCH_TEMPLATE_UPDATE_SNAPSHOT_ATTR, MAPPER.writeValueAsString(snapshot));
} catch (JsonProcessingException e) {
LOG.warnv("Could not serialize Launch Template update snapshot for {0}: {1}",
r.getLogicalId(), e.getMessage());
}
} else {
lt = ec2Service.createLaunchTemplate(ctx.region(), name, data, null);
// A changed name is a replacement: drop the template the previous execution created,
@@ -97,6 +113,40 @@ public class Ec2LaunchTemplateCfnProvisioner implements CfnResourceProvisioner {
ec2Service.deleteLaunchTemplate(region, physicalId, null);
}
@Override
public boolean rollbackUpdate(StackResource resource) {
String rawSnapshot = resource.getAttributes().remove(CfnRollback.LAUNCH_TEMPLATE_UPDATE_SNAPSHOT_ATTR);
if (rawSnapshot != null) {
try {
LaunchTemplateSnapshot snapshot = MAPPER.readValue(rawSnapshot, LaunchTemplateSnapshot.class);
if (snapshot.createdVersion() != null) {
ec2Service.deleteLaunchTemplateVersion(snapshot.region(), snapshot.launchTemplateId(), snapshot.createdVersion());
}
resource.getAttributes().put("LatestVersionNumber", snapshot.priorLatestVersion());
resource.getAttributes().put("DefaultVersionNumber", snapshot.priorDefaultVersion());
return true;
} catch (Exception e) {
LOG.errorv("Could not restore Launch Template update snapshot for {0}: {1}",
resource.getLogicalId(), e.getMessage());
return false;
}
}
return false;
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.LAUNCH_TEMPLATE_UPDATE_SNAPSHOT_ATTR);
}
public record LaunchTemplateSnapshot(
String region,
String launchTemplateId,
String createdVersion,
String priorLatestVersion,
String priorDefaultVersion
) {}
/** The template a previous execution created, or null when it is gone. */
private LaunchTemplate findExisting(String region, String launchTemplateId) {
try {
@@ -1,6 +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.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
@@ -8,6 +11,7 @@ import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.services.sqs.model.Queue;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.HashMap;
import java.util.List;
@@ -22,6 +26,9 @@ import java.util.UUID;
@ApplicationScoped
public class SqsCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(SqsCfnProvisioner.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private final SqsService sqsService;
@Inject
@@ -51,7 +58,57 @@ public class SqsCfnProvisioner implements CfnResourceProvisioner {
// AWS::SQS::QueuePolicy has no backing resource to delete (matches prior behavior).
}
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return ReplacementCleanup.hasReplacement(resource);
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
return ReplacementCleanup.cleanupPhysicalId(resource);
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
return ReplacementCleanup.complete(resource, this::delete);
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.SQS_UPDATE_SNAPSHOT_ATTR);
ReplacementCleanup.clear(resource);
}
@Override
public boolean rollbackUpdate(StackResource resource) {
if (ReplacementCleanup.rollback(resource, this::delete)) {
return true;
}
String rawSnapshot = resource.getAttributes().remove(CfnRollback.SQS_UPDATE_SNAPSHOT_ATTR);
if (rawSnapshot != null) {
try {
JsonNode snapshot = MAPPER.readTree(rawSnapshot);
String queueUrl = snapshot.get("queueUrl").asText();
String region = snapshot.get("region").asText();
Map<String, String> restoreAttrs = new HashMap<>();
snapshot.path("attributes").fields().forEachRemaining(e -> restoreAttrs.put(e.getKey(), e.getValue().asText()));
if (!restoreAttrs.isEmpty()) {
sqsService.setQueueAttributes(queueUrl, restoreAttrs, region);
}
Map<String, String> restoreTags = new HashMap<>();
snapshot.path("tags").fields().forEachRemaining(e -> restoreTags.put(e.getKey(), e.getValue().asText()));
reconcileTags(queueUrl, restoreTags, region);
return true;
} catch (JsonProcessingException e) {
LOG.errorv("Could not parse SQS update snapshot for {0}: {1}", resource.getLogicalId(), e.getMessage());
return false;
}
}
return false;
}
private void provisionQueue(StackResource r, JsonNode props, ProvisionContext ctx) {
Map<String, String> attributesBefore = r.getAttributes() != null ? new HashMap<>(r.getAttributes()) : new HashMap<>();
String fifoFlag = props != null && props.has("FifoQueue")
? ctx.engine().resolve(props.get("FifoQueue"))
: null;
@@ -119,6 +176,19 @@ public class SqsCfnProvisioner implements CfnResourceProvisioner {
String queueUrl;
if (ctx.isUpdate() && queueName.equals(priorName)) {
attrs.remove("FifoQueue");
Map<String, String> currentAttrs = sqsService.getQueueAttributes(ctx.priorPhysicalId(), List.of("All"), ctx.region());
Map<String, String> currentTags = sqsService.listQueueTags(ctx.priorPhysicalId(), ctx.region());
ObjectNode snapshot = MAPPER.createObjectNode();
snapshot.put("queueUrl", ctx.priorPhysicalId());
snapshot.put("region", ctx.region());
ObjectNode attrsNode = snapshot.putObject("attributes");
for (String attrKey : attrs.keySet()) {
attrsNode.put(attrKey, currentAttrs.getOrDefault(attrKey, ""));
}
ObjectNode tagsNode = snapshot.putObject("tags");
currentTags.forEach(tagsNode::put);
r.getAttributes().put(CfnRollback.SQS_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
sqsService.setQueueAttributes(ctx.priorPhysicalId(), attrs, ctx.region());
queueUrl = ctx.priorPhysicalId();
} else {
@@ -134,6 +204,7 @@ public class SqsCfnProvisioner implements CfnResourceProvisioner {
r.getAttributes().put("Arn", queueArn);
r.getAttributes().put("QueueName", queueName);
r.getAttributes().put("QueueUrl", queueUrl);
ReplacementCleanup.record(r, ctx, attributesBefore);
}
/**
@@ -6706,6 +6706,26 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return launchTemplate;
}
public void deleteLaunchTemplateVersion(String region, String id, String version) {
ensureDefaultResources(region);
LaunchTemplate launchTemplate = findLaunchTemplate(region, id, null);
ensureLaunchTemplateVersions(launchTemplate);
launchTemplate.getVersions().remove(version);
launchTemplate.getVersionDescriptions().remove(version);
int max = launchTemplate.getVersions().keySet().stream()
.mapToInt(this::parseLaunchTemplateVersion)
.max()
.orElse(1);
String maxStr = String.valueOf(max);
launchTemplate.setLatestVersionNumber(maxStr);
LaunchTemplateData latestData = launchTemplate.getVersions().get(maxStr);
if (latestData != null) {
launchTemplate.setData(new LaunchTemplateData(latestData));
}
launchTemplate.setVersionDescription(launchTemplate.getVersionDescriptions().get(maxStr));
launchTemplates.put(key(region, launchTemplate.getLaunchTemplateId()), launchTemplate);
}
/**
* EC2 spells the two not-found codes asymmetrically —
* {@code InvalidLaunchTemplateName.NotFoundException} but {@code InvalidLaunchTemplateId.NotFound},