fix(cloudformation): keep a rolled-back stack's diagnostics until the next redeploy

CreateStack had no name-conflict check at all: createChangeSet's
computeIfAbsent silently reused any existing stack regardless of
status, so a second CreateStack for a live name re-ran the template
against the same stack instead of failing. That left callers no
AWS-faithful way to redeploy over a ROLLBACK_COMPLETE stack except an
explicit DeleteStack first - which destroys the failed attempt's
DescribeStackEvents before an operator gets to read them.

Now a CREATE-type change set against an existing stack throws
AlreadyExistsException unless that stack is ROLLBACK_COMPLETE, in
which case it's replaced with a fresh stack (new StackId, empty
resources/events) at execute time - the moment a redeploy is actually
requested, not eagerly when the rollback itself completes. The failed
attempt stays fully describable for as long as nobody's asked to
retry.

Closes #2207.
This commit is contained in:
Priamo committed 2026-08-18 00:17:43 -04:00
1 parent 7d8acede18
commit d8e66b3ced
2 files changed
+145 -2

No files matched your search

@@ -174,6 +174,18 @@ public class CloudFormationService {
// created, so CreateStack/UpdateStack fail synchronously the way real CloudFormation does.
validateConditionDependencies(resolvedTemplate, parameters, region, accountId);
// A CREATE change set against a name that already has a stack is only valid when that
// stack is ROLLBACK_COMPLETE - AWS lets a redeploy proceed directly over that state
// (deleting the failed attempt at execute time, not here - see the ROLLBACK_COMPLETE
// handling in executeChangeSet) rather than throwing. Every other existing status is a
// real conflict.
boolean isCreateType = changeSetType == null || "CREATE".equalsIgnoreCase(changeSetType);
Stack existing = stacks.get(key(stackName, region));
if (isCreateType && existing != null && !"ROLLBACK_COMPLETE".equals(existing.getStatus())) {
throw new AwsException("AlreadyExistsException",
"Stack [" + stackName + "] already exists", 400);
}
// Detect first creation atomically: the mapping function runs at most once per key, so the
// flag is only set for the thread that actually creates the stack (no double-recording under
// concurrent CreateChangeSet calls).
@@ -189,7 +201,6 @@ public class CloudFormationService {
// stack-level event (as AWS and LocalStack do) so DescribeStackEvents is non-empty straight
// after change-set creation — tooling such as the AWS SAM CLI reads StackEvents[0] there and
// otherwise fails with an IndexError. (CreateChangeSet defaults a null type to CREATE.)
boolean isCreateType = changeSetType == null || "CREATE".equalsIgnoreCase(changeSetType);
if (stackCreated[0] && isCreateType) {
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "REVIEW_IN_PROGRESS", "User Initiated");
@@ -249,6 +260,21 @@ public class CloudFormationService {
boolean isCreate = "CREATE".equalsIgnoreCase(cs.getChangeSetType()) ||
"CREATE_IN_PROGRESS".equals(stack.getStatus());
if (isCreate && "ROLLBACK_COMPLETE".equals(stack.getStatus())) {
// A redeploy over a ROLLBACK_COMPLETE stack: rollback already tore down every
// resource it created, so there's nothing left to physically clean up - just replace
// the stale shell with a fresh stack (new StackId, empty resources/events) now, at the
// moment the operator actually retries, rather than eagerly when the rollback itself
// completed. That's what keeps the failed attempt's DescribeStackEvents readable for
// as long as the operator hasn't asked to redeploy - see #2207.
Stack fresh = newStack(stackName, region);
fresh.setTags(stack.getTags());
cs.setStackId(fresh.getStackId());
fresh.getChangeSets().put(changeSetName, cs);
stacks.put(key(stackName, region), fresh);
stack = fresh;
}
stack.setStatus(isCreate ? "CREATE_IN_PROGRESS" : "UPDATE_IN_PROGRESS");
stack.setLastUpdatedTime(now());
addEvent(stack, stack.getStackName(), stack.getStackId(),
@@ -258,8 +284,9 @@ public class CloudFormationService {
String templateBody = cs.getTemplateBody();
Map<String, String> params = cs.getParameters() != null ? cs.getParameters() : Map.of();
Stack executingStack = stack;
return executor.submit(() -> runUnderAccount(accountId,
() -> executeTemplate(stack, templateBody, params, isCreate, region, accountId)));
() -> executeTemplate(executingStack, templateBody, params, isCreate, region, accountId)));
}
/**
@@ -9505,6 +9505,122 @@ class CloudFormationIntegrationTest {
.body(containsString("CREATE_FAILED"));
}
@Test
void createStack_onExistingActiveStack_throwsAlreadyExistsException() {
String template = """
{
"Resources": {
"MyBus": { "Type": "AWS::Events::EventBus", "Properties": { "Name": "cfn-2207-active-bus" } }
}
}
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", "cfn-2207-active-stack")
.formParam("TemplateBody", template)
.when().post("/").then().statusCode(200);
// A second CreateStack for the same name, while the first is still ACTIVE, is a real
// conflict - it must not silently re-run the template against the live stack.
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", "cfn-2207-active-stack")
.formParam("TemplateBody", template)
.when().post("/")
.then()
.body(containsString("AlreadyExistsException"))
.body(containsString("already exists"));
}
@Test
void createStack_redeployOverRollbackComplete_succeedsWithFreshStack() {
// #2207: floci used to give callers no way to redeploy over ROLLBACK_COMPLETE except an
// explicit DeleteStack first - which destroyed the failed attempt's DescribeStackEvents
// before an operator had a chance to read them. AWS instead lets CreateStack proceed
// directly over ROLLBACK_COMPLETE, deleting the failed attempt at that point.
String failingTemplate = """
{
"Resources": {
"BadSecret": {
"Type": "AWS::SecretsManager::Secret",
"Properties": {
"Name": "cfn-2207-redeploy-secret",
"SecretString": "explicit",
"GenerateSecretString": { "PasswordLength": 32 }
}
}
}
}
""";
String stackName = "cfn-2207-redeploy-stack";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", failingTemplate)
.when().post("/").then().statusCode(200);
String failedDescribe = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when().post("/").then().extract().asString();
assertThat(failedDescribe, containsString("<StackStatus>ROLLBACK_COMPLETE</StackStatus>"));
String firstStackId = failedDescribe.substring(
failedDescribe.indexOf("<StackId>") + 9, failedDescribe.indexOf("</StackId>"));
// The failed attempt's diagnostic is still readable right up until the redeploy.
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackEvents")
.formParam("StackName", stackName)
.when().post("/")
.then().statusCode(200).body(containsString("CREATE_FAILED"));
String workingTemplate = """
{
"Resources": {
"MyBus": { "Type": "AWS::Events::EventBus", "Properties": { "Name": "cfn-2207-redeploy-bus" } }
}
}
""";
String createXml = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", workingTemplate)
.when().post("/")
.then().statusCode(200).extract().asString();
// The redeploy is a fresh stack, not a resumed one - new StackId, no leftover BadSecret.
assertThat(createXml, not(containsString(firstStackId)));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when().post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
.body(not(containsString(firstStackId)));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackResources")
.formParam("StackName", stackName)
.when().post("/")
.then()
.statusCode(200)
.body(containsString("MyBus"))
.body(not(containsString("BadSecret")));
}
@Test
void createStack_apiGatewayRestApi_withEndpointConfiguration() {
String template = """