fix(cloudformation): roll back without a transient stack FAILED status (#5878)

When a resource failed, rollbackFailedExecution set the stack status to
CREATE_FAILED or UPDATE_FAILED and added a stack event with that status
before moving the stack to ROLLBACK_IN_PROGRESS or
UPDATE_ROLLBACK_IN_PROGRESS; the update exception path did the same. AWS
reports those statuses on the failed resource only, and on the stack only
when rollback is disabled. A DescribeStacks poll landing between the
writes read UPDATE_FAILED and stopped, which made the nested stack
rollback test in CloudFormationDeletionPolicyIntegrationTest flaky.

Drop the transient status and event, and publish each rollback status
after its reason and event so a poll that sees the status sees both.
CfnStackWaits no longer needs to wait out the transient status.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-10-17 13:47:42 -04:00
1 parent 23edd58992
commit 115a919a83
5 files changed
+113 -29

No files matched your search

@@ -2285,12 +2285,11 @@ public class CloudFormationService implements ResourceProvider {
return;
}
LOG.errorv("Stack {0} execution failed: {1}", stack.getStackName(), e.getMessage());
String failStatus = isCreate ? "CREATE_FAILED" : "UPDATE_FAILED";
stack.setStatus(failStatus);
stack.setStatusReason(e.getMessage());
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", failStatus, e.getMessage());
if (isCreate) {
stack.setStatusReason(e.getMessage());
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "CREATE_FAILED", e.getMessage());
stack.setStatus("CREATE_FAILED");
persistStack(stack);
} else {
rollbackFailedUpdate(
@@ -2375,30 +2374,26 @@ public class CloudFormationService implements ResourceProvider {
String reason,
StackUpdateSnapshot previousState,
Set<String> attemptedResourceIds) {
String failStatus = isCreate ? "CREATE_FAILED" : "UPDATE_FAILED";
stack.setStatus(failStatus);
stack.setStatusReason(reason);
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", failStatus, reason);
if (isCreate) {
stack.setStatus("ROLLBACK_IN_PROGRESS");
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "ROLLBACK_IN_PROGRESS", reason);
stack.setStatus("ROLLBACK_IN_PROGRESS");
List<String> rollbackFailures = rollbackCreatedResources(stack, region);
stack.setLastUpdatedTime(now());
if (rollbackFailures.isEmpty()) {
stack.setStatus("ROLLBACK_COMPLETE");
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "ROLLBACK_COMPLETE", null);
stack.setStatus("ROLLBACK_COMPLETE");
LOG.infov("Stack {0} rolled back to a clean slate (ROLLBACK_COMPLETE)", stack.getStackName());
} else {
String rollbackReason = "The following resource(s) failed to roll back: ["
+ String.join(", ", rollbackFailures) + "].";
stack.setStatus("ROLLBACK_FAILED");
stack.setStatusReason(rollbackReason);
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "ROLLBACK_FAILED", rollbackReason);
stack.setStatus("ROLLBACK_FAILED");
LOG.errorv("Stack {0} rollback failed: {1}", stack.getStackName(), rollbackReason);
}
} else {
@@ -2656,10 +2651,10 @@ public class CloudFormationService implements ResourceProvider {
StackUpdateSnapshot previousState,
Set<String> attemptedResourceIds,
String failureReason) {
stack.setStatus("UPDATE_ROLLBACK_IN_PROGRESS");
stack.setStatusReason(failureReason);
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "UPDATE_ROLLBACK_IN_PROGRESS", failureReason);
stack.setStatus("UPDATE_ROLLBACK_IN_PROGRESS");
List<String> rollbackFailures = rollbackUpdatedResources(
stack, previousState.resources(), attemptedResourceIds, region);
@@ -3629,9 +3624,9 @@ public class CloudFormationService implements ResourceProvider {
* {@code UPDATE_FAILED}) means the resource loop failed and rolled back before Outputs were
* ever computed: see {@link #executeTemplate}, which only reaches its Outputs block once the
* whole resource loop has succeeded. This is deliberately an allow-list rather than a
* deny-list of failure strings: a nested stack's own {@code rollbackFailedExecution} rewrites
* its status past {@code CREATE_FAILED}/{@code UPDATE_FAILED} into one of the ROLLBACK_*
* statuses before this method ever inspects it, so checking for the FAILED strings here can
* deny-list of failure strings: a nested stack's own {@code rollbackFailedExecution} settles
* it in one of the ROLLBACK_* statuses before this method ever inspects it, never in
* {@code CREATE_FAILED}/{@code UPDATE_FAILED}, so checking for the FAILED strings here can
* never match on a create and silently reports a stack that rolled back to nothing as
* CREATE_COMPLETE.
*/
@@ -74,15 +74,12 @@ final class CfnStackWaits {
}
/**
* Waits until DescribeStacks reports {@code expectedStatus} and returns that state. Unlike
* {@link #awaitTerminal}, a rollback is waited out: a stack rolling back shows CREATE_FAILED or
* UPDATE_FAILED for a moment before ROLLBACK_IN_PROGRESS, so while a rollback status is expected
* only a failed rollback is final. Any other terminal status fails at once with its reason, as
* do a DescribeStacks that is not 200 and ten seconds without the expected status.
* Waits until DescribeStacks reports {@code expectedStatus} and returns that state. Any other
* terminal status fails at once with its reason, as do a DescribeStacks that is not 200 and ten
* seconds without the expected status.
*/
static StackState awaitStatus(String stackName, String expectedStatus) {
long deadline = System.currentTimeMillis() + 10_000;
boolean rollbackExpected = expectedStatus.contains("ROLLBACK");
StackState last = new StackState(null, "");
while (System.currentTimeMillis() < deadline) {
Response response = given()
@@ -100,9 +97,7 @@ final class CfnStackWaits {
if (expectedStatus.equals(last.status())) {
return last;
}
boolean onTheWayToRollback = rollbackExpected
&& ("CREATE_FAILED".equals(last.status()) || "UPDATE_FAILED".equals(last.status()));
if (last.status() != null && TERMINAL.contains(last.status()) && !onTheWayToRollback) {
if (last.status() != null && TERMINAL.contains(last.status())) {
fail("Stack " + stackName + " reached " + last.status() + " instead of " + expectedStatus
+ ": " + last.reason());
}
@@ -730,8 +730,8 @@ class CloudFormationDeletionPolicyIntegrationTest {
* Reproduces the failure-propagation bug: a nested stack whose own resource loop fails rolls
* back internally to a clean slate ({@code ROLLBACK_COMPLETE}), but {@code executeNestedStack}
* used to detect that only by checking for the literal strings {@code CREATE_FAILED} /
* {@code UPDATE_FAILED}, status values that {@code rollbackFailedExecution} always overwrites
* with a {@code ROLLBACK_*} status before returning. So the check could never match, and the
* {@code UPDATE_FAILED}, status values a stack that {@code rollbackFailedExecution} rolled back
* never ends in: it settles in a {@code ROLLBACK_*} status. So the check could never match, and the
* nested stack's own resource in the parent was reported as {@code CREATE_COMPLETE} regardless.
*
* <p>With the child silently "succeeding", the parent went on to provision a downstream
@@ -7281,8 +7281,8 @@ class CloudFormationIntegrationTest {
* resource's {@code Outputs.*} attributes right after the child's (synchronous, same-thread)
* {@code executeTemplate} call returns. When the child's own resource loop fails, {@code
* executeTemplate} never reaches its Outputs block at all: {@code rollbackFailedExecution}
* rewrites the child's status straight from {@code CREATE_FAILED} into {@code
* ROLLBACK_COMPLETE} before returning. {@code executeNestedStack} used to detect a failed
* settles the child in {@code ROLLBACK_COMPLETE} before returning, and the child's status is
* never {@code CREATE_FAILED}. {@code executeNestedStack} used to detect a failed
* child only by checking for the literal strings {@code CREATE_FAILED}/{@code UPDATE_FAILED},
* which a rolled-back create can never match, so the parent kept going and reported
* {@code CREATE_COMPLETE} with its {@code Fn::GetAtt} on the child's outputs left unresolved:
@@ -27,6 +27,7 @@ import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
@@ -117,6 +118,58 @@ class CloudFormationServiceRollbackTest {
verify(provisioner).delete(created, REGION);
}
/**
* With rollback enabled AWS moves the stack from CREATE_IN_PROGRESS straight to
* ROLLBACK_IN_PROGRESS; CREATE_FAILED is the failed resource's status, not the stack's. A
* stack status of CREATE_FAILED, even for a moment, is read as final by a DescribeStacks poll.
* Each status is published after its reason and event, so a poll that sees it sees them too.
*/
@Test
void createRollback_neverReportsTheStackAsCreateFailed() {
StatusRecordingStack stack = new StatusRecordingStack();
stack.setStackName("rollback-stack-events");
stack.setStackId("stack-id");
stack.setRegion(REGION);
StackResource failed = resource("FailingResource", null, "AWS::Test::Failure", "CREATE_FAILED");
failed.setStatusReason("simulated create failure");
stack.getResources().put(failed.getLogicalId(), failed);
service.rollbackFailedExecution(stack, REGION, true, failed, null, Set.of());
assertEquals(List.of("ROLLBACK_IN_PROGRESS", "ROLLBACK_COMPLETE"), stack.statuses());
assertEquals(List.of("ROLLBACK_IN_PROGRESS", "ROLLBACK_COMPLETE"), stackEventStatuses(stack));
stack.assertEachStatusFollowsItsEvent();
assertEquals("simulated create failure", stack.writes().getFirst().reason());
}
/**
* The update counterpart: UPDATE_IN_PROGRESS goes straight to UPDATE_ROLLBACK_IN_PROGRESS, with
* no stack-level UPDATE_FAILED in between.
*/
@Test
void updateRollback_neverReportsTheStackAsUpdateFailed() {
StatusRecordingStack stack = new StatusRecordingStack();
stack.setStackName("update-rollback-stack-events");
stack.setStackId("stack-id");
stack.setRegion(REGION);
stack.setStatus("UPDATE_IN_PROGRESS");
stack.writes().clear();
StackResource added = resource("Dup", null, "AWS::Logs::LogGroup", "CREATE_FAILED");
added.setStatusReason("already exists");
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());
service.rollbackFailedExecution(stack, REGION, false, added, previousState,
new LinkedHashSet<>(List.of("Dup")));
assertEquals(List.of("UPDATE_ROLLBACK_IN_PROGRESS", "UPDATE_ROLLBACK_COMPLETE"), stack.statuses());
assertEquals(List.of("UPDATE_ROLLBACK_IN_PROGRESS", "UPDATE_ROLLBACK_COMPLETE"), stackEventStatuses(stack));
stack.assertEachStatusFollowsItsEvent();
assertEquals("already exists", stack.writes().getFirst().reason());
}
@Test
void createRollback_withDependencyNotFoundMessage_reachesRollbackFailed() {
Stack stack = new Stack();
@@ -781,6 +834,47 @@ class CloudFormationServiceRollbackTest {
return stack;
}
private static List<String> stackEventStatuses(Stack stack) {
return stack.getEvents().stream()
.filter(event -> "AWS::CloudFormation::Stack".equals(event.getResourceType()))
.map(StackEvent::getResourceStatus)
.toList();
}
/** One status write, with the reason and the latest stack-level event it was published with. */
private record StatusWrite(String status, String reason, String latestStackEvent) {
}
/**
* Records every status write, so a test sees a status DescribeStacks could have served for a
* moment, not only the one the stack settled in.
*/
private static final class StatusRecordingStack extends Stack {
private final List<StatusWrite> writes = new ArrayList<>();
@Override
public void setStatus(String status) {
List<String> stackEvents = stackEventStatuses(this);
writes.add(new StatusWrite(status, getStatusReason(),
stackEvents.isEmpty() ? null : stackEvents.getLast()));
super.setStatus(status);
}
List<StatusWrite> writes() {
return writes;
}
List<String> statuses() {
return writes.stream().map(StatusWrite::status).toList();
}
void assertEachStatusFollowsItsEvent() {
for (StatusWrite write : writes) {
assertEquals(write.status(), write.latestStackEvent(), "event published after " + write.status());
}
}
}
private static StackResource resource(String logicalId, String physicalId, String resourceType, String status) {
StackResource resource = new StackResource();
resource.setLogicalId(logicalId);