fix(cloudformation): honor retained resources on stack deletion (#6723)

* fix(cloudformation): honor retained resources on stack deletion

* test(cloudformation): assert the unretained sibling bucket is removed

* fix(cloudformation): skip every retained resource, whatever its status

A DELETE_FAILED stack can hold a CREATE_FAILED resource that the delete
never touches, because floci only deletes a failed resource it owns for
rollback. Naming it in RetainResources was accepted but left it
CREATE_FAILED with no DELETE_SKIPPED event. AWS reports every retained
resource DELETE_SKIPPED, so the retain check now runs before the
deletability guard.

* test(cloudformation): build the retain integration test on the shared CFN helpers

Use CfnStackWaits.awaitStatus, which also fails at once on another
terminal status, instead of a private poll, and CfnRequests.cfn for the
Query requests.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-31 12:15:25 -04:00
1 parent 4c52e12834
commit 7cf516a14d
8 files changed
+508 -10

No files matched your search

@@ -0,0 +1,114 @@
package com.floci.test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;
import software.amazon.awssdk.services.cloudformation.model.StackEvent;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@DisplayName("CloudFormation DeleteStack RetainResources")
class CloudFormationDeleteStackRetainResourcesTest {
private static CloudFormationClient cfn;
private static S3Client s3;
private String stackName;
private String dataBucket;
@BeforeAll
static void clients() {
cfn = TestFixtures.cloudFormationClient();
s3 = TestFixtures.s3Client();
}
@BeforeEach
void setup() {
stackName = TestFixtures.uniqueName("compat-cfn-retain");
dataBucket = stackName + "-data";
}
@AfterEach
void cleanup() {
try {
TestFixtures.deleteBucketContents(s3, dataBucket);
} catch (NoSuchBucketException ignored) {
// The stack never created the bucket, because an assertion failed first.
}
try {
cfn.deleteStack(r -> r.stackName(stackName));
} catch (CloudFormationException ignored) {
// The test deletes the stack itself; this only covers an assertion failing first.
}
try {
s3.deleteBucket(r -> r.bucket(dataBucket));
} catch (NoSuchBucketException ignored) {
// Deleted by the stack, which the test retains it from only on the path it asserts.
}
}
@AfterAll
static void closeClients() {
cfn.close();
s3.close();
}
@Test
@DisplayName("keeps the retained resource of a DELETE_FAILED stack and deletes the rest")
void retainsResourceOfDeleteFailedStack() throws InterruptedException {
String stackId = cfn.createStack(r -> r.stackName(stackName).templateBody("""
{
"Resources": {
"DataBucket": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": "%s"}},
"OtherBucket": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": "%s-other"}}
}
}
""".formatted(dataBucket, stackName))).stackId();
awaitStatus(stackId, "CREATE_COMPLETE");
assertThatThrownBy(() -> cfn.deleteStack(r -> r.stackName(stackName).retainResources("DataBucket")))
.isInstanceOf(CloudFormationException.class)
.hasMessageContaining("specify which resources to retain only when the stack is in the"
+ " DELETE_FAILED state");
s3.putObject(r -> r.bucket(dataBucket).key("kept.txt"), RequestBody.fromString("kept"));
cfn.deleteStack(r -> r.stackName(stackName));
awaitStatus(stackId, "DELETE_FAILED");
assertThatThrownBy(() -> cfn.deleteStack(r -> r.stackName(stackName).retainResources("OtherBucket")))
.as("OtherBucket was deleted by the failed delete")
.isInstanceOf(CloudFormationException.class)
.hasMessageContaining("Do not specify resources that are in the DELETE_COMPLETE state");
cfn.deleteStack(r -> r.stackName(stackName).retainResources("DataBucket"));
awaitStatus(stackId, "DELETE_COMPLETE");
assertThat(s3.getObjectAsBytes(r -> r.bucket(dataBucket).key("kept.txt")).asUtf8String())
.isEqualTo("kept");
assertThatThrownBy(() -> s3.headBucket(r -> r.bucket(stackName + "-other")))
.isInstanceOf(NoSuchBucketException.class);
assertThat(cfn.describeStackEventsPaginator(r -> r.stackName(stackId)).stackEvents().stream()
.filter(event -> "DataBucket".equals(event.logicalResourceId()))
.findFirst())
.as("DescribeStackEvents lists newest first")
.get()
.extracting(StackEvent::resourceStatusAsString)
.isEqualTo("DELETE_SKIPPED");
}
private void awaitStatus(String stackId, String expected) throws InterruptedException {
TestFixtures.await(() -> {
String status = cfn.describeStacks(r -> r.stackName(stackId)).stacks().get(0).stackStatusAsString();
if (!status.endsWith("_IN_PROGRESS") && !status.equals(expected)) {
throw new AssertionError(stackName + " settled at " + status + ", expected " + expected);
}
return status.equals(expected);
}, stackName, expected, 120_000_000_000L, TestFixtures.isRealAws() ? 5000 : 100);
}
}
+7 -1
View File
@@ -11,7 +11,7 @@
| `DescribeStacks` | Get stack status, parameters, and outputs |
| `CreateStack` | Deploy a CloudFormation template |
| `UpdateStack` | Update an existing stack |
| `DeleteStack` | Delete a stack and its resources |
| `DeleteStack` | Delete a stack and its resources, keeping those named in `RetainResources` once a delete has failed (see [Deletion Policies](#deletion-policies)) |
| `ContinueUpdateRollback` | Retry the rollback of a stack in `UPDATE_ROLLBACK_FAILED`, optionally skipping resources or forcing past every failed one (see [Failed update rollbacks](#failed-update-rollbacks)) |
| `UpdateTerminationProtection` | - |
| `CreateChangeSet` | Create a change set |
@@ -1028,6 +1028,12 @@ Resources in any other status (`DELETE_COMPLETE`, `DELETE_SKIPPED`, an in-progre
resources without a physical id are skipped. A resource that cannot be deleted leaves the stack in
`DELETE_FAILED`, named in the status reason.
A `DELETE_FAILED` stack can be deleted again with `RetainResources` naming the resources to keep:
they stay in place and are reported as `DELETE_SKIPPED`, and the rest are deleted. As on AWS, the
parameter is refused when the stack is in any other status, when it names a resource the stack does
not have or has already deleted, or when it names one twice. A retry while that delete is still
running must repeat the same list in the same order.
Deviations from AWS to be aware of:
- `Snapshot` deletes the resource without taking a snapshot; floci has no snapshot support for the
@@ -183,8 +183,9 @@ public class CloudFormationQueryHandler {
private Response deleteStack(MultivaluedMap<String, String> params, String region) {
String stackName = params.getFirst("StackName");
List<String> retainResources = extractList(params, "RetainResources.member.");
try {
cfnService.deleteStack(stackName, region);
cfnService.deleteStack(stackName, retainResources, region);
String xml = new XmlBuilder()
.start("DeleteStackResponse", CF_NS)
.raw(AwsQueryResponse.responseMetadata())
@@ -102,6 +102,15 @@ public class CloudFormationService implements ResourceProvider {
+ " to review their current state before your next update.";
private static final String FORCE_WITH_SKIPS = "ForceRollback and ResourcesToSkip are mutually exclusive";
private static final String CONTINUE_STACK_MISSING = "Stack: %s does not exist";
private static final String RETAIN_NOT_UNIQUE = "The logical IDs specified for the resources to retain are not"
+ " all unique. Specify unique logical IDs for all of the resources that you want to retain.";
private static final String RETAIN_STACK_NOT_DELETE_FAILED = "Invalid operation on stack [%s]. When you delete"
+ " a stack, specify which resources to retain only when the stack is in the DELETE_FAILED state.";
private static final String RETAIN_INVALID_STATE = "The specified resources to retain must be in a valid state."
+ " Do not specify resources that are in the DELETE_COMPLETE state.";
private static final String RETAIN_DIFFERS_FROM_DELETE = "A delete stack operation is already in progress for"
+ " stack [%s]. Do not submit another delete stack request specifying different resources to retain"
+ " or resources to retain in a different order.";
/** The StackName pattern ContinueUpdateRollback and DescribeStacks validate a name against. */
private static final Pattern STACK_NAME =
Pattern.compile("[a-zA-Z][-a-zA-Z0-9]*|arn:[-a-zA-Z0-9:/._+]*");
@@ -1289,20 +1298,27 @@ public class CloudFormationService implements ResourceProvider {
// ── DeleteStack ───────────────────────────────────────────────────────────
public void deleteStack(String stackName, String region) {
deleteStack(stackName, region, regionResolver.getAccountId());
public void deleteStack(String stackName, List<String> retainResources, String region) {
deleteStack(stackName, retainResources, region, regionResolver.getAccountId());
}
public Future<?> deleteStack(String stackName, String region, String accountId) {
return deleteStack(stackName, List.of(), region, accountId);
}
/**
* Deletes a stack, removing its resources from {@code accountId}'s namespace. The account must
* match the one the resources were provisioned into (the caller's account for a single-stack
* deployment, or the target account for a StackSet instance).
* deployment, or the target account for a StackSet instance). {@code retainResources} names
* resources of a {@code DELETE_FAILED} stack that the delete leaves in place, as AWS allows
* only from that status.
*
* @return a future that completes when the resources have been removed; already-gone stacks
* complete immediately. Callers that need synchronous deletion (e.g. StackSet instance
* removal) can await it.
*/
public Future<?> deleteStack(String stackName, String region, String accountId) {
public Future<?> deleteStack(String stackName, List<String> retainResources, String region, String accountId) {
validateRetainResources(retainResources);
purgeExpiredDeletedStacks();
Stack stack = resolveStack(stackName, region, accountId);
if (stack == null) {
@@ -1325,10 +1341,18 @@ public class CloudFormationService implements ResourceProvider {
// deletion already running, and starts no second one; a stack that took this name since it
// was resolved is a different stack, and is left alone.
String stackId = stack.getStackId();
List<String> retain = List.copyOf(retainResources);
Future<?>[] submitted = new Future<?>[1];
stacks.compute(stackKey(accountId, stack.getStackName(), region), (k, existing) -> {
if (existing == null || !existing.getStackId().equals(stackId)
|| isBeingDeleted(existing.getStatus())) {
if (existing == null || !existing.getStackId().equals(stackId)) {
return existing;
}
if (isBeingDeleted(existing.getStatus())) {
// A retry of the running delete is a no-op; one that would retain otherwise is refused.
if ("DELETE_IN_PROGRESS".equals(existing.getStatus()) && !retain.equals(existing.getRetainResources())) {
throw new AwsException("ValidationError",
RETAIN_DIFFERS_FROM_DELETE.formatted(existing.getStackId()), 400);
}
return existing;
}
if (existing.isEnableTerminationProtection()) {
@@ -1337,13 +1361,26 @@ public class CloudFormationService implements ResourceProvider {
"Stack [" + existing.getStackId()
+ "] cannot be deleted while TerminationProtection is enabled", 400);
}
if (!retain.isEmpty()) {
if (!"DELETE_FAILED".equals(existing.getStatus())) {
throw new AwsException("ValidationError",
RETAIN_STACK_NOT_DELETE_FAILED.formatted(existing.getStackId()), 400);
}
for (String logicalId : retain) {
StackResource resource = existing.getResources().get(logicalId);
if (resource == null || "DELETE_COMPLETE".equals(resource.getStatus())) {
throw new AwsException("ValidationError", RETAIN_INVALID_STATE, 400);
}
}
}
StackMutationSnapshot snapshot = snapshot(existing);
existing.setRetainResources(retain);
existing.setStatus("DELETE_IN_PROGRESS");
addEvent(existing, existing.getStackName(), existing.getStackId(),
"AWS::CloudFormation::Stack", "DELETE_IN_PROGRESS", null);
try {
submitted[0] = submitOperation(() -> RequestScopes.runAs(accountId, region,
() -> deleteStackResources(existing, region, accountId)));
() -> deleteStackResources(existing, retain, region, accountId)));
} catch (AwsException e) {
restore(existing, snapshot);
throw e;
@@ -1353,6 +1390,21 @@ public class CloudFormationService implements ResourceProvider {
return submitted[0] != null ? submitted[0] : CompletableFuture.completedFuture(null);
}
/**
* Refuses a malformed {@code RetainResources} as AWS does, before the stack is looked up: a
* logical id outside 1 to 255 characters, then one named twice.
*/
private static void validateRetainResources(List<String> retainResources) {
if (retainResources.stream().anyMatch(id -> id.isEmpty() || id.codePointCount(0, id.length()) > 255)) {
throw SmithyValidationErrors.validationError("Value '" + retainResources + "' at 'resourcesToRetain'"
+ " failed to satisfy constraint: Member must satisfy constraint: [Member must have length"
+ " less than or equal to 255, Member must have length greater than or equal to 1]");
}
if (new HashSet<>(retainResources).size() != retainResources.size()) {
throw new AwsException("ValidationError", RETAIN_NOT_UNIQUE, 400);
}
}
// ── ContinueUpdateRollback ────────────────────────────────────────────────
/**
@@ -2612,6 +2664,7 @@ public class CloudFormationService implements ResourceProvider {
"Stack [" + child.getStackId()
+ "] cannot be deleted while TerminationProtection is enabled", 400);
}
child.setRetainResources(List.of());
child.setStatus("DELETE_IN_PROGRESS");
addEvent(child, child.getStackName(), child.getStackId(),
"AWS::CloudFormation::Stack", "DELETE_IN_PROGRESS", null);
@@ -3553,6 +3606,11 @@ public class CloudFormationService implements ResourceProvider {
}
void deleteStackResources(Stack stack, String region, String accountId) {
deleteStackResources(stack, List.of(), region, accountId);
}
/** Deletes the stack's resources, except those {@code retainResources} names or a policy retains. */
void deleteStackResources(Stack stack, List<String> retainResources, String region, String accountId) {
try {
List<StackResource> resources = resourcesInCreationOrder(stack, region);
Collections.reverse(resources); // Dependents go before what they depend on
@@ -3566,6 +3624,13 @@ public class CloudFormationService implements ResourceProvider {
failedResources.add(displacedFailure.logicalId());
}
for (StackResource resource : resources) {
if (retainResources.contains(resource.getLogicalId())) {
resource.setStatus("DELETE_SKIPPED");
resource.setStatusReason(null);
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "DELETE_SKIPPED", null);
continue;
}
if (resource.getPhysicalId() == null || !isDeletableOnStackDelete(resource)) {
continue;
}
@@ -80,6 +80,11 @@ public class Stack {
*/
private StackUpdateSnapshot updateRollbackSnapshot;
private List<String> updateRollbackResourceIds;
/**
* The {@code RetainResources} of the last DeleteStack that started a delete. A DeleteStack
* repeated while that delete runs must name the same list, in the same order.
*/
private List<String> retainResources = List.of();
public String getStackId() { return stackId; }
public void setStackId(String stackId) { this.stackId = stackId; }
@@ -226,4 +231,6 @@ public class Stack {
public void setUpdateRollbackSnapshot(StackUpdateSnapshot updateRollbackSnapshot) { this.updateRollbackSnapshot = updateRollbackSnapshot; }
public List<String> getUpdateRollbackResourceIds() { return updateRollbackResourceIds; }
public void setUpdateRollbackResourceIds(List<String> updateRollbackResourceIds) { this.updateRollbackResourceIds = updateRollbackResourceIds; }
public List<String> getRetainResources() { return retainResources; }
public void setRetainResources(List<String> retainResources) { this.retainResources = retainResources; }
}
@@ -0,0 +1,194 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static io.github.hectorvent.floci.testing.CfnRequests.cfn;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Verifies {@code DeleteStack}'s {@code RetainResources}: a stack whose delete failed can be deleted
* again while keeping the resources it names, and a request naming them anywhere else is refused
* with the texts AWS answers.
*/
@QuarkusTest
class CloudFormationDeleteStackRetainResourcesIntegrationTest {
private static final String INVALID_STATE = "The specified resources to retain must be in a valid state."
+ " Do not specify resources that are in the DELETE_COMPLETE state.";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void retainedBucketKeepsItsDataWhileTheRestOfTheStackIsDeleted() {
String suffix = Long.toString(System.nanoTime(), 36);
String data = "cfn-retain-data-" + suffix;
String spare = "cfn-retain-spare-" + suffix;
String stackName = "cfn-retain-" + suffix;
String stackId = deleteFailedStack(stackName, data, spare, "cfn-retain-other-" + suffix);
given().when().delete("/" + spare + "/object.txt").then().statusCode(204);
deleteStack(stackName, "DataBucket").then().statusCode(200);
CfnStackWaits.awaitStatus(stackId, "DELETE_COMPLETE");
given().when().get("/" + data + "/object.txt").then().statusCode(200).body(containsString("kept"));
bucketRequest(spare).then().statusCode(404);
String events = cfn("DescribeStackEvents", stackId)
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString();
Map<String, String> newest = XmlParser.extractGroups(events, "member").stream()
.filter(member -> "DataBucket".equals(member.get("LogicalResourceId")))
.findFirst().orElseThrow();
assertEquals("DELETE_SKIPPED", newest.get("ResourceStatus"));
assertNull(newest.get("ResourceStatusReason"));
given().when().delete("/" + data + "/object.txt");
given().header("Host", data + ".localhost").when().delete("/");
}
@Test
void retainingAResourceTheStackNoLongerHasIsRefused() {
String suffix = Long.toString(System.nanoTime(), 36);
String data = "cfn-retain-gone-data-" + suffix;
String spare = "cfn-retain-gone-spare-" + suffix;
String stackName = "cfn-retain-gone-" + suffix;
String stackId = deleteFailedStack(stackName, data, spare, "cfn-retain-gone-other-" + suffix);
// OtherBucket was deleted by the failed delete, Nope was never a resource of the stack.
for (String retained : new String[] {"OtherBucket", "Nope"}) {
assertValidationError(deleteStack(stackName, retained), INVALID_STATE);
}
assertThat(describeStacks(stackId), containsString("<StackStatus>DELETE_FAILED</StackStatus>"));
given().when().delete("/" + data + "/object.txt");
given().when().delete("/" + spare + "/object.txt");
deleteStack(stackName).then().statusCode(200);
CfnStackWaits.awaitStatus(stackId, "DELETE_COMPLETE");
}
@Test
void retainingIsRefusedUnlessTheStackIsDeleteFailed() {
String suffix = Long.toString(System.nanoTime(), 36);
String bucket = "cfn-retain-live-" + suffix;
String stackName = "cfn-retain-live-" + suffix;
String stackId = createStack(stackName, """
{"Resources": {"Bucket": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": "%s"}}}}
""".formatted(bucket));
CfnStackWaits.awaitStatus(stackId, "CREATE_COMPLETE");
assertValidationError(deleteStack(stackName, "Bucket"), "Invalid operation on stack [" + stackId
+ "]. When you delete a stack, specify which resources to retain only when the stack is in the"
+ " DELETE_FAILED state.");
assertThat(describeStacks(stackId), containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
// An empty list is the one the AWS CLI sends for --retain-resources with no ids: no list at all.
cfn("DeleteStack", stackName)
.formParam("RetainResources", "")
.when()
.post("/")
.then()
.statusCode(200);
CfnStackWaits.awaitStatus(stackId, "DELETE_COMPLETE");
bucketRequest(bucket).then().statusCode(404);
}
@Test
void malformedRetainListIsRefusedBeforeTheStackIsLookedUp() {
String missing = "cfn-retain-missing-" + Long.toString(System.nanoTime(), 36);
String tooLong = "a".repeat(256);
String lengths = "' at 'resourcesToRetain' failed to satisfy constraint: Member must satisfy constraint:"
+ " [Member must have length less than or equal to 255, Member must have length greater than"
+ " or equal to 1]";
assertValidationError(deleteStack(missing, ""), "1 validation error detected: Value '[]" + lengths);
assertValidationError(deleteStack(missing, "x", tooLong),
"1 validation error detected: Value '[x, " + tooLong + "]" + lengths);
assertValidationError(deleteStack(missing, "x", "x"), "The logical IDs specified for the resources to"
+ " retain are not all unique. Specify unique logical IDs for all of the resources that you want"
+ " to retain.");
deleteStack(missing, "x", "a".repeat(255)).then().statusCode(200);
}
/**
* A stack of three buckets whose delete failed on the two holding an object: DataBucket and
* SpareBucket are DELETE_FAILED, the empty OtherBucket is DELETE_COMPLETE.
*/
private static String deleteFailedStack(String stackName, String data, String spare, String other) {
String stackId = createStack(stackName, """
{
"Resources": {
"DataBucket": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": "%s"}},
"SpareBucket": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": "%s"}},
"OtherBucket": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": "%s"}}
}
}
""".formatted(data, spare, other));
CfnStackWaits.awaitStatus(stackId, "CREATE_COMPLETE");
for (String bucket : new String[] {data, spare}) {
given().contentType("text/plain").body("kept").when().put("/" + bucket + "/object.txt")
.then().statusCode(200);
}
deleteStack(stackName).then().statusCode(200);
CfnStackWaits.awaitStatus(stackId, "DELETE_FAILED");
bucketRequest(other).then().statusCode(404);
return stackId;
}
private static void assertValidationError(Response response, String message) {
response.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message", equalTo(message));
}
private static String createStack(String stackName, String template) {
String xml = cfn("CreateStack", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString();
int start = xml.indexOf("<StackId>") + "<StackId>".length();
return xml.substring(start, xml.indexOf("</StackId>", start));
}
private static Response deleteStack(String stackName, String... retainResources) {
RequestSpecification request = cfn("DeleteStack", stackName);
for (int i = 0; i < retainResources.length; i++) {
request.formParam("RetainResources.member." + (i + 1), retainResources[i]);
}
return request.when().post("/");
}
private static String describeStacks(String stackId) {
return cfn("DescribeStacks", stackId)
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString();
}
private static Response bucketRequest(String bucket) {
return given().header("Host", bucket + ".localhost").when().get("/");
}
}
@@ -116,7 +116,7 @@ class CloudFormationServiceRestoreIntegrationTest {
List<Future<?>> runningOperations = fillExecutor();
try {
AwsException rejected = assertThrows(AwsException.class,
() -> service.deleteStack(targetStack, REGION));
() -> service.deleteStack(targetStack, List.of(), REGION));
assertEquals("LimitExceededException", rejected.getErrorCode());
assertEquals("CREATE_COMPLETE", service.describeStacks(targetStack, REGION).getFirst().getStatus());
} finally {
@@ -420,6 +420,102 @@ class CloudFormationServiceRollbackTest {
assertEquals("DELETE_COMPLETE", stack.getStatus());
}
@Test
void deleteStack_retainingResourcesOfADeleteFailedStack_skipsOnlyThose() throws Exception {
Stack stack = deleteFailedStack("retained-delete");
StackResource data = stack.getResources().get("Data");
StackResource spare = stack.getResources().get("Spare");
service.deleteStack("retained-delete", List.of("Data"), REGION, ACCOUNT).get(10, TimeUnit.SECONDS);
assertEquals("DELETE_COMPLETE", stack.getStatus());
verify(provisioner, never()).delete(eq(data), anyString());
verify(provisioner).delete(spare, REGION);
assertEquals("DELETE_SKIPPED", data.getStatus());
assertNull(data.getStatusReason());
assertTrue(stack.getEvents().stream().anyMatch(event -> "Data".equals(event.getLogicalResourceId())
&& "DELETE_SKIPPED".equals(event.getResourceStatus())));
}
@Test
void deleteStack_retainingResourcesTheDeleteWouldNotTouch_skipsThemToo() throws Exception {
Stack stack = deleteFailedStack("retained-failed-create");
StackResource borrowed = resource("Borrowed", "existing-param", "AWS::SSM::Parameter", "CREATE_FAILED");
StackResource unnamed = resource("Unnamed", null, "AWS::SSM::Parameter", "CREATE_FAILED");
for (StackResource failed : List.of(borrowed, unnamed)) {
failed.setStatusReason("Error occurred during operation 'PutParameter'.");
stack.getResources().put(failed.getLogicalId(), failed);
}
service.deleteStack("retained-failed-create", List.of("Data", "Borrowed", "Unnamed"), REGION, ACCOUNT)
.get(10, TimeUnit.SECONDS);
assertEquals("DELETE_COMPLETE", stack.getStatus());
for (StackResource failed : List.of(borrowed, unnamed)) {
verify(provisioner, never()).delete(eq(failed), anyString());
assertEquals("DELETE_SKIPPED", failed.getStatus());
assertNull(failed.getStatusReason());
assertTrue(stack.getEvents().stream().anyMatch(event -> failed.getLogicalId()
.equals(event.getLogicalResourceId()) && "DELETE_SKIPPED".equals(event.getResourceStatus())));
}
}
@Test
void deleteStack_retriedWhileDeleting_refusesADifferentRetainList() throws Exception {
Stack stack = deleteFailedStack("retain-retried");
StackResource spare = stack.getResources().get("Spare");
CountDownLatch deleting = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
doAnswer(invocation -> {
deleting.countDown();
release.await(30, TimeUnit.SECONDS);
return null;
}).when(provisioner).delete(eq(spare), eq(REGION));
Future<?> first = service.deleteStack("retain-retried", List.of("Data"), REGION, ACCOUNT);
assertTrue(deleting.await(10, TimeUnit.SECONDS));
service.deleteStack("retain-retried", List.of("Data"), REGION, ACCOUNT).get(5, TimeUnit.SECONDS);
for (List<String> other : List.of(List.<String>of(), List.of("Data", "Spare"))) {
AwsException error = assertThrows(AwsException.class,
() -> service.deleteStack("retain-retried", other, REGION, ACCOUNT));
assertEquals("ValidationError", error.getErrorCode());
assertEquals("A delete stack operation is already in progress for stack [" + stack.getStackId()
+ "]. Do not submit another delete stack request specifying different resources to retain"
+ " or resources to retain in a different order.", error.getMessage());
}
release.countDown();
first.get(10, TimeUnit.SECONDS);
verify(provisioner, times(1)).delete(spare, REGION);
assertEquals("DELETE_COMPLETE", stack.getStatus());
}
@Test
void deleteStack_retriedOnAChildItsParentIsDeleting_isANoOp() throws Exception {
Stack child = deleteFailedStack("retain-child");
child.setRetainResources(List.of("Data"));
Stack parent = liveStack("retain-parent");
parent.getResources().clear();
parent.getResources().put("Child",
resource("Child", child.getStackId(), "AWS::CloudFormation::Stack", "CREATE_COMPLETE"));
StackResource spare = child.getResources().get("Spare");
CountDownLatch deleting = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
doAnswer(invocation -> {
deleting.countDown();
release.await(30, TimeUnit.SECONDS);
return null;
}).when(provisioner).delete(eq(spare), eq(REGION));
Future<?> parentDelete = service.deleteStack("retain-parent", REGION, ACCOUNT);
assertTrue(deleting.await(10, TimeUnit.SECONDS));
service.deleteStack("retain-child", List.of(), REGION, ACCOUNT).get(5, TimeUnit.SECONDS);
release.countDown();
parentDelete.get(10, TimeUnit.SECONDS);
assertEquals("DELETE_COMPLETE", child.getStatus());
}
@Test
void executeChangeSet_onStackBeingDeleted_isRefused() {
Stack stack = liveStack("executed-while-deleting");
@@ -1774,6 +1870,21 @@ class CloudFormationServiceRollbackTest {
return stack;
}
/** A live stack whose delete failed on both of its buckets, Data and Spare. */
private Stack deleteFailedStack(String stackName) {
Stack stack = liveStack(stackName);
stack.setStatus("DELETE_FAILED");
stack.getResources().clear();
for (String logicalId : List.of("Data", "Spare")) {
StackResource bucket = resource(logicalId, logicalId.toLowerCase() + "-bucket", "AWS::S3::Bucket",
"DELETE_FAILED");
bucket.setStatusReason("The bucket you tried to delete is not empty");
stack.getResources().put(logicalId, bucket);
}
when(provisioner.completeDeleteCleanup(any())).thenReturn(UpdateCleanupResult.notApplicable());
return stack;
}
private static List<String> stackEventStatuses(Stack stack) {
return stack.getEvents().stream()
.filter(event -> "AWS::CloudFormation::Stack".equals(event.getResourceType()))