fix(cloudformation): propagate tags to nested stacks (#7383)

This commit is contained in:
Rashen Anupama authored and GitHub committed 2026-11-03 16:47:32 -04:00
1 parent 08b6049de7
commit fad0493169
11 files changed
+787 -75

No files matched your search

+19
View File
@@ -951,6 +951,25 @@ module for inline `ZipFile` code follows that URL's scheme and port and does not
this callback. The HTTPS/443 requirement applies to handlers with the hard-coded behavior above,
not to every custom-resource handler.
## Nested stack tags
Stack-level tags passed to `CreateStack` or `UpdateStack` are applied to nested stacks as well as
the root stack. `DescribeStacks` on a nested stack returns its inherited tags, including through
multiple levels of nesting, and the tags its own `Tags` property declares take precedence over the
inherited ones. Updating the root stack's tags updates its nested stacks even when their templates
have not changed, and a template holding a nested stack is never refused as having nothing to
change: AWS reads the child template again and counts the nested stack as a change on every update.
Every update requires a readable child template URL, including an output-only parent update.
If the child template is missing, the child update fails and the parent rolls back while the
existing child's deployment remains intact.
When a later resource fails the parent update, a nested stack the update re-provisioned with the
template and the parameter values it already ran gets its prior tags back, its descendants'
inherited tags included. A nested stack the update re-deployed with a different template or
different parameter values, including in a descendant, is not restored: the stack ends `UPDATE_ROLLBACK_FAILED` rather than
claiming a nested deployment rollback Floci does not implement yet.
## Failed update rollbacks
When an update fails, Floci rolls back the resources it changed. A resource whose rollback fails
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsPartitions;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
@@ -29,6 +30,7 @@ import io.github.hectorvent.floci.services.cloudformation.model.TemplateSummary;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ProvisionContext;
import io.github.hectorvent.floci.services.cloudformation.provisioners.UpdateCleanupResult;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
@@ -961,7 +963,7 @@ public class CloudFormationService implements ResourceProvider {
: !oldDef.equals(newDef)
|| referencesAnyParameter(newDef, changedParams)
|| referencesAnyCondition(newDef, changedConditions))
|| ("AWS::CloudFormation::Stack".equals(resourceType) && isNestedStackChanged(stack, logicalId, newDef, region, accountId)))) {
|| "AWS::CloudFormation::Stack".equals(resourceType))) {
boolean typeChanged = !oldDef.path("Type").asText().equals(resourceType);
boolean replacement = typeChanged
|| requiresReplacement(resourceType, oldDef.path("Properties"), newDef.path("Properties"), changedParams, changedConditions);
@@ -2037,7 +2039,14 @@ public class CloudFormationService implements ResourceProvider {
private void executeTemplate(Stack stack, String templateBody, Map<String, String> params,
Map<String, String> tags,
boolean isCreate, String region, String accountId) {
Map<String, String> previousTags = stack.tagsSnapshot();
Map<String, String> operationTags = tags == null ? previousTags : new LinkedHashMap<>(tags);
boolean stackTagsChanged = !operationTags.equals(previousTags);
// Taken before the replacement below, so the snapshot carries the prior tags for a rollback.
StackUpdateSnapshot previousState = snapshotForUpdate(stack);
if (tags != null) {
stack.replaceTags(tags);
}
boolean updateCommitted = false;
Set<String> attemptedResourceIds = new LinkedHashSet<>();
try {
@@ -2093,6 +2102,13 @@ public class CloudFormationService implements ResourceProvider {
// Process resources in order
JsonNode resources = template.path("Resources");
if (!isCreate && stackTagsChanged && resources.isObject()) {
resources.fields().forEachRemaining(entry -> {
if ("AWS::CloudFormation::Stack".equals(entry.getValue().path("Type").asText())) {
changedResourceIds.add(entry.getKey());
}
});
}
Map<String, String> physicalIds = new LinkedHashMap<>();
Map<String, Map<String, String>> resourceAttrs = new LinkedHashMap<>();
@@ -2181,7 +2197,7 @@ public class CloudFormationService implements ResourceProvider {
if ("AWS::CloudFormation::Stack".equals(type)) {
resource = executeNestedStack(stack, logicalId,
props.isMissingNode() ? null : props,
engine, region, accountId, isCreate, previousResource);
engine, operationTags, region, accountId, isCreate, previousResource);
} else {
JsonNode previousDefinition = previousResources.path(logicalId);
JsonNode priorProps = type.equals(previousDefinition.path("Type").asText())
@@ -2375,12 +2391,16 @@ public class CloudFormationService implements ResourceProvider {
exportName, value, stack.getStackName());
});
if (isCreate) {
stack.replaceTags(operationTags);
}
if (!isCreate) {
updateCommitted = true;
stack.replaceTags(operationTags);
stack.getResources().values().forEach(resource -> resource.getAttributes()
.remove(CfnRollback.NESTED_STACK_UPDATE_SNAPSHOT_ATTR));
refreshTemplateUses(stack, resources, conditions, physicalIds);
if (tags != null) {
stack.replaceTags(tags);
}
if (hasReplacementUpdates(stack) || hasRemovedOrConditionFalseResources(stack, resources, conditions)) {
stack.setStatus("UPDATE_COMPLETE_CLEANUP_IN_PROGRESS");
stack.setLastUpdatedTime(now());
@@ -2437,8 +2457,10 @@ public class CloudFormationService implements ResourceProvider {
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "CREATE_FAILED", e.getMessage());
stack.setStatus("CREATE_FAILED");
stack.replaceTags(operationTags);
persistStack(stack);
} else {
stack.replaceTags(previousTags);
rollbackFailedUpdate(
stack, region, previousState, attemptedResourceIds, e.getMessage());
}
@@ -2464,36 +2486,6 @@ public class CloudFormationService implements ResourceProvider {
}
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.
*
@@ -2544,6 +2536,9 @@ public class CloudFormationService implements ResourceProvider {
LOG.errorv("Stack {0} rollback failed: {1}", stack.getStackName(), rollbackReason);
}
} else {
if (previousState.tags() != null) {
stack.replaceTags(previousState.tags());
}
rollbackFailedUpdate(
stack, region, previousState, attemptedResourceIds,
reason);
@@ -2880,6 +2875,10 @@ public class CloudFormationService implements ResourceProvider {
// serving the failed update's attempted values.
stack.replaceParameters(previousState.parameters());
stack.replaceResolvedParameters(previousState.resolvedParameters());
// Older persisted snapshots have no tag state to restore. An explicit empty map still clears tags.
if (previousState.tags() != null) {
stack.replaceTags(previousState.tags());
}
if (rollbackFailures.isEmpty()) {
stack.setTemplateBody(previousState.templateBody());
// GetTemplate reads originalTemplateBody for TemplateStage=Original and templateBody
@@ -2962,7 +2961,8 @@ public class CloudFormationService implements ResourceProvider {
resource.setStatusReason(reason);
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "UPDATE_FAILED", reason);
} else if ("true".equals(resource.getAttributes().remove(
} else if (rollbackNestedStackTags(resource, region, ownerAccount(stack))
|| "true".equals(resource.getAttributes().remove(
CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR))
|| dispatcher.rollbackUpdate(resource,
event -> addEvent(stack, resource.getLogicalId(), event.getPhysicalResourceId(),
@@ -2998,6 +2998,93 @@ public class CloudFormationService implements ResourceProvider {
return failures;
}
/**
* Restores the tags a nested stack carried before an in-flight update re-provisioned it, along
* with the inherited tags its descendants took from each changed level. The resource's saved
* record holds the child's deployment from before that call, so a template the update replaced
* in S3 cannot carry the restore unseen: a child whose template body or given parameters now
* differ from it is owed a deployment rollback this build does not implement, and reports false
* so the walker's own arms settle the stack in UPDATE_ROLLBACK_FAILED rather than claiming the
* prior deployment is live. A resource carrying no record was not touched by this update, and
* one whose child is gone cannot be compared; both fall through the same way.
*/
private boolean rollbackNestedStackTags(StackResource resource, String region, String accountId) {
JsonNode saved = CfnRollback.updateSnapshot(
resource, CfnRollback.NESTED_STACK_UPDATE_SNAPSHOT_ATTR);
if (saved == null) {
return false;
}
Stack childStack = resource.getPhysicalId() == null ? null
: resolveStack(resource.getPhysicalId(), region, accountId);
if (childStack == null) {
return false;
}
Map<String, String> priorTags;
try {
if (!savedChildDeploymentMatches(childStack, saved)) {
return false;
}
priorTags = objectMapper.convertValue(
saved.path("tags"), new TypeReference<Map<String, String>>() {});
} catch (RuntimeException e) {
LOG.warnv("Could not read the saved nested stack deployment for {0}: {1}",
resource.getLogicalId(), e.getMessage());
return false;
}
if (priorTags == null || !restoreSavedDescendantTags(saved, region, accountId)) {
return false;
}
childStack.replaceTags(priorTags);
persistStack(childStack);
resource.getAttributes().remove(CfnRollback.NESTED_STACK_UPDATE_SNAPSHOT_ATTR);
return true;
}
/**
* Whether the child still runs the deployment the record saved: its template body and the
* parameter values it was given match, so only its tags moved and restoring them is the whole
* rollback owed. A saved field that will not read as the map or string this comparison needs
* throws, which the caller settles as an unrestorable record.
*/
private boolean savedChildDeploymentMatches(Stack childStack, JsonNode saved) {
if (!saved.path("templateBody").asText("").equals(childStack.getTemplateBody())) {
return false;
}
Map<String, String> savedParameters = objectMapper.convertValue(
saved.path("parameters"), new TypeReference<Map<String, String>>() {});
return savedParameters.equals(childStack.parametersSnapshot());
}
/** Restores captured tags without inferring whether an equal value was explicit or inherited. */
private boolean restoreSavedDescendantTags(JsonNode saved, String region, String accountId) {
Map<String, Map<String, String>> priorTags;
Map<String, String> priorDeployments;
try {
priorTags = objectMapper.convertValue(saved.path("descendantTags"), new TypeReference<>() {});
priorDeployments = objectMapper.convertValue(saved.path("descendantDeployments"), new TypeReference<>() {});
} catch (RuntimeException e) {
LOG.warnv("Could not read saved descendant tags: {0}", e.getMessage());
return false;
}
if (priorTags == null || priorDeployments == null || priorTags.values().stream().anyMatch(Objects::isNull)) {
return false;
}
Map<Stack, Map<String, String>> restores = new LinkedHashMap<>();
for (Map.Entry<String, Map<String, String>> entry : priorTags.entrySet()) {
Stack descendant = resolveStack(entry.getKey(), region, accountId);
if (descendant == null || "DELETE_COMPLETE".equals(descendant.getStatus())
|| !nestedDeploymentFingerprint(descendant).equals(priorDeployments.get(entry.getKey()))) {
return false;
}
restores.put(descendant, entry.getValue());
}
restores.forEach((descendant, tags) -> {
descendant.replaceTags(tags);
persistStack(descendant);
});
return true;
}
private void restoreOutputAndExportState(
Stack stack, String region, StackUpdateSnapshot previousState) {
RuntimeException storageFailure = null;
@@ -3114,7 +3201,8 @@ public class CloudFormationService implements ResourceProvider {
stack.outputsSnapshot(),
stack.exportsSnapshot(),
stack.outputExportNamesSnapshot(),
copyResources(stack.resourcesSnapshot()));
copyResources(stack.resourcesSnapshot()),
stack.tagsSnapshot());
}
private Map<String, StackResource> copyResources(
@@ -4273,7 +4361,8 @@ public class CloudFormationService implements ResourceProvider {
"CREATE_COMPLETE", "UPDATE_COMPLETE", "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS");
private StackResource executeNestedStack(Stack parentStack, String logicalId, JsonNode props,
CloudFormationTemplateEngine engine, String region,
CloudFormationTemplateEngine engine,
Map<String, String> inheritedTags, String region,
String accountId, boolean isCreate,
StackResource previousResource) {
StackResource resource = new StackResource();
@@ -4287,7 +4376,9 @@ public class CloudFormationService implements ResourceProvider {
return resource;
}
String childTemplate = fetchTemplateFromS3(templateUrl);
Stack childStack = previousResource == null || previousResource.getPhysicalId() == null ? null
: resolveStack(previousResource.getPhysicalId(), region, accountId);
boolean childCreate = isCreate || childStack == null;
String childStackName = parentStack.getStackName() + "-" + logicalId;
// Resolved as a property value: Parameters may be an Fn::If choosing between whole maps,
@@ -4308,6 +4399,22 @@ public class CloudFormationService implements ResourceProvider {
}
});
}
Map<String, String> childTags = new LinkedHashMap<>(inheritedTags);
childTags.putAll(ProvisionContext.resolveTags(props, "Tags", engine));
String childTemplate;
try {
childTemplate = fetchTemplateFromS3(templateUrl);
} catch (RuntimeException e) {
if (childCreate) {
throw e;
}
StackResource failedResource = copyResource(previousResource);
// The read failed before any child mutation, so its deployment needs no undo.
failedResource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true");
failedResource.setStatus("CREATE_FAILED");
failedResource.setStatusReason(e.getMessage());
return failedResource;
}
// CloudFormation creates or updates the child with these values, so the call fails as a
// CreateStack or UpdateStack would, before the child is created or changed: a parameter
// without a value, or a Fn::GetStackOutput where the child's template may not hold one
@@ -4321,20 +4428,18 @@ public class CloudFormationService implements ResourceProvider {
return resource;
}
Stack childStack = null;
boolean childCreate = isCreate || previousResource == null
|| previousResource.getPhysicalId() == null;
if (!childCreate) {
childStack = resolveStack(previousResource.getPhysicalId(), region, accountId);
childCreate = childStack == null;
}
if (childCreate) {
childStack = newStack(childStackName, newStackId(childStackName, region, accountId), region, accountId);
childStack.setStatus("CREATE_IN_PROGRESS");
stacks.put(stackKey(accountId, childStackName, region), childStack);
}
executeTemplate(childStack, childTemplate, childParams, null, childCreate, region, accountId);
if (!childCreate) {
resource.getAttributes().put(CfnRollback.NESTED_STACK_UPDATE_SNAPSHOT_ATTR,
savedChildDeployment(childStack, region, accountId).toString());
}
executeTemplate(childStack, childTemplate, childParams, childTags, childCreate, region, accountId);
resource.setPhysicalId(childStack.getStackId());
resource.getAttributes().put("Arn", childStack.getStackId());
@@ -4361,6 +4466,49 @@ public class CloudFormationService implements ResourceProvider {
return resource;
}
/**
* The child stack's own deployment before an update re-provisions it: the tags it ran with, its
* template body and the parameter values it was given. Descendant tags are captured separately;
* their templates, parameters and resources are not restored here.
*/
private ObjectNode savedChildDeployment(Stack stack, String region, String accountId) {
ObjectNode saved = objectMapper.createObjectNode();
saved.put("templateBody", stack.getTemplateBody());
saved.set("parameters", objectMapper.valueToTree(stack.parametersSnapshot()));
saved.set("tags", objectMapper.valueToTree(stack.tagsSnapshot()));
Map<String, Map<String, String>> descendantTags = new LinkedHashMap<>();
Map<String, String> descendantDeployments = new LinkedHashMap<>();
collectDescendantTags(stack, descendantTags, descendantDeployments, region, accountId);
saved.set("descendantTags", objectMapper.valueToTree(descendantTags));
saved.set("descendantDeployments", objectMapper.valueToTree(descendantDeployments));
return saved;
}
/** Captures tags and comparison fingerprints, never descendant state to re-provision. */
private void collectDescendantTags(Stack stack, Map<String, Map<String, String>> tags,
Map<String, String> deployments,
String region, String accountId) {
for (StackResource resource : stack.resourcesSnapshot().values()) {
if (!"AWS::CloudFormation::Stack".equals(resource.getResourceType())) {
continue;
}
Stack descendant = resource.getPhysicalId() == null ? null
: resolveStack(resource.getPhysicalId(), region, accountId);
if (descendant != null && !tags.containsKey(descendant.getStackId())) {
tags.put(descendant.getStackId(), descendant.tagsSnapshot());
deployments.put(descendant.getStackId(), nestedDeploymentFingerprint(descendant));
collectDescendantTags(descendant, tags, deployments, region, accountId);
}
}
}
private String nestedDeploymentFingerprint(Stack stack) {
ObjectNode deployment = objectMapper.createObjectNode();
deployment.put("templateBody", stack.getTemplateBody());
deployment.set("parameters", objectMapper.valueToTree(new TreeMap<>(stack.parametersSnapshot())));
return Digests.sha256Hex(deployment.toString());
}
/** Prefixes the keys {@link #recordTemplateUses} keeps, one per resource a definition names. */
private static final String TEMPLATE_USES_PREFIX = CfnRollback.USES_ATTR_PREFIX + "Resource.";
@@ -9,6 +9,8 @@ import java.util.Map;
* A stack's state from before an update, which the rollback of that update restores. A rollback
* that fails keeps it on the stack, so ContinueUpdateRollback can run the rollback again after the
* update that took it has returned, or after a restart.
*
* @param tags prior tags, or null when a legacy snapshot did not capture them
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@@ -20,5 +22,14 @@ public record StackUpdateSnapshot(
Map<String, String> outputs,
Map<String, String> exports,
Map<String, String> outputExportNames,
Map<String, StackResource> resources) {
Map<String, StackResource> resources,
Map<String, String> tags) {
public StackUpdateSnapshot(String templateBody, String originalTemplateBody,
Map<String, String> parameters, Map<String, String> resolvedParameters,
Map<String, String> outputs, Map<String, String> exports,
Map<String, String> outputExportNames, Map<String, StackResource> resources) {
this(templateBody, originalTemplateBody, parameters, resolvedParameters, outputs, exports,
outputExportNames, resources, null);
}
}
@@ -41,6 +41,17 @@ public final class CfnRollback {
*/
public static final String UPDATE_ROLLBACK_FAILURE_ATTR = "__FlociUpdateRollbackFailure";
/**
* Holds the child stack deployment a nested-stack resource carried before the update in flight
* re-provisioned it: the tags it ran with, its template body and the parameter values it was
* given. Descendant tags are captured too, without their deployment state. Written by
* {@code CloudFormationService.executeNestedStack} before it runs the child's template and
* spent once the update commits or the rollback restores the child's tags. A child whose live
* deployment no longer matches it is owed a template or parameter rollback this build defers,
* so the walker fails the stack honestly instead of restoring tags alone.
*/
public static final String NESTED_STACK_UPDATE_SNAPSHOT_ATTR = "__FlociNestedStackUpdateSnapshot";
/** The namespace, credentials, secret and attributes overwritten by a Serverless namespace update. */
public static final String REDSHIFT_SERVERLESS_NAMESPACE_UPDATE_SNAPSHOT_ATTR =
"__FlociRedshiftServerlessNamespaceUpdateSnapshot";
@@ -113,6 +113,10 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio
* "the template said nothing, leave stored tags alone" must keep that distinction themselves.
*/
public Map<String, String> resolveTags(JsonNode props, String name) {
return resolveTags(props, name, engine);
}
public static Map<String, String> resolveTags(JsonNode props, String name, CloudFormationTemplateEngine engine) {
Map<String, String> tags = new LinkedHashMap<>();
if (props == null || !props.has(name)) {
return tags;
@@ -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 io.restassured.response.Response;
@@ -468,7 +469,7 @@ class CloudFormationDeletionPolicyIntegrationTest {
}
@Test
void updateParentStackWithUnchangedNestedStackSucceedsEvenIfTemplateUrlUnavailable() throws InterruptedException {
void updateParentStackRollsBackWhenUnchangedChildTemplateUrlIsUnavailable() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String functionName = "cfn-nested-keep-func-" + suffix;
String bucketName = "nested-stack-templates-" + suffix;
@@ -507,13 +508,25 @@ class CloudFormationDeletionPolicyIntegrationTest {
try {
awaitStackStatus(parentStackId, "CREATE_COMPLETE", CUSTOM_AUTH);
String childStackId = getNestedStackId(parentStackId, "ChildStack", 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
// Every update re-reads the child template, including output-only parent updates.
updateStack(stackName, updatedParentTemplate, CUSTOM_AUTH);
awaitStackStatus(parentStackId, "UPDATE_COMPLETE", CUSTOM_AUTH);
awaitStackStatus(parentStackId, "UPDATE_ROLLBACK_COMPLETE", CUSTOM_AUTH);
assertThat(getNestedStackId(parentStackId, "ChildStack", CUSTOM_AUTH), equalTo(childStackId));
given().header("Authorization", CUSTOM_AUTH)
.when().get("/2015-03-31/functions/" + functionName)
.then().statusCode(200).body("Configuration.Timeout", equalTo(3));
String events = cfnQuery("DescribeStackEvents", parentStackId, CUSTOM_AUTH)
.then().statusCode(200).extract().asString();
assertThat(XmlParser.extractGroups(events, "member").stream().anyMatch(event ->
"ChildStack".equals(event.get("LogicalResourceId"))
&& "UPDATE_FAILED".equals(event.get("ResourceStatus"))
&& event.getOrDefault("ResourceStatusReason", "").contains("NoSuchKey")), equalTo(true));
} finally {
deleteStack(stackName);
}
@@ -0,0 +1,160 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.UUID;
import static io.github.hectorvent.floci.testing.CfnRequests.cfn;
import static io.github.hectorvent.floci.testing.CfnRequests.tags;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class CloudFormationNestedStackTagsIntegrationTest {
@Test
void nestedStacksInheritRootTagsOnCreateAndUpdateAndRestoreThemOnRollback() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String stackName = "cfn-nested-tags-" + suffix;
String bucket = "cfn-nested-tags-templates-" + suffix;
String grandchildTemplate = """
{"Description":"grandchild","Resources":{}}
""";
String childTemplate = childTemplate("child", bucket);
String parentTemplate = parentTemplate(bucket);
Throwable testFailure = null;
try {
given().when().put("/" + bucket).then().statusCode(200);
uploadTemplate(bucket, "grandchild.json", grandchildTemplate);
uploadTemplate(bucket, "child.json", childTemplate);
withTags(cfn("CreateStack", stackName).formParam("TemplateBody", parentTemplate), "blue", "owner-a")
.when().post("/").then().statusCode(200);
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
String childStack = nestedStackId(stackName, "ChildStack");
String grandchildStack = nestedStackId(childStack, "GrandchildStack");
assertEquals(Map.of("team", "blue", "owner", "owner-a"), tags(childStack));
assertEquals(Map.of("team", "blue", "owner", "owner-a"), tags(grandchildStack));
withTags(cfn("UpdateStack", stackName).formParam("TemplateBody", parentTemplate), "green", "owner-b")
.when().post("/").then().statusCode(200);
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
assertEquals(Map.of("team", "green", "owner", "owner-b"), tags(childStack));
assertEquals(Map.of("team", "green", "owner", "owner-b"), tags(grandchildStack));
uploadTemplate(bucket, "child.json", childTemplate("updated child", bucket));
cfn("UpdateStack", stackName).formParam("TemplateBody", parentTemplate)
.when().post("/").then().statusCode(200);
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
assertEquals(Map.of("team", "green", "owner", "owner-b"), tags(childStack));
String failingParentTemplate = """
{"Resources":{
"ChildStack":{"Type":"AWS::CloudFormation::Stack","Properties":{
"TemplateURL":"http://localhost/%1$s/child.json"}},
"ZFail":{"Type":"AWS::CloudFormation::Stack","Properties":{}}
}}
""".formatted(bucket);
String previousChildTemplate = deployedTemplate(childStack);
String previousGrandchildTemplate = deployedTemplate(grandchildStack);
withTags(cfn("UpdateStack", stackName).formParam("TemplateBody", failingParentTemplate),
"orange", "owner-c").when().post("/").then().statusCode(200);
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
assertEquals(Map.of("team", "green", "owner", "owner-b"), tags(stackName));
assertEquals(Map.of("team", "green", "owner", "owner-b"), tags(childStack));
assertEquals(Map.of("team", "green", "owner", "owner-b"), tags(grandchildStack));
// The failed update re-provisioned the child with the template and the parameter values
// it already ran, so only its tags moved: the rollback puts the prior tags back on the
// child and on the grandchild that inherited them, and every deployment stays exactly
// where it was. A nested stack the update re-deployed with a changed template or
// changed parameters is owed a deployment rollback this build defers; that one ends
// UPDATE_ROLLBACK_FAILED instead, covered in CloudFormationServiceRollbackTest.
assertEquals(previousChildTemplate, deployedTemplate(childStack));
assertEquals(previousGrandchildTemplate, deployedTemplate(grandchildStack));
cfn("UpdateStack", stackName).formParam("TemplateBody", parentTemplate).formParam("Tags", "")
.when().post("/").then().statusCode(200);
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
assertEquals(Map.of(), tags(stackName));
assertEquals(Map.of(), tags(childStack));
assertEquals(Map.of(), tags(grandchildStack));
String explicitChildTags = parentTemplate.replace("\"TemplateURL\":",
"\"Tags\":[{\"Key\":\"team\",\"Value\":\"child\"}],\"TemplateURL\":");
withTags(cfn("UpdateStack", stackName).formParam("TemplateBody", explicitChildTags), "root", "owner-d")
.when().post("/").then().statusCode(200);
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
assertEquals(Map.of("team", "child", "owner", "owner-d"), tags(childStack));
assertEquals(Map.of("team", "child", "owner", "owner-d"), tags(grandchildStack));
cfn("UpdateStack", stackName).formParam("TemplateBody", explicitChildTags).formParam("Tags", "")
.when().post("/").then().statusCode(200);
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
assertEquals(Map.of("team", "child"), tags(childStack));
assertEquals(Map.of("team", "child"), tags(grandchildStack));
} catch (RuntimeException | Error failure) {
testFailure = failure;
throw failure;
} finally {
try {
assertAll("nested stack cleanup",
() -> cfn("DeleteStack", stackName).when().post("/").then().statusCode(200),
() -> CfnStackWaits.awaitStackDeleted(stackName),
() -> given().when().delete("/" + bucket + "/child.json").then().statusCode(204),
() -> given().when().delete("/" + bucket + "/grandchild.json").then().statusCode(204),
() -> given().when().delete("/" + bucket).then().statusCode(204));
} catch (RuntimeException | Error cleanupFailure) {
if (testFailure == null) {
throw cleanupFailure;
}
testFailure.addSuppressed(cleanupFailure);
}
}
}
private static String childTemplate(String description, String bucket) {
return """
{"Description":"%1$s","Parameters":{"Revision":{"Type":"String","Default":"previous"}},
"Resources":{"GrandchildStack":{"Type":"AWS::CloudFormation::Stack",
"Properties":{"TemplateURL":"http://localhost/%2$s/grandchild.json"}}}}
""".formatted(description, bucket);
}
private static String parentTemplate(String bucket) {
return """
{"Resources":{"ChildStack":{"Type":"AWS::CloudFormation::Stack",
"Properties":{"TemplateURL":"http://localhost/%1$s/child.json"}}}}
""".formatted(bucket);
}
private static void uploadTemplate(String bucket, String key, String body) {
given().contentType("application/json").body(body)
.when().put("/" + bucket + "/" + key).then().statusCode(200);
}
private static RequestSpecification withTags(RequestSpecification request, String team, String owner) {
return request.formParam("Tags.member.1.Key", "team")
.formParam("Tags.member.1.Value", team)
.formParam("Tags.member.2.Key", "owner")
.formParam("Tags.member.2.Value", owner);
}
private static String nestedStackId(String stackName, String logicalId) {
String xml = cfn("DescribeStackResources", stackName).when().post("/")
.then().statusCode(200).extract().asString();
return XmlParser.extractPairs(xml, "member", "LogicalResourceId", "PhysicalResourceId").get(logicalId);
}
private static String deployedTemplate(String stackName) {
String xml = cfn("GetTemplate", stackName).when().post("/")
.then().statusCode(200).extract().asString();
return XmlParser.extractFirst(xml, "TemplateBody", null);
}
}
@@ -1,6 +1,5 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.ssm.SsmService;
import io.github.hectorvent.floci.testing.CfnStackWaits;
@@ -19,6 +18,7 @@ import java.util.List;
import java.util.Map;
import static io.github.hectorvent.floci.testing.CfnRequests.cfn;
import static io.github.hectorvent.floci.testing.CfnRequests.tags;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
@@ -400,6 +400,46 @@ class CloudFormationNoChangesIntegrationTest {
}
}
/**
* A template holding a nested stack is never a no-change, whether or not the child moved: AWS
* reads the child template again and reports the nested stack as a change on every update, so
* the same parent with the same child is updated, and so is the parent after the child changed
* in S3. Regression for the rejection reported on PR #7383: without the nested-stack exception
* the comparison only sees the unchanged parent and answers "No updates are to be performed."
* before the child is ever read.
*/
@Test
void aNestedStackWhoseChildTemplateChangedInS3IsAnUpdate() {
String bucket = name("nested-child");
s3Service.createBucket(bucket, "us-east-1");
putChildTemplate(bucket, "Description: first\n");
String parent = """
Resources:
Child:
Type: AWS::CloudFormation::Stack
Properties:
TemplateURL: http://localhost/%s/child.yaml
""".formatted(bucket);
String stackName = name("no-change-nested");
try {
create(stackName, parent);
update(stackName, parent).statusCode(200);
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
putChildTemplate(bucket, "Description: second\n");
update(stackName, parent).statusCode(200);
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
} finally {
s3Service.deleteObject(bucket, "child.yaml");
s3Service.deleteBucket(bucket);
}
}
private void putChildTemplate(String bucket, String content) {
s3Service.putObject(bucket, "child.yaml", content.getBytes(StandardCharsets.UTF_8), "text/yaml", Map.of());
}
private void putFragment(String bucket, String content) {
s3Service.putObject(bucket, "fragment.yaml", content.getBytes(StandardCharsets.UTF_8), "text/yaml", Map.of());
}
@@ -558,12 +598,6 @@ class CloudFormationNoChangesIntegrationTest {
return request;
}
private static Map<String, String> tags(String stackName) {
String xml = cfn("DescribeStacks", stackName).when().post("/")
.then().statusCode(200).extract().asString();
return XmlParser.extractPairs(xml, "member", "Key", "Value");
}
private static ValidatableResponse listChangeSets(String stackName) {
return given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "ListChangeSets")
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudformation.model.ChangeSet;
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
import io.github.hectorvent.floci.services.cloudformation.model.StackEvent;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
@@ -26,11 +27,13 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.SecretTar
import io.github.hectorvent.floci.services.cloudformation.provisioners.UpdateCleanupResult;
import io.github.hectorvent.floci.services.cloudformation.provisioners.WafV2CfnProvisioner;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.github.hectorvent.floci.services.ssm.SsmService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
@@ -76,6 +79,281 @@ import static org.mockito.Mockito.when;
*/
class CloudFormationServiceRollbackTest {
@Test
void unchangedParent_schedulesNestedWorkWhenOnlyGrandchildTemplateChanges() throws Exception {
assertGrandchildUpdate(true);
}
@Test
void unchangedParent_executesGrandchildS3Changes() throws Exception {
assertGrandchildUpdate(false);
}
private void assertGrandchildUpdate(boolean checkPreview) throws Exception {
when(provisioner.completeUpdate(any())).thenReturn(UpdateCleanupResult.notApplicable());
AtomicReference<String> childInS3 = new AtomicReference<>(treeChildTemplate());
AtomicReference<String> grandchildInS3 = new AtomicReference<>(previousGrandchildTemplate());
serveTreeTemplates(childInS3, grandchildInS3);
createNestedTree(treeParentTemplate());
grandchildInS3.set(previousGrandchildTemplate().replace("previous", "changed"));
ChangeSet changeSet = service.createChangeSet("rollback-tree", "update", "UPDATE", treeParentTemplate(), null,
Map.of(), List.of(), null, REGION, ACCOUNT);
if (checkPreview) {
assertTrue(service.computeChangeSetChanges(changeSet, REGION).stream()
.anyMatch(change -> "Child".equals(change.logicalResourceId()) && "Modify".equals(change.action())));
}
service.executeChangeSet("rollback-tree", "update", REGION, ACCOUNT).get(30, TimeUnit.SECONDS);
Stack parent = service.describeStacks("rollback-tree", REGION, ACCOUNT).getFirst();
Stack grandchild = service.describeStacks("rollback-tree-Child-Grandchild", REGION, ACCOUNT).getFirst();
assertEquals("UPDATE_COMPLETE", parent.getStatus());
assertEquals("changed", grandchild.getOutputs().get("Revision"));
}
/**
* A failing update that only moved the inherited tags re-provisioned the child with the very
* template and parameter values it already ran, so the deployment saved before that call still
* matches and the rollback restores the child's prior tags and the grandchild's inherited ones.
*/
@Test
void parentRollback_restoresInheritedTagsOfATagOnlyUpdate() throws Exception {
assertTagOnlyRollback(false);
}
@Test
void parentRollback_preservesExplicitGrandchildTagMatchingAttemptedInheritance() throws Exception {
assertTagOnlyRollback(true);
}
private void assertTagOnlyRollback(boolean explicitGrandchildTag) throws Exception {
when(provisioner.completeUpdate(any())).thenReturn(UpdateCleanupResult.notApplicable());
String childTemplate = explicitGrandchildTag ? treeChildTemplate().replace(
"\"TemplateURL\":\"http://localhost/templates/grandchild.json\"",
"\"TemplateURL\":\"http://localhost/templates/grandchild.json\","
+ "\"Tags\":[{\"Key\":\"team\",\"Value\":\"new\"}]") : treeChildTemplate();
AtomicReference<String> childInS3 = new AtomicReference<>(childTemplate);
AtomicReference<String> grandchildInS3 = new AtomicReference<>(previousGrandchildTemplate());
serveTreeTemplates(childInS3, grandchildInS3);
createNestedTree(treeParentTemplate());
Stack parent = service.describeStacks("rollback-tree", REGION, ACCOUNT).getFirst();
assertEquals("CREATE_COMPLETE", parent.getStatus());
service.createChangeSet("rollback-tree", "update", "UPDATE", failingParentTemplate(), null,
Map.of(), List.of(), Map.of("team", "new"), REGION, ACCOUNT);
service.executeChangeSet("rollback-tree", "update", REGION, ACCOUNT).get(30, TimeUnit.SECONDS);
assertEquals("UPDATE_ROLLBACK_COMPLETE", parent.getStatus());
assertTrue(service.describeStackEvents("rollback-tree", REGION).stream()
.anyMatch(event -> "ZFail".equals(event.getLogicalResourceId())
&& "Missing TemplateURL".equals(event.getResourceStatusReason())));
assertEquals(Map.of("team", "old"), parent.tagsSnapshot());
Stack child = service.describeStacks("rollback-tree-Child", REGION, ACCOUNT).getFirst();
assertEquals(Map.of("team", "old"), child.tagsSnapshot());
Stack grandchild = service.describeStacks("rollback-tree-Child-Grandchild", REGION, ACCOUNT).getFirst();
assertEquals(Map.of("team", explicitGrandchildTag ? "new" : "old"), grandchild.tagsSnapshot());
assertEquals(previousGrandchildTemplate(), grandchild.getTemplateBody());
assertEquals("previous", grandchild.getOutputs().get("Revision"));
}
/**
* The parent's TemplateURL and the root tags never moved; the child template in S3 did. What
* the child runs no longer matches what was saved before the update, so the rollback reports
* the nested stack as not rolled back rather than claiming the prior deployment is live with
* only its tags put back. Restoring a moved deployment is a rollback deferred to its own
* change.
*/
@Test
void parentRollback_failsHonestlyWhenTheChildTemplateChanged() throws Exception {
when(provisioner.completeUpdate(any())).thenReturn(UpdateCleanupResult.notApplicable());
AtomicReference<String> childInS3 = new AtomicReference<>(treeChildTemplate());
AtomicReference<String> grandchildInS3 = new AtomicReference<>(previousGrandchildTemplate());
serveTreeTemplates(childInS3, grandchildInS3);
createNestedTree(treeParentTemplate());
Stack parent = service.describeStacks("rollback-tree", REGION, ACCOUNT).getFirst();
assertEquals("CREATE_COMPLETE", parent.getStatus());
childInS3.set(treeChildTemplate().replace("\"Resources\":",
"\"Description\":\"changed child\",\"Resources\":"));
service.createChangeSet("rollback-tree", "update", "UPDATE", failingParentTemplate(), null,
Map.of(), List.of(), Map.of("team", "old"), REGION, ACCOUNT);
service.executeChangeSet("rollback-tree", "update", REGION, ACCOUNT).get(30, TimeUnit.SECONDS);
assertEquals("UPDATE_ROLLBACK_FAILED", parent.getStatus());
assertTrue(parent.getStatusReason().contains("failed to roll back: [Child]"), parent.getStatusReason());
Stack child = service.describeStacks("rollback-tree-Child", REGION, ACCOUNT).getFirst();
assertTrue(child.getTemplateBody().contains("changed child"), child.getTemplateBody());
}
@Test
void parentRollback_failsHonestlyWhenTheGrandchildTemplateChanged() throws Exception {
when(provisioner.completeUpdate(any())).thenReturn(UpdateCleanupResult.notApplicable());
AtomicReference<String> childInS3 = new AtomicReference<>(treeChildTemplate());
AtomicReference<String> grandchildInS3 = new AtomicReference<>(previousGrandchildTemplate());
serveTreeTemplates(childInS3, grandchildInS3);
createNestedTree(treeParentTemplate());
Stack parent = service.describeStacks("rollback-tree", REGION, ACCOUNT).getFirst();
grandchildInS3.set(previousGrandchildTemplate().replace("previous", "changed"));
service.createChangeSet("rollback-tree", "update", "UPDATE", failingParentTemplate(), null,
Map.of(), List.of(), Map.of("team", "new"), REGION, ACCOUNT);
service.executeChangeSet("rollback-tree", "update", REGION, ACCOUNT).get(30, TimeUnit.SECONDS);
assertEquals("UPDATE_ROLLBACK_FAILED", parent.getStatus());
Stack grandchild = service.describeStacks("rollback-tree-Child-Grandchild", REGION, ACCOUNT).getFirst();
assertEquals("changed", grandchild.getOutputs().get("Revision"));
}
/** Likewise for the parameter values handed to the child, with the child template unchanged. */
@Test
void parentRollback_failsHonestlyWhenTheChildParametersChanged() throws Exception {
when(provisioner.completeUpdate(any())).thenReturn(UpdateCleanupResult.notApplicable());
AtomicReference<String> childInS3 = new AtomicReference<>(treeChildTemplate());
AtomicReference<String> grandchildInS3 = new AtomicReference<>(previousGrandchildTemplate());
serveTreeTemplates(childInS3, grandchildInS3);
createNestedTree(treeParentTemplate());
Stack parent = service.describeStacks("rollback-tree", REGION, ACCOUNT).getFirst();
assertEquals("CREATE_COMPLETE", parent.getStatus());
String givenParameters = failingParentTemplate().replace(
"\"TemplateURL\":\"http://localhost/templates/child.json\"",
"\"TemplateURL\":\"http://localhost/templates/child.json\",\"Parameters\":{\"Revision\":\"changed\"}");
service.createChangeSet("rollback-tree", "update", "UPDATE", givenParameters, null,
Map.of(), List.of(), Map.of("team", "old"), REGION, ACCOUNT);
service.executeChangeSet("rollback-tree", "update", REGION, ACCOUNT).get(30, TimeUnit.SECONDS);
assertEquals("UPDATE_ROLLBACK_FAILED", parent.getStatus());
assertTrue(parent.getStatusReason().contains("failed to roll back: [Child]"), parent.getStatusReason());
Stack child = service.describeStacks("rollback-tree-Child", REGION, ACCOUNT).getFirst();
assertEquals("changed", child.parametersSnapshot().get("Revision"));
}
private void serveTreeTemplates(AtomicReference<String> childInS3, AtomicReference<String> grandchildInS3) {
when(templateStore.getObject("templates", "child.json")).thenAnswer(invocation ->
new S3Object("templates", "child.json", childInS3.get().getBytes(StandardCharsets.UTF_8),
"application/json"));
when(templateStore.getObject("templates", "grandchild.json")).thenAnswer(invocation ->
new S3Object("templates", "grandchild.json", grandchildInS3.get().getBytes(StandardCharsets.UTF_8),
"application/json"));
}
private void createNestedTree(String parentTemplate) throws Exception {
service.createChangeSet("rollback-tree", "create", "CREATE", parentTemplate, null,
Map.of(), List.of(), Map.of("team", "old"), REGION, ACCOUNT);
service.executeChangeSet("rollback-tree", "create", REGION, ACCOUNT).get(30, TimeUnit.SECONDS);
}
private static String treeChildTemplate() {
return """
{"Parameters":{"Revision":{"Type":"String","Default":"previous"}},
"Resources":{"Grandchild":{"Type":"AWS::CloudFormation::Stack",
"Properties":{"TemplateURL":"http://localhost/templates/grandchild.json"}}}}
""";
}
private static String previousGrandchildTemplate() {
return """
{"Resources":{},"Outputs":{"Revision":{"Value":"previous"}}}
""";
}
private static String treeParentTemplate() {
return """
{"Resources":{"Child":{"Type":"AWS::CloudFormation::Stack",
"Properties":{"TemplateURL":"http://localhost/templates/child.json"}}}}
""";
}
private static String failingParentTemplate() {
return treeParentTemplate().replace("\"Child\":", "\"ZFail\":{\"Type\":\"AWS::CloudFormation::Stack\","
+ "\"DependsOn\":\"Child\",\"Properties\":{}},\"Child\":");
}
@Test
void updateRollback_missingNestedChildDoesNotReportSuccess() {
Stack stack = new Stack();
stack.setStackName("missing-nested-rollback");
stack.setStackId("stack-id");
stack.setRegion(REGION);
stack.setTemplateBody("{\"Resources\":{}}");
StackResource nested = resource("Child", "missing-child", "AWS::CloudFormation::Stack", "UPDATE_COMPLETE");
nested.getAttributes().put(CfnRollback.NESTED_STACK_UPDATE_SNAPSHOT_ATTR,
"{\"templateBody\":\"{}\",\"parameters\":{},\"tags\":{}}");
stack.getResources().put("Child", nested);
StackResource failed = resource("Failed", null, "AWS::S3::Bucket", "CREATE_FAILED");
stack.getResources().put("Failed", failed);
StackUpdateSnapshot snapshot = new StackUpdateSnapshot("{}", "{}", Map.of(), Map.of(),
Map.of(), Map.of(), Map.of(),
Map.of("Child", resource("Child", "missing-child", "AWS::CloudFormation::Stack", "CREATE_COMPLETE")),
Map.of());
service.rollbackFailedExecution(stack, REGION, false, failed, snapshot, Set.of("Child", "Failed"));
assertEquals("UPDATE_ROLLBACK_FAILED", stack.getStatus());
assertEquals("UPDATE_FAILED", nested.getStatus());
assertTrue(nested.getStatusReason().contains("Rollback is not implemented"));
assertEquals(List.of("Child"), stack.getUpdateRollbackResourceIds());
assertTrue(nested.getAttributes().containsKey(CfnRollback.NESTED_STACK_UPDATE_SNAPSHOT_ATTR));
}
@Test
void resumeUpdateRollback_legacySnapshotPreservesCurrentTags() throws Exception {
assertRollbackSnapshotTags("", Map.of("Environment", "prod"));
}
@Test
void updateRollback_legacySnapshotPreservesCurrentTags() throws Exception {
assertRollbackSnapshotTags("", Map.of("Environment", "prod"), true);
}
@Test
void resumeUpdateRollback_nullSnapshotTagsPreservesCurrentTags() throws Exception {
assertRollbackSnapshotTags(",\"tags\":null", Map.of("Environment", "prod"));
}
@Test
void resumeUpdateRollback_explicitEmptySnapshotTagsRemovesCurrentTags() throws Exception {
assertRollbackSnapshotTags(",\"tags\":{}", Map.of());
}
@Test
void resumeUpdateRollback_snapshotRestoresPreviousTags() throws Exception {
assertRollbackSnapshotTags(",\"tags\":{\"Environment\":\"previous\"}",
Map.of("Environment", "previous"));
}
private void assertRollbackSnapshotTags(String tagsField, Map<String, String> expectedTags) throws Exception {
assertRollbackSnapshotTags(tagsField, expectedTags, false);
}
private void assertRollbackSnapshotTags(
String tagsField, Map<String, String> expectedTags, boolean initialRollback) throws Exception {
Stack stack = new Stack();
stack.setStackName("persisted-snapshot-tags");
stack.setStackId("stack-id");
stack.setRegion(REGION);
stack.setStatus("UPDATE_ROLLBACK_IN_PROGRESS");
stack.replaceTags(Map.of("Environment", "prod"));
StackUpdateSnapshot snapshot = new ObjectMapper().readValue("""
{"templateBody":"{}","originalTemplateBody":"previous-original",
"parameters":{},"resolvedParameters":{},"outputs":{},"exports":{},
"outputExportNames":{},"resources":{}%s}
""".formatted(tagsField), StackUpdateSnapshot.class);
stack.setUpdateRollbackSnapshot(snapshot);
stack.setUpdateRollbackResourceIds(List.of());
if (initialRollback) {
StackResource failed = resource("Failed", null, "AWS::S3::Bucket", "CREATE_FAILED");
stack.getResources().put("Failed", failed);
service.rollbackFailedExecution(stack, REGION, false, failed, snapshot, Set.of("Failed"));
} else {
service.resumeUpdateRollback(stack, List.of(), false, REGION);
}
assertEquals("UPDATE_ROLLBACK_COMPLETE", stack.getStatus());
assertEquals(expectedTags, stack.tagsSnapshot());
}
private static final String ACCOUNT = "000000000000";
private static final String REGION = "us-east-1";
private static final String FORCED_ROLLBACK_REASON = "One or more resources were skipped during UpdateRollback."
@@ -84,6 +362,7 @@ class CloudFormationServiceRollbackTest {
private CfnResourceDispatcher provisioner;
private CloudFormationService service;
private S3Service templateStore;
@BeforeEach
void setUp() {
@@ -107,15 +386,18 @@ class CloudFormationServiceRollbackTest {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.defaultAccountId()).thenReturn(ACCOUNT);
templateStore = mock(S3Service.class);
RegionResolver resolver = mock(RegionResolver.class);
when(resolver.getAccountId()).thenReturn(ACCOUNT);
service = new CloudFormationService(
provisioner,
mock(S3Service.class),
templateStore,
mock(SsmService.class),
mock(GetStackOutputRoleAuthorizer.class),
mock(CfnDynamicReferences.class),
new ObjectMapper(),
config,
mock(RegionResolver.class),
resolver,
Clock.systemUTC(),
new InMemoryStorageFactory());
}
@@ -186,7 +468,7 @@ class CloudFormationServiceRollbackTest {
stack.getResources().put(added.getLogicalId(), added);
StackUpdateSnapshot previousState = new StackUpdateSnapshot(
"previous-template", "previous-original", Map.of(), Map.of(), Map.of(), Map.of(), Map.of(),
Map.of());
Map.of(), Map.of());
service.rollbackFailedExecution(stack, REGION, false, added, previousState,
new LinkedHashSet<>(List.of("Dup")));
@@ -197,6 +479,27 @@ class CloudFormationServiceRollbackTest {
assertEquals("The following resource(s) failed to create: [Dup].", stack.writes().getFirst().reason());
}
@Test
void updateRollback_restoresStackTagsFromSnapshot() {
Stack stack = new Stack();
stack.setStackName("update-rollback-tags");
stack.setStackId("stack-id");
stack.setRegion(REGION);
stack.setStatus("UPDATE_IN_PROGRESS");
stack.replaceTags(Map.of("team", "new"));
StackUpdateSnapshot previousState = new StackUpdateSnapshot(
"previous-template", "previous-original", Map.of(), Map.of(), Map.of(), Map.of(), Map.of(),
Map.of(), Map.of("team", "old"));
StackResource failed = resource("Added", null, "AWS::Logs::LogGroup", "CREATE_FAILED");
failed.setStatusReason("already exists");
stack.getResources().put(failed.getLogicalId(), failed);
service.rollbackFailedExecution(stack, REGION, false, failed, previousState,
new LinkedHashSet<>(List.of("Added")));
assertEquals(Map.of("team", "old"), stack.tagsSnapshot());
}
/**
* The stack's rollback event names the resource that failed, as AWS does; the resource's own
* message stays on the resource's event. An update rollback carries no "Rollback requested by
@@ -214,7 +517,7 @@ class CloudFormationServiceRollbackTest {
stack.getResources().put(failed.getLogicalId(), failed);
StackUpdateSnapshot previousState = new StackUpdateSnapshot(
"previous-template", "previous-original", Map.of(), Map.of(), Map.of(), Map.of(), Map.of(),
Map.of());
Map.of(), Map.of());
service.rollbackFailedExecution(stack, REGION, false, failed, previousState,
new LinkedHashSet<>(List.of("MyDB")));
@@ -781,7 +1084,8 @@ class CloudFormationServiceRollbackTest {
StackUpdateSnapshot previousState = new StackUpdateSnapshot(
"previous-template", "previous-original", Map.of("P", "1"), Map.of("P", "1"),
Map.of("Out", "v"), Map.of(), Map.of(),
Map.of("LogGroup", resource("LogGroup", "/lg", "AWS::Logs::LogGroup", "CREATE_COMPLETE")));
Map.of("LogGroup", resource("LogGroup", "/lg", "AWS::Logs::LogGroup", "CREATE_COMPLETE")),
Map.of());
service.rollbackFailedExecution(stack, REGION, false, added, previousState,
new LinkedHashSet<>(List.of("LogGroup", "Dup")));
@@ -854,7 +1158,7 @@ class CloudFormationServiceRollbackTest {
StackUpdateSnapshot previousState = new StackUpdateSnapshot(
"previous-template", "previous-original", Map.of(), Map.of(), Map.of(), Map.of(), Map.of(),
Map.of("Nested", resource("Nested", "nested-stack-id", "AWS::CloudFormation::Stack",
"CREATE_COMPLETE")));
"CREATE_COMPLETE")), Map.of());
stack.setUpdateRollbackSnapshot(previousState);
stack.setUpdateRollbackResourceIds(List.of("Nested"));
@@ -886,7 +1190,8 @@ class CloudFormationServiceRollbackTest {
stack.getResources().put(added.getLogicalId(), added);
StackUpdateSnapshot previousState = new StackUpdateSnapshot(
"previous-template", "previous-original", Map.of(), Map.of(), Map.of(), Map.of(), Map.of(),
Map.of("Dashboard", resource("Dashboard", "ops", "AWS::CloudWatch::Dashboard", "CREATE_COMPLETE")));
Map.of("Dashboard", resource("Dashboard", "ops", "AWS::CloudWatch::Dashboard", "CREATE_COMPLETE")),
Map.of());
when(provisioner.rollbackUpdate(eq(dashboard), any()))
.thenThrow(new IllegalStateException("simulated restore failure"))
.thenReturn(true);
@@ -940,7 +1245,7 @@ class CloudFormationServiceRollbackTest {
stack.getResources().put(loadBalancer.getLogicalId(), loadBalancer);
stack.getResources().put(subnet.getLogicalId(), subnet);
stack.setUpdateRollbackSnapshot(new StackUpdateSnapshot("previous-template", "previous-original",
Map.of("Env", "dev"), Map.of("Env", "dev"), Map.of(), Map.of(), Map.of(), Map.of()));
Map.of("Env", "dev"), Map.of("Env", "dev"), Map.of(), Map.of(), Map.of(), Map.of(), Map.of()));
stack.setUpdateRollbackResourceIds(List.of("SubnetC", "ProdAlb"));
stack.setStatus("UPDATE_ROLLBACK_IN_PROGRESS");
@@ -1744,7 +2049,7 @@ class CloudFormationServiceRollbackTest {
stack.getResources().put(logGroup.getLogicalId(), logGroup);
StackUpdateSnapshot previousState = new StackUpdateSnapshot(
"previous-template", "previous-original", Map.of(), Map.of(), Map.of(), Map.of(), Map.of(),
Map.of("LogGroup", resource("LogGroup", "/lg", "AWS::Logs::LogGroup", "CREATE_COMPLETE")));
Map.of("LogGroup", resource("LogGroup", "/lg", "AWS::Logs::LogGroup", "CREATE_COMPLETE")), Map.of());
stack.setUpdateRollbackSnapshot(previousState);
stack.setUpdateRollbackResourceIds(List.of("LogGroup"));
stack.setStatus("UPDATE_ROLLBACK_IN_PROGRESS");
@@ -1786,7 +2091,7 @@ class CloudFormationServiceRollbackTest {
stack.getResources().put(skipped.getLogicalId(), skipped);
StackUpdateSnapshot previousState = new StackUpdateSnapshot(
"previous-template", "previous-original", Map.of(), Map.of(), Map.of(), Map.of(), Map.of(),
Map.of("Skipped", resource("Skipped", "/skipped", "AWS::Logs::LogGroup", "CREATE_COMPLETE")));
Map.of("Skipped", resource("Skipped", "/skipped", "AWS::Logs::LogGroup", "CREATE_COMPLETE")), Map.of());
stack.setUpdateRollbackSnapshot(previousState);
stack.setUpdateRollbackResourceIds(List.of("Skipped"));
stack.setStatus("UPDATE_ROLLBACK_IN_PROGRESS");
@@ -1832,7 +2137,7 @@ class CloudFormationServiceRollbackTest {
Map.of(), Map.of(
"Role", resource("Role", "role", "AWS::IAM::Role", "CREATE_COMPLETE"),
"Stable", resource("Stable", "/stable", "AWS::Logs::LogGroup", "CREATE_COMPLETE"),
"LogGroup", resource("LogGroup", "/lg", "AWS::Logs::LogGroup", "CREATE_COMPLETE"))));
"LogGroup", resource("LogGroup", "/lg", "AWS::Logs::LogGroup", "CREATE_COMPLETE")), Map.of()));
stack.setUpdateRollbackResourceIds(List.of("Role", "LogGroup"));
service.resumeUpdateRollback(stack, List.of(), true, REGION);
@@ -1,6 +1,5 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
@@ -10,6 +9,7 @@ import java.util.Map;
import java.util.UUID;
import static io.github.hectorvent.floci.testing.CfnRequests.cfn;
import static io.github.hectorvent.floci.testing.CfnRequests.tags;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
@@ -140,11 +140,7 @@ class CloudFormationUpdateStackTagsIntegrationTest {
.formParam("Tags.member.2.Value", secondValue);
}
private static Map<String, String> tags(String stackName) {
String xml = cfn("DescribeStacks", stackName).when().post("/")
.then().statusCode(200).extract().asString();
return XmlParser.extractPairs(xml, "member", "Key", "Value");
}
private static void executeChangeSet(String stackName, String changeSetName) {
cfn("ExecuteChangeSet", stackName).formParam("ChangeSetName", changeSetName)
@@ -1,7 +1,10 @@
package io.github.hectorvent.floci.testing;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.restassured.specification.RequestSpecification;
import java.util.Map;
import static io.restassured.RestAssured.given;
public final class CfnRequests {
@@ -13,4 +16,12 @@ public final class CfnRequests {
.formParam("Action", action);
return stackName == null ? request : request.formParam("StackName", stackName);
}
/** Returns the stack-level tags reported by DescribeStacks. */
public static Map<String, String> tags(String stackName) {
String xml = cfn("DescribeStacks", stackName).when().post("/")
.then().statusCode(200).extract().asString();
return XmlParser.extractPairs(xml, "member", "Key", "Value");
}
}