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},
+1
View File
@@ -62,6 +62,7 @@ quarkus:
- sagemaker/*.yaml
- eks/*.json
- aws/*.json
- cloudformation/*.json
- i18n/*.properties
- org/apache/velocity/runtime/defaults/*.properties
# DriverManager finds the JDBC drivers through ServiceLoader, and the MySQL
@@ -0,0 +1,708 @@
{
"AWS::ApiGateway::Account": [],
"AWS::ApiGateway::ApiKey": [
"GenerateDistinctId",
"Name",
"Value"
],
"AWS::ApiGateway::Authorizer": [
"RestApiId"
],
"AWS::ApiGateway::BasePathMapping": [
"DomainName",
"BasePath"
],
"AWS::ApiGateway::Deployment": [
"DeploymentCanarySettings",
"RestApiId"
],
"AWS::ApiGateway::DomainName": [
"DomainName"
],
"AWS::ApiGateway::GatewayResponse": [
"ResponseType",
"RestApiId"
],
"AWS::ApiGateway::Method": [
"RestApiId",
"ResourceId",
"HttpMethod"
],
"AWS::ApiGateway::Resource": [
"PathPart",
"ParentId",
"RestApiId"
],
"AWS::ApiGateway::RestApi": [],
"AWS::ApiGateway::Stage": [
"RestApiId",
"StageName"
],
"AWS::ApiGateway::UsagePlan": [],
"AWS::ApiGateway::UsagePlanKey": [
"KeyId",
"UsagePlanId",
"KeyType"
],
"AWS::ApiGatewayV2::Api": [
"ProtocolType"
],
"AWS::ApiGatewayV2::Authorizer": [
"ApiId"
],
"AWS::ApiGatewayV2::Deployment": [
"ApiId"
],
"AWS::ApiGatewayV2::Integration": [
"ApiId"
],
"AWS::ApiGatewayV2::Route": [
"ApiId"
],
"AWS::ApiGatewayV2::Stage": [
"StageName",
"ApiId"
],
"AWS::AppSync::ApiKey": [
"ApiId"
],
"AWS::AppSync::DataSource": [
"ApiId",
"Name"
],
"AWS::AppSync::FunctionConfiguration": [
"ApiId"
],
"AWS::AppSync::GraphQLApi": [],
"AWS::AppSync::GraphQLSchema": [
"ApiId"
],
"AWS::AppSync::Resolver": [
"ApiId",
"FieldName",
"TypeName"
],
"AWS::AutoScaling::AutoScalingGroup": [
"InstanceId",
"AutoScalingGroupName"
],
"AWS::AutoScaling::LaunchConfiguration": [
"AssociatePublicIpAddress",
"BlockDeviceMappings",
"ClassicLinkVPCId",
"ClassicLinkVPCSecurityGroups",
"EbsOptimized",
"IamInstanceProfile",
"ImageId",
"InstanceId",
"InstanceMonitoring",
"InstanceType",
"KernelId",
"KeyName",
"LaunchConfigurationName",
"MetadataOptions",
"PlacementTenancy",
"RamDiskId",
"SecurityGroups",
"SpotPrice",
"UserData"
],
"AWS::AutoScaling::LifecycleHook": [
"AutoScalingGroupName",
"LifecycleHookName"
],
"AWS::AutoScaling::ScalingPolicy": [
"AutoScalingGroupName"
],
"AWS::Backup::BackupVault": [
"BackupVaultName",
"EncryptionKeyArn"
],
"AWS::Batch::ComputeEnvironment": [
"ComputeResources/SpotIamFleetRole",
"ComputeEnvironmentName",
"Tags",
"Type",
"EksConfiguration",
"ComputeResources/ManagedInstancesProvider/InstanceLaunchTemplate/CapacityOptionType",
"ComputeResources/ManagedInstancesProvider/InstanceLaunchTemplate/FipsEnabled"
],
"AWS::Batch::JobDefinition": [
"JobDefinitionName"
],
"AWS::Batch::JobQueue": [
"JobQueueName",
"JobQueueType"
],
"AWS::CertificateManager::Certificate": [
"SubjectAlternativeNames",
"DomainValidationOptions",
"KeyAlgorithm",
"DomainName",
"CertificateAuthorityArn",
"CertificateExport"
],
"AWS::CloudFormation::CustomResource": [
"ServiceToken"
],
"AWS::CloudFront::CachePolicy": [],
"AWS::CloudFront::Distribution": [],
"AWS::CloudFront::OriginAccessControl": [],
"AWS::CloudFront::OriginRequestPolicy": [],
"AWS::CloudFront::ResponseHeadersPolicy": [],
"AWS::CloudTrail::Trail": [
"TrailName"
],
"AWS::CloudWatch::Alarm": [
"AlarmName"
],
"AWS::CloudWatch::Dashboard": [
"DashboardName"
],
"AWS::CodeBuild::Project": [
"Name"
],
"AWS::CodePipeline::CustomActionType": [
"Category",
"ConfigurationProperties",
"InputArtifactDetails",
"OutputArtifactDetails",
"Provider",
"Settings",
"Version"
],
"AWS::CodePipeline::Pipeline": [
"Name"
],
"AWS::CodePipeline::Webhook": [
"Name"
],
"AWS::Cognito::UserPool": [],
"AWS::Cognito::UserPoolClient": [
"GenerateSecret",
"UserPoolId"
],
"AWS::Cognito::UserPoolDomain": [
"UserPoolId",
"Domain"
],
"AWS::Cognito::UserPoolGroup": [
"UserPoolId",
"GroupName"
],
"AWS::Config::ConfigRule": [
"ConfigRuleName"
],
"AWS::DynamoDB::GlobalTable": [
"TableName"
],
"AWS::DynamoDB::Table": [
"TableName",
"ImportSourceSpecification"
],
"AWS::EC2::EIP": [
"NetworkBorderGroup",
"TransferAddress",
"IpamPoolId",
"Address"
],
"AWS::EC2::FlowLog": [
"DeliverCrossAccountRole",
"DeliverLogsPermissionArn",
"LogGroupName",
"LogDestination",
"ResourceId",
"TrafficType",
"LogDestinationType",
"ResourceType",
"LogFormat",
"MaxAggregationInterval",
"DestinationOptions",
"TagFieldSpecifications"
],
"AWS::EC2::Instance": [
"AvailabilityZone",
"CpuOptions",
"ElasticGpuSpecifications",
"ElasticInferenceAccelerators",
"EnclaveOptions",
"HibernationOptions",
"HostResourceGroupArn",
"ImageId",
"Ipv6AddressCount",
"Ipv6Addresses",
"KeyName",
"LaunchTemplate",
"LicenseSpecifications",
"NetworkInterfaces",
"PlacementGroupName",
"PrivateIpAddress",
"SecurityGroups",
"SubnetId"
],
"AWS::EC2::InternetGateway": [],
"AWS::EC2::LaunchTemplate": [
"LaunchTemplateName"
],
"AWS::EC2::NatGateway": [
"VpcId",
"SubnetId",
"ConnectivityType",
"AllocationId",
"PrivateIpAddress",
"AvailabilityMode"
],
"AWS::EC2::NetworkAcl": [
"VpcId"
],
"AWS::EC2::NetworkAclEntry": [
"Egress",
"RuleNumber",
"NetworkAclId"
],
"AWS::EC2::Route": [
"RouteTableId",
"DestinationCidrBlock",
"DestinationIpv6CidrBlock",
"DestinationPrefixListId"
],
"AWS::EC2::RouteTable": [
"VpcId"
],
"AWS::EC2::SecurityGroup": [
"GroupDescription",
"GroupName",
"VpcId"
],
"AWS::EC2::SecurityGroupEgress": [
"IpProtocol",
"DestinationSecurityGroupId",
"ToPort",
"CidrIp",
"FromPort",
"GroupId",
"CidrIpv6",
"DestinationPrefixListId"
],
"AWS::EC2::SecurityGroupIngress": [
"GroupName",
"IpProtocol",
"SourceSecurityGroupId",
"SourcePrefixListId",
"ToPort",
"CidrIp",
"SourceSecurityGroupName",
"SourceSecurityGroupOwnerId",
"FromPort",
"GroupId",
"CidrIpv6"
],
"AWS::EC2::Subnet": [
"VpcId",
"AvailabilityZone",
"AvailabilityZoneId",
"CidrBlock",
"OutpostArn",
"Ipv6Native",
"Ipv4IpamPoolId",
"Ipv4NetmaskLength",
"Ipv6IpamPoolId",
"Ipv6NetmaskLength"
],
"AWS::EC2::SubnetNetworkAclAssociation": [
"SubnetId",
"NetworkAclId"
],
"AWS::EC2::SubnetRouteTableAssociation": [
"SubnetId",
"RouteTableId"
],
"AWS::EC2::VPC": [
"CidrBlock",
"Ipv4IpamPoolId",
"Ipv4NetmaskLength",
"VpcEncryptionControl"
],
"AWS::EC2::VPCEndpoint": [
"ServiceName",
"VpcEndpointType",
"VpcId",
"ServiceNetworkArn",
"ResourceConfigurationArn",
"ServiceRegion",
"DnsOptions/PrivateDnsPreference",
"DnsOptions/PrivateDnsSpecifiedDomains"
],
"AWS::EC2::VPCGatewayAttachment": [
"VpcId"
],
"AWS::ECR::Repository": [
"RepositoryName",
"EncryptionConfiguration",
"EncryptionConfiguration/EncryptionType",
"EncryptionConfiguration/KmsKey"
],
"AWS::ECS::CapacityProvider": [
"AutoScalingGroupProvider/AutoScalingGroupArn",
"ManagedInstancesProvider/InstanceLaunchTemplate/FipsEnabled",
"Name",
"ClusterName"
],
"AWS::ECS::Cluster": [
"ClusterName"
],
"AWS::ECS::ClusterCapacityProviderAssociations": [
"Cluster"
],
"AWS::ECS::Service": [
"Cluster",
"Role",
"SchedulingStrategy",
"ServiceName"
],
"AWS::ECS::TaskDefinition": [
"Family",
"ContainerDefinitions",
"Cpu",
"EnableFaultInjection",
"ExecutionRoleArn",
"InferenceAccelerators",
"Memory",
"NetworkMode",
"PlacementConstraints",
"ProxyConfiguration",
"RequiresCompatibilities",
"RuntimePlatform",
"TaskRoleArn",
"Volumes",
"PidMode",
"IpcMode",
"EphemeralStorage"
],
"AWS::EKS::Cluster": [
"OutpostConfig",
"EncryptionConfig",
"KubernetesNetworkConfig/IpFamily",
"KubernetesNetworkConfig/ServiceIpv4Cidr",
"AccessConfig/BootstrapClusterCreatorAdminPermissions",
"Name",
"RoleArn",
"BootstrapSelfManagedAddons"
],
"AWS::EKS::Nodegroup": [
"CapacityType",
"NodegroupName",
"RemoteAccess",
"NodeRole",
"ClusterName",
"InstanceTypes",
"DiskSize",
"AmiType",
"Subnets"
],
"AWS::ElasticLoadBalancingV2::Listener": [
"LoadBalancerArn"
],
"AWS::ElasticLoadBalancingV2::ListenerRule": [
"ListenerArn"
],
"AWS::ElasticLoadBalancingV2::LoadBalancer": [
"Name",
"Type",
"Scheme"
],
"AWS::ElasticLoadBalancingV2::TargetGroup": [
"TargetType",
"ProtocolVersion",
"Port",
"Name",
"VpcId",
"Protocol",
"IpAddressType"
],
"AWS::Events::EventBus": [
"Name"
],
"AWS::Events::EventBusPolicy": [
"EventBusName",
"StatementId"
],
"AWS::Events::Rule": [
"Name"
],
"AWS::IAM::AccessKey": [
"UserName",
"Serial"
],
"AWS::IAM::InstanceProfile": [
"InstanceProfileName",
"Path"
],
"AWS::IAM::ManagedPolicy": [
"ManagedPolicyName",
"Description",
"Path"
],
"AWS::IAM::Policy": [],
"AWS::IAM::Role": [
"Path",
"RoleName"
],
"AWS::IAM::User": [
"UserName"
],
"AWS::IoT::DomainConfiguration": [
"DomainConfigurationName",
"DomainName",
"ServiceType",
"ValidationCertificateArn",
"ServerCertificateArns"
],
"AWS::IoT::Policy": [
"PolicyName"
],
"AWS::IoT::Thing": [
"ThingName"
],
"AWS::IoT::TopicRule": [
"RuleName"
],
"AWS::Kinesis::Stream": [
"Name"
],
"AWS::KinesisFirehose::DeliveryStream": [
"DeliveryStreamName",
"DeliveryStreamType",
"ElasticsearchDestinationConfiguration/VpcConfiguration",
"AmazonopensearchserviceDestinationConfiguration/VpcConfiguration",
"AmazonOpenSearchServerlessDestinationConfiguration/VpcConfiguration",
"DatabaseSourceConfiguration",
"KinesisStreamSourceConfiguration",
"DirectPutSourceConfiguration",
"MSKSourceConfiguration",
"IcebergDestinationConfiguration/CatalogConfiguration",
"SnowflakeDestinationConfiguration/SnowflakeVpcConfiguration"
],
"AWS::KMS::Alias": [
"AliasName"
],
"AWS::KMS::Key": [],
"AWS::Lambda::Alias": [
"Name",
"FunctionName"
],
"AWS::Lambda::EventInvokeConfig": [
"FunctionName",
"Qualifier"
],
"AWS::Lambda::EventSourceMapping": [
"EventSourceArn",
"StartingPosition",
"StartingPositionTimestamp",
"SelfManagedEventSource"
],
"AWS::Lambda::Function": [
"FunctionName",
"PackageType",
"TenancyConfig"
],
"AWS::Lambda::LayerVersion": [
"CompatibleRuntimes",
"LicenseInfo",
"CompatibleArchitectures",
"LayerName",
"Description",
"Content"
],
"AWS::Lambda::MicrovmImage": [
"Name"
],
"AWS::Lambda::NetworkConnector": [
"Name"
],
"AWS::Lambda::Permission": [
"FunctionName",
"FunctionUrlAuthType",
"InvokedViaFunctionUrl",
"SourceAccount",
"SourceArn",
"Principal",
"PrincipalOrgID",
"Action",
"EventSourceToken"
],
"AWS::Lambda::Url": [
"TargetFunctionArn",
"Qualifier"
],
"AWS::Lambda::Version": [
"FunctionName",
"Description",
"CodeSha256",
"ProvisionedConcurrencyConfig",
"RuntimePolicy"
],
"AWS::Logs::LogGroup": [
"LogGroupName"
],
"AWS::Logs::LogStream": [
"LogGroupName",
"LogStreamName"
],
"AWS::Logs::MetricFilter": [
"FilterName",
"LogGroupName"
],
"AWS::Organizations::Account": [],
"AWS::Organizations::Organization": [],
"AWS::Organizations::OrganizationalUnit": [
"ParentId"
],
"AWS::Organizations::Policy": [
"Type"
],
"AWS::Organizations::ResourcePolicy": [],
"AWS::Pipes::Pipe": [
"Name",
"Source",
"SourceParameters/DynamoDBStreamParameters/StartingPosition",
"SourceParameters/KinesisStreamParameters/StartingPosition",
"SourceParameters/KinesisStreamParameters/StartingPositionTimestamp",
"SourceParameters/ActiveMQBrokerParameters/QueueName",
"SourceParameters/RabbitMQBrokerParameters/QueueName",
"SourceParameters/RabbitMQBrokerParameters/VirtualHost",
"SourceParameters/ManagedStreamingKafkaParameters/TopicName",
"SourceParameters/ManagedStreamingKafkaParameters/StartingPosition",
"SourceParameters/ManagedStreamingKafkaParameters/ConsumerGroupID",
"SourceParameters/SelfManagedKafkaParameters/TopicName",
"SourceParameters/SelfManagedKafkaParameters/StartingPosition",
"SourceParameters/SelfManagedKafkaParameters/AdditionalBootstrapServers",
"SourceParameters/SelfManagedKafkaParameters/ConsumerGroupID"
],
"AWS::RDS::DBCluster": [
"ClusterScalabilityType",
"DBClusterIdentifier",
"DBSubnetGroupName",
"DBSystemId",
"DatabaseName",
"EngineMode",
"KmsKeyId",
"PubliclyAccessible",
"RestoreToTime",
"RestoreType",
"SnapshotIdentifier",
"SourceDBClusterIdentifier",
"SourceDbClusterResourceId",
"SourceRegion",
"StorageEncrypted",
"UseLatestRestorableTime"
],
"AWS::RDS::DBClusterParameterGroup": [
"DBClusterParameterGroupName",
"Description",
"Family"
],
"AWS::RDS::DBInstance": [
"BackupTarget",
"CharacterSetName",
"CustomIAMInstanceProfile",
"DBClusterIdentifier",
"DBInstanceIdentifier",
"DBName",
"DBSubnetGroupName",
"DBSystemId",
"KmsKeyId",
"MasterUsername",
"NcharCharacterSetName",
"SourceRegion",
"StorageEncrypted",
"Timezone"
],
"AWS::RDS::DBParameterGroup": [
"DBParameterGroupName",
"Description",
"Family"
],
"AWS::RDS::DBProxy": [
"DBProxyName",
"EngineFamily",
"EndpointNetworkType",
"TargetConnectionNetworkType",
"VpcSubnetIds"
],
"AWS::RDS::DBProxyTargetGroup": [
"DBProxyName",
"TargetGroupName"
],
"AWS::RDS::DBSubnetGroup": [
"DBSubnetGroupName"
],
"AWS::Redshift::Cluster": [
"ClusterIdentifier",
"OwnerAccount",
"SnapshotIdentifier",
"DBName",
"SnapshotClusterIdentifier",
"ClusterSubnetGroupName",
"MasterUsername"
],
"AWS::Redshift::ClusterParameterGroup": [
"ParameterGroupName",
"ParameterGroupFamily",
"Description"
],
"AWS::Redshift::ClusterSecurityGroup": [
"Description"
],
"AWS::Redshift::ClusterSubnetGroup": [],
"AWS::Route53::HostedZone": [
"Name"
],
"AWS::Route53::RecordSet": [
"HostedZoneName",
"HostedZoneId"
],
"AWS::S3::Bucket": [
"BucketName",
"BucketNamePrefix",
"BucketNamespace"
],
"AWS::S3::BucketPolicy": [
"Bucket"
],
"AWS::Scheduler::ScheduleGroup": [
"Name"
],
"AWS::SecretsManager::Secret": [
"Name"
],
"AWS::SecretsManager::SecretTargetAttachment": [
"SecretId"
],
"AWS::SNS::Subscription": [
"Endpoint",
"Protocol",
"TopicArn"
],
"AWS::SNS::Topic": [
"TopicName",
"FifoTopic"
],
"AWS::SNS::TopicPolicy": [],
"AWS::SQS::Queue": [
"FifoQueue",
"QueueName"
],
"AWS::SQS::QueuePolicy": [],
"AWS::SSM::Parameter": [
"Name"
],
"AWS::StepFunctions::StateMachine": [
"StateMachineName",
"StateMachineType"
],
"AWS::WAFv2::WebACL": [
"Name",
"Scope"
]
}
@@ -0,0 +1,54 @@
package io.github.hectorvent.floci.services.cloudformation;
import org.junit.jupiter.api.Test;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CfnCreateOnlyPropertiesTest {
@Test
void isCreateOnly_matchesSchemaDefinedProperties() {
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::Redshift::Cluster", "DBName"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::Redshift::Cluster", "ClusterIdentifier"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::EC2::Subnet", "CidrBlock"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGateway::DomainName", "DomainName"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::SQS::Queue", "QueueName"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::SQS::Queue", "FifoQueue"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::S3::Bucket", "BucketName"));
}
@Test
void isCreateOnly_returnsFalseForMutableProperties() {
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::SQS::Queue", "VisibilityTimeout"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::Redshift::Cluster", "NumberOfNodes"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::S3::Bucket", "VersioningConfiguration"));
}
@Test
void isCreateOnly_treatsEmptySchemaListAsAuthoritative() {
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGateway::RestApi", "Name"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::Cognito::UserPool", "UserPoolName"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGateway::UsagePlan", "UsagePlanName"));
}
@Test
void isCreateOnly_fallsBackToHeuristicForCustomOrUnknownTypes() {
assertTrue(CfnCreateOnlyProperties.isCreateOnly("Custom::Widget", "WidgetName"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("Custom::Widget", "Name"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("Custom::Widget", "ClusterIdentifier"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("Custom::Widget", "Description"));
}
@Test
void getCreateOnlyProperties_returnsExpectedSet() {
Set<String> redshiftProps = CfnCreateOnlyProperties.getCreateOnlyProperties("AWS::Redshift::Cluster");
assertTrue(redshiftProps.contains("DBName"));
assertTrue(redshiftProps.contains("ClusterIdentifier"));
Set<String> unknownProps = CfnCreateOnlyProperties.getCreateOnlyProperties("Unknown::Type");
assertTrue(unknownProps.isEmpty());
}
}
@@ -4,11 +4,17 @@ import io.github.hectorvent.floci.core.common.XmlParser;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* UpdateStack must leave an unchanged resource alone, whatever its type.
@@ -28,6 +34,8 @@ class CfnUnchangedResourceUpdateIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260808/us-west-2/cloudformation/aws4_request";
private static final String SQS_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260808/us-west-2/sqs/aws4_request";
private static String stackWith(String namedResourceJson, String queueName) {
return """
@@ -65,6 +73,25 @@ class CfnUnchangedResourceUpdateIntegrationTest {
return physicalIdOf(body, "Named");
}
private String queueAttribute(String queueUrl, String attributeName) {
String body = given()
.header("Authorization", SQS_AUTH)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetQueueAttributes")
.formParam("QueueUrl", queueUrl)
.formParam("AttributeName.1", attributeName)
.when().post("/").then().statusCode(200)
.extract().body().asString();
return XmlParser.extractPairs(body, "Attribute", "Name", "Value").get(attributeName);
}
private void deleteStack(String stackName) {
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DeleteStack").formParam("StackName", stackName)
.when().post("/").then().statusCode(200);
CfnStackWaits.awaitStackDeleted(stackName);
}
/**
* Creates the stack, updates it with only the churn queue renamed, then asserts both that the
* update completed and that the untouched resource kept its physical id. The second assertion
@@ -286,6 +313,189 @@ class CfnUnchangedResourceUpdateIntegrationTest {
}""");
}
@Test
void updatesAResourceWhenItsReferencedQueueIsReplaced() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "probe-sqs-redrive-" + suffix;
String oldDeadLetterName = "probe-dlq-old-" + suffix;
String newDeadLetterName = "probe-dlq-new-" + suffix;
String mainQueueName = "probe-main-" + suffix;
String initialTemplate = redriveTemplate(oldDeadLetterName, mainQueueName);
String updatedTemplate = redriveTemplate(newDeadLetterName, mainQueueName);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", initialTemplate)
.when().post("/").then().statusCode(200);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks").formParam("StackName", stackName)
.when().post("/").then().statusCode(200).body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
String beforeXml = given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackResources").formParam("StackName", stackName)
.when().post("/").then().statusCode(200).extract().body().asString();
String oldDeadLetterUrl = physicalIdOf(beforeXml, "DeadLetterQueue");
String mainQueueUrl = physicalIdOf(beforeXml, "MainQueue");
String oldDeadLetterArn = queueAttribute(oldDeadLetterUrl, "QueueArn");
assertTrue(queueAttribute(mainQueueUrl, "RedrivePolicy").contains(oldDeadLetterArn));
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack").formParam("StackName", stackName)
.formParam("TemplateBody", updatedTemplate)
.when().post("/").then().statusCode(200);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks").formParam("StackName", stackName)
.when().post("/").then().statusCode(200).body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"));
String afterXml = given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackResources").formParam("StackName", stackName)
.when().post("/").then().statusCode(200).extract().body().asString();
String newDeadLetterUrl = physicalIdOf(afterXml, "DeadLetterQueue");
String newDeadLetterArn = queueAttribute(newDeadLetterUrl, "QueueArn");
assertNotEquals(oldDeadLetterArn, newDeadLetterArn);
assertTrue(queueAttribute(mainQueueUrl, "RedrivePolicy").contains(newDeadLetterArn));
deleteStack(stackName);
}
@Test
void changeSetIncludesDependentQueueWhenReferencedQueueIsReplaced() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "probe-sqs-cs-" + suffix;
String changeSetName = "cs-" + suffix;
String oldDeadLetterName = "probe-dlq-old-" + suffix;
String newDeadLetterName = "probe-dlq-new-" + suffix;
String mainQueueName = "probe-main-" + suffix;
String initialTemplate = redriveTemplate(oldDeadLetterName, mainQueueName);
String updatedTemplate = redriveTemplate(newDeadLetterName, mainQueueName);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", initialTemplate)
.when().post("/").then().statusCode(200);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks").formParam("StackName", stackName)
.when().post("/").then().statusCode(200).body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateChangeSet").formParam("StackName", stackName)
.formParam("ChangeSetName", changeSetName)
.formParam("ChangeSetType", "UPDATE")
.formParam("TemplateBody", updatedTemplate)
.when().post("/").then().statusCode(200);
String describeXml = given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeChangeSet").formParam("StackName", stackName)
.formParam("ChangeSetName", changeSetName)
.when().post("/").then().statusCode(200).extract().body().asString();
assertTrue(describeXml.contains("<LogicalResourceId>DeadLetterQueue</LogicalResourceId>"));
assertTrue(describeXml.contains("<LogicalResourceId>MainQueue</LogicalResourceId>"));
assertTrue(describeXml.contains("<Replacement>True</Replacement>"));
deleteStack(stackName);
}
@Test
void unchangedBucketRetainsCorsWhenReferencedLogGroupUpdatesInPlace() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "probe-s3-cors-" + suffix;
String bucketName = "probe-bucket-cors-" + suffix;
String logGroupName = "/cfn/log-group-" + suffix;
String initialTemplate = """
{
"Resources": {
"LogGroup": {
"Type": "AWS::Logs::LogGroup",
"Properties": {"LogGroupName": "%s", "RetentionInDays": 7}
},
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": "%s",
"Tags": [{"Key": "LogGroupRef", "Value": {"Ref": "LogGroup"}}]
}
}
}
}
""".formatted(logGroupName, bucketName);
String updatedTemplate = """
{
"Resources": {
"LogGroup": {
"Type": "AWS::Logs::LogGroup",
"Properties": {"LogGroupName": "%s", "RetentionInDays": 14}
},
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": "%s",
"Tags": [{"Key": "LogGroupRef", "Value": {"Ref": "LogGroup"}}]
}
}
}
}
""".formatted(logGroupName, bucketName);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", initialTemplate)
.when().post("/").then().statusCode(200);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks").formParam("StackName", stackName)
.when().post("/").then().statusCode(200).body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
String corsXml = """
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>http://example.com</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
</CORSRule>
</CORSConfiguration>
""";
given().contentType("application/xml").body(corsXml)
.when().put("/" + bucketName + "?cors")
.then().statusCode(200);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack").formParam("StackName", stackName)
.formParam("TemplateBody", updatedTemplate)
.when().post("/").then().statusCode(200);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks").formParam("StackName", stackName)
.when().post("/").then().statusCode(200).body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"));
given()
.when().get("/" + bucketName + "?cors")
.then().statusCode(200)
.body(containsString("http://example.com"));
deleteStack(stackName);
}
private static String redriveTemplate(String deadLetterQueueName, String mainQueueName) {
return """
{
"Resources": {
"DeadLetterQueue": {
"Type": "AWS::SQS::Queue",
"Properties": {"QueueName": "%s"}
},
"MainQueue": {
"Type": "AWS::SQS::Queue",
"Properties": {
"QueueName": "%s",
"RedrivePolicy": {
"deadLetterTargetArn": {"Fn::GetAtt": ["DeadLetterQueue", "Arn"]},
"maxReceiveCount": 3
}
}
}
}
}
""".formatted(deadLetterQueueName, mainQueueName);
}
@Test
void ecrRepository() {
assertUnchangedResourceSurvivesUpdate("ecr", """
@@ -348,4 +558,151 @@ class CfnUnchangedResourceUpdateIntegrationTest {
"Properties": {"BucketName": "probe-bucket-SUFFIX"}
}""");
}
@Test
void outputsOnlyUpdate_skipsUnchangedResources() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "probe-outputs-only-" + suffix;
String queueName = "probe-q-" + suffix;
String initialTemplate = """
{
"Resources": {
"Queue": {
"Type": "AWS::SQS::Queue",
"Properties": {"QueueName": "%s"}
}
}
}
""".formatted(queueName);
String updatedTemplate = """
{
"Resources": {
"Queue": {
"Type": "AWS::SQS::Queue",
"Properties": {"QueueName": "%s"}
}
},
"Outputs": {
"QueueArn": {"Value": "static-output"}
}
}
""".formatted(queueName);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", initialTemplate)
.when().post("/").then().statusCode(200);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks").formParam("StackName", stackName)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack").formParam("StackName", stackName)
.formParam("TemplateBody", updatedTemplate)
.when().post("/").then().statusCode(200);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks").formParam("StackName", stackName)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
.body(containsString("<OutputKey>QueueArn</OutputKey>"));
// Queue was unchanged, so it should have only CREATE_IN_PROGRESS / CREATE_COMPLETE events,
// never UPDATE_IN_PROGRESS or UPDATE_COMPLETE.
String events = given()
.contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackEvents").formParam("StackName", stackName)
.when().post("/").then().statusCode(200)
.extract().body().asString();
List<String> queueStatuses = XmlParser.extractGroups(events, "member").stream()
.filter(member -> "Queue".equals(member.get("LogicalResourceId")))
.map(member -> member.get("ResourceStatus"))
.toList();
assertTrue(queueStatuses.contains("CREATE_COMPLETE"));
assertFalse(queueStatuses.contains("UPDATE_IN_PROGRESS"));
assertFalse(queueStatuses.contains("UPDATE_COMPLETE"));
deleteStack(stackName);
}
@Test
void createChangeSet_updateRestApiAndUserPoolRename_reportsReplacementFalse() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "probe-cs-rename-" + suffix;
String changeSetName = "cs-rename-" + suffix;
String initialTemplate = """
{
"Resources": {
"Api": {
"Type": "AWS::ApiGateway::RestApi",
"Properties": {"Name": "api-initial-%s"}
},
"Pool": {
"Type": "AWS::Cognito::UserPool",
"Properties": {"UserPoolName": "pool-initial-%s"}
}
}
}
""".formatted(suffix, suffix);
String updatedTemplate = """
{
"Resources": {
"Api": {
"Type": "AWS::ApiGateway::RestApi",
"Properties": {"Name": "api-renamed-%s"}
},
"Pool": {
"Type": "AWS::Cognito::UserPool",
"Properties": {"UserPoolName": "pool-renamed-%s"}
}
}
}
""".formatted(suffix, suffix);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", initialTemplate)
.when().post("/").then().statusCode(200);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks").formParam("StackName", stackName)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", changeSetName)
.formParam("ChangeSetType", "UPDATE")
.formParam("TemplateBody", updatedTemplate)
.when().post("/").then().statusCode(200);
String desc = given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", changeSetName)
.when().post("/").then().statusCode(200)
.extract().body().asString();
List<Map<String, String>> members = XmlParser.extractGroups(desc, "ResourceChange");
Map<String, String> apiChange = members.stream()
.filter(m -> "Api".equals(m.get("LogicalResourceId")))
.findFirst()
.orElseThrow();
assertEquals("Modify", apiChange.get("Action"));
assertEquals("False", apiChange.get("Replacement"));
Map<String, String> poolChange = members.stream()
.filter(m -> "Pool".equals(m.get("LogicalResourceId")))
.findFirst()
.orElseThrow();
assertEquals("Modify", poolChange.get("Action"));
assertEquals("False", poolChange.get("Replacement"));
deleteStack(stackName);
}
}
@@ -1,12 +1,20 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Covers how AWS::AutoScaling::AutoScalingGroup resolves a launch template when it is provisioned by
@@ -61,6 +69,19 @@ class CloudFormationAsgLaunchTemplateIntegrationTest {
.statusCode(200);
}
private void updateStack(String stackName, String template) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
}
private String describeStacks(String stackName) {
return given()
.contentType("application/x-www-form-urlencoded")
@@ -309,4 +330,251 @@ class CloudFormationAsgLaunchTemplateIntegrationTest {
assertThat(describeStacks(stackName),
containsString("Value of property OnDemandBaseCapacity must be an integer."));
}
@Test
void asgUpdatesWhenLaunchTemplateBumpsVersionInPlace() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-lt-bump-stack-" + suffix;
String asgName = "cfn-asg-bump-" + suffix;
String ltName = "cfn-lt-bump-" + suffix;
String queueName = "cfn-q-bump-" + suffix;
String template1 = """
{
"Resources": {
"Lt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateName": "%s",
"LaunchTemplateData": {"ImageId": "ami-12345678", "InstanceType": "t3.micro"}
}
},
"Asg": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AutoScalingGroupName": "%s",
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}
},
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"AvailabilityZones": ["us-east-1a"]
}
},
"Queue": {
"Type": "AWS::SQS::Queue",
"Properties": {"QueueName": "%s"}
}
}
}
""".formatted(ltName, asgName, queueName);
String template2 = """
{
"Resources": {
"Lt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateName": "%s",
"LaunchTemplateData": {"ImageId": "ami-12345678", "InstanceType": "t3.small"}
}
},
"Asg": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AutoScalingGroupName": "%s",
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}
},
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"AvailabilityZones": ["us-east-1a"]
}
},
"Queue": {
"Type": "AWS::SQS::Queue",
"Properties": {"QueueName": "%s"}
}
}
}
""".formatted(ltName, asgName, queueName);
createStack(stackName, template1);
assertStackCreated(stackName);
assertThat(describeAutoScalingGroup(asgName), containsString("<Version>1</Version>"));
// DescribeChangeSet must include ASG with Action=Modify, Replacement=False
String csName = "cs-" + Long.toString(System.nanoTime(), 36);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", csName)
.formParam("ChangeSetType", "UPDATE")
.formParam("TemplateBody", template2)
.when()
.post("/")
.then()
.statusCode(200);
String csXml = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", csName)
.when()
.post("/")
.then()
.statusCode(200)
.extract().body().asString();
List<Map<String, String>> resourceChanges = XmlParser.extractGroups(csXml, "ResourceChange");
Map<String, String> asgChange = resourceChanges.stream()
.filter(m -> "Asg".equals(m.get("LogicalResourceId")))
.findFirst()
.orElse(null);
assertNotNull(asgChange, "DescribeChangeSet must preview ASG update when LaunchTemplate version changes");
assertEquals("Modify", asgChange.get("Action"));
assertEquals("False", asgChange.get("Replacement"));
updateStack(stackName, template2);
String describe = describeStacks(stackName);
assertThat(describe, containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"));
// ASG must have updated to version 2 because Fn::GetAtt on LatestVersionNumber changed
assertThat(describeAutoScalingGroup(asgName), containsString("<Version>2</Version>"));
// Queue was unchanged and doesn't reference Lt, so it must not have received UPDATE_COMPLETE
String events = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackEvents")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.extract().body().asString();
List<String> asgStatuses = XmlParser.extractGroups(events, "member").stream()
.filter(m -> "Asg".equals(m.get("LogicalResourceId")))
.map(m -> m.get("ResourceStatus"))
.toList();
assertTrue(asgStatuses.contains("UPDATE_COMPLETE"));
List<String> queueStatuses = XmlParser.extractGroups(events, "member").stream()
.filter(m -> "Queue".equals(m.get("LogicalResourceId")))
.map(m -> m.get("ResourceStatus"))
.toList();
assertTrue(queueStatuses.contains("CREATE_COMPLETE"));
assertFalse(queueStatuses.contains("UPDATE_COMPLETE"));
}
@Test
void asgRollsBackWhenLaterResourceFails() {
String suffix = Long.toString(System.nanoTime(), 36);
String ltName = "cfn-lt-rb-" + suffix;
String asgName = "cfn-asg-rb-" + suffix;
String stackName = "cfn-asg-rb-stack-" + suffix;
String queueName = "cfn-rb-q-" + suffix;
String template1 = """
{
"Resources": {
"Lt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateName": "%s",
"LaunchTemplateData": {
"ImageId": "ami-12345678",
"InstanceType": "t3.micro"
}
}
},
"Asg": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AutoScalingGroupName": "%s",
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}
},
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"AvailabilityZones": ["us-east-1a"]
}
},
"Queue": {
"Type": "AWS::SQS::Queue",
"DependsOn": ["Asg"],
"Properties": {"QueueName": "%s"}
}
}
}
""".formatted(ltName, asgName, queueName);
String template2 = """
{
"Resources": {
"Lt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateName": "%s",
"LaunchTemplateData": {
"ImageId": "ami-87654321",
"InstanceType": "t3.small"
}
}
},
"Asg": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AutoScalingGroupName": "%s",
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}
},
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"AvailabilityZones": ["us-east-1a"],
"DesiredCapacityType": "units",
"CapacityRebalance": true,
"MaxInstanceLifetime": 86400,
"DefaultInstanceWarmup": 300
}
},
"Queue": {
"Type": "AWS::SQS::Queue",
"DependsOn": ["Asg"],
"Properties": {
"QueueName": "%s",
"FifoQueue": true
}
}
}
}
""".formatted(ltName, asgName, queueName);
createStack(stackName, template1);
assertStackCreated(stackName);
assertThat(describeAutoScalingGroup(asgName), containsString("<Version>1</Version>"));
updateStack(stackName, template2);
String describe = describeStacks(stackName);
assertThat(describe, containsString("<StackStatus>UPDATE_ROLLBACK_COMPLETE</StackStatus>"));
// ASG must have rolled back to Version 1
String asg = describeAutoScalingGroup(asgName);
assertThat(asg, containsString("<Version>1</Version>"));
assertThat(asg, containsString("<DesiredCapacityType>units</DesiredCapacityType>"));
assertThat(asg, containsString("<CapacityRebalance>false</CapacityRebalance>"));
assertThat(asg, containsString("<MaxInstanceLifetime>0</MaxInstanceLifetime>"));
assertThat(asg, not(containsString("<DefaultInstanceWarmup>")));
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.AfterEach;
@@ -8,10 +9,13 @@ import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* Covers three ways {@code computeChangeSetChanges} previously misreported a change set's diff:
@@ -708,4 +712,168 @@ class CloudFormationChangeSetDiffIntegrationTest {
.body(containsString("<LogicalResourceId>Q</LogicalResourceId>"))
.body(containsString("<Action>Remove</Action>"));
}
@Test
void inPlaceAttributeChangePullsInDependentResourceInChangeSet() {
String stackName = "cs-diff-attr-change-stack";
stacksToDelete.add(stackName);
String template1 = """
{
"Resources": {
"Lt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateName": "cs-diff-lt",
"LaunchTemplateData": {
"ImageId": "ami-12345678",
"InstanceType": "t3.micro"
}
}
},
"Asg": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AutoScalingGroupName": "cs-diff-asg",
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}
},
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"AvailabilityZones": ["us-east-1a"]
}
},
"DefaultAsg": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AutoScalingGroupName": "cs-diff-default-asg",
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "DefaultVersionNumber"]}
},
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"AvailabilityZones": ["us-east-1a"]
}
},
"UnchangedQueue": {
"Type": "AWS::SQS::Queue",
"Properties": {
"QueueName": "cs-diff-unchanged-q"
}
}
}
}
""";
String template2 = """
{
"Resources": {
"Lt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateName": "cs-diff-lt",
"LaunchTemplateData": {
"ImageId": "ami-87654321",
"InstanceType": "t3.small"
}
}
},
"Asg": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AutoScalingGroupName": "cs-diff-asg",
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}
},
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"AvailabilityZones": ["us-east-1a"]
}
},
"DefaultAsg": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AutoScalingGroupName": "cs-diff-default-asg",
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "DefaultVersionNumber"]}
},
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"AvailabilityZones": ["us-east-1a"]
}
},
"UnchangedQueue": {
"Type": "AWS::SQS::Queue",
"Properties": {
"QueueName": "cs-diff-unchanged-q"
}
}
}
}
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template1)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "attr-change-cs")
.formParam("ChangeSetType", "UPDATE")
.formParam("TemplateBody", template2)
.when()
.post("/")
.then()
.statusCode(200);
String desc = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "attr-change-cs")
.when()
.post("/")
.then()
.statusCode(200)
.extract().body().asString();
List<Map<String, String>> changes = XmlParser.extractGroups(desc, "ResourceChange");
Map<String, String> ltChange = changes.stream()
.filter(m -> "Lt".equals(m.get("LogicalResourceId")))
.findFirst()
.orElseThrow();
assertEquals("Modify", ltChange.get("Action"));
assertEquals("False", ltChange.get("Replacement"));
Map<String, String> asgChange = changes.stream()
.filter(m -> "Asg".equals(m.get("LogicalResourceId")))
.findFirst()
.orElseThrow();
assertEquals("Modify", asgChange.get("Action"));
assertEquals("False", asgChange.get("Replacement"));
boolean unchangedDefaultDependentIncluded = changes.stream()
.anyMatch(m -> "DefaultAsg".equals(m.get("LogicalResourceId")));
assertFalse(unchangedDefaultDependentIncluded);
boolean unchangedQueueIncluded = changes.stream()
.anyMatch(m -> "UnchangedQueue".equals(m.get("LogicalResourceId")));
assertFalse(unchangedQueueIncluded);
}
}
@@ -466,6 +466,58 @@ class CloudFormationDeletionPolicyIntegrationTest {
}
}
@Test
void updateParentStackWithUnchangedNestedStackSucceedsEvenIfTemplateUrlUnavailable() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String functionName = "cfn-nested-keep-func-" + suffix;
String bucketName = "nested-stack-templates-" + suffix;
String templateUrl = bucketName + "/child-lambda-keep.json";
String initialParentTemplate = """
{
"Resources": {
"ChildStack": {
"Type": "AWS::CloudFormation::Stack",
"Properties": { "TemplateURL": "http://localhost/%s" }
}
}
}
""".formatted(templateUrl);
String updatedParentTemplate = """
{
"Resources": {
"ChildStack": {
"Type": "AWS::CloudFormation::Stack",
"Properties": { "TemplateURL": "http://localhost/%s" }
}
},
"Outputs": {
"ParentOut": { "Value": "static" }
}
}
""".formatted(templateUrl);
String stackName = "parent-nested-keep-" + suffix;
given().header("Authorization", CUSTOM_AUTH).contentType("application/xml").body(EU_WEST_1_BUCKET)
.when().put("/" + bucketName).then().statusCode(200);
given().header("Authorization", CUSTOM_AUTH)
.contentType("application/json").body(nestedLambdaTemplate(functionName, 3))
.when().put("/" + templateUrl).then().statusCode(200);
String parentStackId = createStack(stackName, initialParentTemplate, CUSTOM_AUTH);
try {
awaitStackStatus(parentStackId, "CREATE_COMPLETE", CUSTOM_AUTH);
// Delete the template object from S3 so TemplateURL is no longer reachable
given().header("Authorization", CUSTOM_AUTH)
.when().delete("/" + templateUrl).then().statusCode(204);
// Parent update modifying only Outputs: unchanged nested stack is skipped, so missing TemplateURL doesn't fail update
updateStack(stackName, updatedParentTemplate, CUSTOM_AUTH);
awaitStackStatus(parentStackId, "UPDATE_COMPLETE", CUSTOM_AUTH);
} finally {
deleteStack(stackName);
}
}
@Test
void nestedStackWithNonEmptyBucketFailsDeletionOnUpdate_leavesChildAsDeleteFailedAndTracksInParent() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
@@ -734,7 +734,7 @@ class CloudFormationEventBusIntegrationTest {
callEventBridge("AWSEvents.CreateEventBus",
"{\"Name\":\"" + busName + "\",\"Description\":\"external\"}", 200);
updateStack(stackName, template);
updateStack(stackName, eventBusOnlyTemplate(busName, "updating"));
assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 200);
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
@@ -8,9 +9,11 @@ import org.junit.jupiter.params.provider.MethodSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -157,6 +160,7 @@ class CloudFormationNamedResourceIdenticalUpdateIntegrationTest {
boolean noUpdates = update.statusCode() == 400 && update.asString().contains("No updates");
if (!noUpdates) {
expect(stackName, "UPDATE_COMPLETE", "UPDATE");
assertNoResourceUpdateEvents(stackName);
}
cfn("DeleteStack", stackName, null);
@@ -194,4 +198,16 @@ class CloudFormationNamedResourceIdenticalUpdateIntegrationTest {
}
return reasons.isEmpty() ? "" : " | " + String.join(" | ", reasons);
}
private static void assertNoResourceUpdateEvents(String stackName) {
String eventXml = cfn("DescribeStackEvents", stackName, null).asString();
List<Map<String, String>> events = XmlParser.extractGroups(eventXml, "member");
for (Map<String, String> event : events) {
if (event.get("LogicalResourceId") != null
&& !stackName.equals(event.get("LogicalResourceId"))) {
assertFalse(event.get("ResourceStatus").startsWith("UPDATE_"),
"Identical update should not update resource " + event.get("LogicalResourceId"));
}
}
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
@@ -8,6 +9,8 @@ import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A create that fails rolls its resources back and leaves the stack in ROLLBACK_COMPLETE, which
@@ -166,6 +169,161 @@ class CloudFormationRollbackCompleteUpdateIntegrationTest {
deleteStack(stackName);
}
@Test
void failedUpdateDoesNotRollbackUnchangedResourcesWithoutRollbackSupport() {
assertFailedUpdateDoesNotRollbackUnchangedResources(false);
}
@Test
void failedExecutedChangeSetDoesNotRollbackUnchangedResourcesWithoutRollbackSupport() {
assertFailedUpdateDoesNotRollbackUnchangedResources(true);
}
private void assertFailedUpdateDoesNotRollbackUnchangedResources(boolean executeChangeSet) {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = (executeChangeSet ? "unchanged-resource-cs-" : "unchanged-resource-update-") + suffix;
String changeSetName = "failed-update-" + suffix;
String initialTemplate = """
{"Resources":{
"LogGroup":{"Type":"AWS::Logs::LogGroup","Properties":{"LogGroupName":"/cfn/rollback-%s"}},
"Bucket":{"Type":"AWS::S3::Bucket","Properties":{"BucketName":"cfn-rollback-%s"}}
}}
""".formatted(suffix, suffix);
String failingTemplate = """
{"Resources":{
"LogGroup":{"Type":"AWS::Logs::LogGroup","Properties":{"LogGroupName":"/cfn/rollback-%s"}},
"Bucket":{"Type":"AWS::S3::Bucket","Properties":{"BucketName":"cfn-rollback-%s"}},
"ZFail":{"Type":"AWS::CloudFormation::Stack","Properties":{}}
}}
""".formatted(suffix, suffix);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", initialTemplate)
.when()
.post("/")
.then()
.statusCode(200);
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
if (executeChangeSet) {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", changeSetName)
.formParam("ChangeSetType", "UPDATE")
.formParam("TemplateBody", failingTemplate)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ExecuteChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", changeSetName)
.when()
.post("/")
.then()
.statusCode(200);
} else {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "UpdateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", failingTemplate)
.when()
.post("/")
.then()
.statusCode(200);
}
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);
assertEquals("UPDATE_ROLLBACK_COMPLETE", state.status(), state.reason());
given()
.head("/cfn-rollback-" + suffix)
.then()
.statusCode(200);
given()
.header("X-Amz-Target", "Logs_20140328.DescribeLogGroups")
.contentType("application/x-amz-json-1.1")
.body("{\"logGroupNamePrefix\":\"/cfn/rollback-" + suffix + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("/cfn/rollback-" + suffix));
deleteStack(stackName);
}
@Test
void failedUpdateRollsBackDependentQueueWhenReferencedQueueWasReplaced() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "rollback-sqs-update-" + suffix;
String oldDlq = "dlq-old-" + suffix;
String newDlq = "dlq-new-" + suffix;
String mainQueue = "main-" + suffix;
String initialTemplate = """
{"Resources":{
"DeadLetterQueue":{"Type":"AWS::SQS::Queue","Properties":{"QueueName":"%s"}},
"MainQueue":{"Type":"AWS::SQS::Queue","Properties":{"QueueName":"%s","RedrivePolicy":{"deadLetterTargetArn":{"Fn::GetAtt":["DeadLetterQueue","Arn"]},"maxReceiveCount":3}}}
}}
""".formatted(oldDlq, mainQueue);
String failingTemplate = """
{"Resources":{
"DeadLetterQueue":{"Type":"AWS::SQS::Queue","Properties":{"QueueName":"%s"}},
"MainQueue":{"Type":"AWS::SQS::Queue","Properties":{"QueueName":"%s","RedrivePolicy":{"deadLetterTargetArn":{"Fn::GetAtt":["DeadLetterQueue","Arn"]},"maxReceiveCount":3}}},
"ZFail":{"Type":"AWS::CloudFormation::Stack","Properties":{}}
}}
""".formatted(newDlq, mainQueue);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", initialTemplate)
.when().post("/").then().statusCode(200);
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
String initialResources = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackResources")
.formParam("StackName", stackName)
.when().post("/").then().statusCode(200).extract().body().asString();
String mainQueueUrl = XmlParser.extractGroups(initialResources, "member").stream()
.filter(m -> "MainQueue".equals(m.get("LogicalResourceId")))
.map(m -> m.get("PhysicalResourceId")).findFirst().orElseThrow();
String oldDlqUrl = XmlParser.extractGroups(initialResources, "member").stream()
.filter(m -> "DeadLetterQueue".equals(m.get("LogicalResourceId")))
.map(m -> m.get("PhysicalResourceId")).findFirst().orElseThrow();
// Update with replaced DLQ and a failing resource
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "UpdateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", failingTemplate)
.when().post("/").then().statusCode(200);
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);
assertEquals("UPDATE_ROLLBACK_COMPLETE", state.status(), state.reason());
// Verify MainQueue still has the old DLQ in its redrive policy
String mainAttrs = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetQueueAttributes")
.formParam("QueueUrl", mainQueueUrl)
.formParam("AttributeName.1", "RedrivePolicy")
.when().post("/").then().statusCode(200).extract().body().asString();
assertTrue(mainAttrs.contains(oldDlq));
deleteStack(stackName);
}
// ── Helpers ───────────────────────────────────────────────────────────────
/** Creates a stack whose only resource fails, so it settles in ROLLBACK_COMPLETE. */
@@ -17,8 +17,10 @@ import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -26,6 +28,8 @@ import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -250,4 +254,88 @@ class AutoScalingGroupCfnProvisionerTest {
() -> provisioner.delete("AWS::AutoScaling::ScalingPolicy", "p", REGION));
verify(autoScaling, never()).deleteAutoScalingGroup(anyString(), anyString(), anyBoolean());
}
@Test
void rollbackUpdateRestoresSnapshotWhenPresent() {
AutoScalingGroup existing = group("my-asg");
existing.setLaunchTemplateId("lt-123");
existing.setLaunchTemplateVersion("1");
existing.setMinSize(1);
existing.setMaxSize(5);
existing.setDesiredCapacity(2);
existing.setAvailabilityZones(List.of("us-east-1a"));
when(autoScaling.describeAutoScalingGroups(eq(REGION), eq(List.of("my-asg"))))
.thenReturn(List.of(existing));
StackResource r = resource(GROUP, "Asg", "my-asg");
ObjectNode props = mapper.createObjectNode();
props.put("AutoScalingGroupName", "my-asg");
ObjectNode lt = props.putObject("LaunchTemplate");
lt.put("LaunchTemplateId", "lt-123");
lt.put("Version", "2");
props.put("MinSize", 3);
props.put("MaxSize", 8);
props.put("DesiredCapacity", 4);
props.putArray("AvailabilityZones").add("us-east-1a");
provisioner.provision(r, props, ctx("my-asg"));
String snapshot = r.getAttributes().get(CfnRollback.ASG_UPDATE_SNAPSHOT_ATTR);
assertTrue(snapshot != null && !snapshot.isBlank());
clearInvocations(autoScaling);
boolean rolledBack = provisioner.rollbackUpdate(r);
assertTrue(rolledBack);
ArgumentCaptor<Integer> minSizeCaptor = ArgumentCaptor.forClass(Integer.class);
ArgumentCaptor<Integer> maxSizeCaptor = ArgumentCaptor.forClass(Integer.class);
ArgumentCaptor<String> versionCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<AsgOptionalFields> optionalFieldsCaptor = ArgumentCaptor.forClass(AsgOptionalFields.class);
verify(autoScaling).updateAutoScalingGroup(
eq(REGION),
eq("my-asg"),
isNull(),
eq("lt-123"),
isNull(),
versionCaptor.capture(),
isNull(),
minSizeCaptor.capture(),
maxSizeCaptor.capture(),
anyInt(),
anyInt(),
any(),
any(),
any(),
anyInt(),
any(),
optionalFieldsCaptor.capture()
);
assertEquals("1", versionCaptor.getValue());
assertEquals(1, minSizeCaptor.getValue());
assertEquals(5, maxSizeCaptor.getValue());
AsgOptionalFields optionalFields = optionalFieldsCaptor.getValue();
assertEquals("units", optionalFields.desiredCapacityType());
assertEquals(Boolean.FALSE, optionalFields.capacityRebalance());
assertEquals(0, optionalFields.maxInstanceLifetime());
assertEquals(AsgOptionalFields.DEFAULT_INSTANCE_WARMUP_REMOVAL_SENTINEL,
optionalFields.defaultInstanceWarmup());
// Subsequent rollback should return false since snapshot is spent
assertFalse(provisioner.rollbackUpdate(r));
}
@Test
void clearUpdateRemovesSnapshotAttribute() {
StackResource r = resource(GROUP, "Asg", "my-asg");
r.getAttributes().put(CfnRollback.ASG_UPDATE_SNAPSHOT_ATTR, "{\"name\":\"my-asg\"}");
provisioner.clearUpdate(r);
assertNull(r.getAttributes().get(CfnRollback.ASG_UPDATE_SNAPSHOT_ATTR));
}
}
@@ -24,8 +24,10 @@ import java.util.Set;
import java.util.zip.GZIPOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
@@ -205,6 +207,40 @@ class Ec2LaunchTemplateCfnProvisionerTest {
assertEquals(List.of("sg-1", "sg-2"), captor.getValue().getSecurityGroupIds());
}
@Test
void rollbackUpdateDeletesCreatedVersionAndRestoresAttributes() {
LaunchTemplate existing = template("lt-abc123");
existing.setLaunchTemplateName("my-lt");
existing.setLatestVersionNumber("1");
existing.setDefaultVersionNumber("1");
when(ec2.describeLaunchTemplates(eq("us-east-1"), eq(List.of("lt-abc123")), eq(List.of()), any()))
.thenReturn(List.of(existing));
LaunchTemplate updated = template("lt-abc123");
updated.setLaunchTemplateName("my-lt");
updated.setLatestVersionNumber("2");
updated.setDefaultVersionNumber("1");
when(ec2.createLaunchTemplateVersion(eq("us-east-1"), eq("lt-abc123"), isNull(), isNull(), any()))
.thenReturn(updated);
ObjectNode props = mapper.createObjectNode().put("LaunchTemplateName", "my-lt");
props.set("LaunchTemplateData", mapper.createObjectNode().put("ImageId", "ami-v2"));
StackResource r = resource("Lt");
r.setPhysicalId("lt-abc123");
provisioner.provision(r, props, ctx());
assertEquals("2", r.getAttributes().get("LatestVersionNumber"));
boolean rolledBack = provisioner.rollbackUpdate(r);
assertTrue(rolledBack);
verify(ec2).deleteLaunchTemplateVersion("us-east-1", "lt-abc123", "2");
assertEquals("1", r.getAttributes().get("LatestVersionNumber"));
assertEquals("1", r.getAttributes().get("DefaultVersionNumber"));
// Second rollback without snapshot should return false
assertFalse(provisioner.rollbackUpdate(r));
}
@Test
void provisionedUserDataIsDecodedForInstanceLaunch() {
when(ec2.createLaunchTemplate(any(), any(), any(), any())).thenReturn(template("lt-userdata"));