fix(cloudformation): treat delete of an already-removed DynamoDB table or Lambda function as idempotent (#1803)

* fix(cloudformation): treat delete of an already-removed DynamoDB table or Lambda function as idempotent

When a stack is torn down after a rollback has already deleted some of its
resources, CloudFormation re-issues the delete against resources that no
longer exist. DynamoDB DeleteTable and Lambda DeleteFunction both raise
ResourceNotFoundException in that case, which flipped the stack to
DELETE_FAILED and wedged the stack name against a later create.

Route the AWS::DynamoDB::Table and AWS::Lambda::Function delete cases
through deleteDynamoTableSafe / deleteLambdaFunctionSafe, which swallow
ResourceNotFoundException (treating an absent resource as already deleted,
as AWS does) while still re-throwing any other AwsException so genuine
conflicts continue to surface as DELETE_FAILED.

* test(cloudformation): cover idempotent delete boundaries

* chore(ci): retrigger flaky checks
This commit is contained in:
Alex Banna authored and GitHub committed 2026-08-04 22:22:13 -05:00
1 parent 48b2139b4f
commit 5cb26ff117
3 files changed
+235 -2

No files matched your search

@@ -455,8 +455,8 @@ public class CloudFormationResourceProvisioner {
case "AWS::S3::Bucket" -> s3Service.deleteBucket(physicalId);
case "AWS::SNS::Topic" -> snsService.deleteTopic(physicalId, region);
case "AWS::SNS::Subscription" -> snsService.unsubscribe(physicalId, region);
case "AWS::DynamoDB::Table" -> dynamoDbService.deleteTable(physicalId, region);
case "AWS::Lambda::Function" -> lambdaService.deleteFunction(region, physicalId);
case "AWS::DynamoDB::Table" -> deleteDynamoTableSafe(physicalId, region);
case "AWS::Lambda::Function" -> deleteLambdaFunctionSafe(physicalId, region);
case "AWS::IAM::Role" -> deleteRoleSafe(physicalId);
// AWS::IAM::Policy is inline: it is removed together with its owning principal (see
// deleteRoleSafe), or precisely via the StackResource-aware delete path. Nothing to do
@@ -4261,6 +4261,28 @@ public class CloudFormationResourceProvisioner {
}
}
private void deleteDynamoTableSafe(String tableName, String region) {
try {
dynamoDbService.deleteTable(tableName, region);
} catch (AwsException e) {
if (!"ResourceNotFoundException".equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("DynamoDB table already gone, treating as deleted: {0}", tableName);
}
}
private void deleteLambdaFunctionSafe(String functionName, String region) {
try {
lambdaService.deleteFunction(region, functionName);
} catch (AwsException e) {
if (!"ResourceNotFoundException".equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("Lambda function already gone, treating as deleted: {0}", functionName);
}
}
private void deleteManagedPolicy(StackResource resource) {
String policyArn = resource.getPhysicalId();
for (String roleName : managedPolicyRoleTargets(resource)) {
@@ -0,0 +1,124 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Verifies deleting a stack whose underlying resource was already removed out-of-band completes
* (DELETE_COMPLETE) rather than failing. AWS CloudFormation treats deleting an absent resource as an
* idempotent no-op — this matters because a rolled-back stack has already deleted some of its
* resources, so tearing that stack down re-issues DeleteTable/DeleteFunction against resources that
* no longer exist. Without the {@code *Safe} wrappers those "not found" errors flipped the stack to
* DELETE_FAILED, wedging the stack name against a later create.
*
* <p>Exercised end-to-end through the DynamoDB path (metadata-only, so Docker-free). Hermetic unit
* coverage verifies both the DynamoDB and Lambda wrappers, including propagation of other errors.
*/
@QuarkusTest
class CloudFormationDeleteIdempotencyIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
private static final String DDB_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/dynamodb/aws4_request";
private static final String DDB_CT = "application/x-amz-json-1.0";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void deletingStackWhoseTableWasRemovedOutOfBandStillCompletes() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String tableName = "idem-delete-table-" + suffix;
String stackName = "idem-delete-stack-" + suffix;
String template = """
{
"Resources": {
"T": {
"Type": "AWS::DynamoDB::Table",
"Properties": {
"TableName": "%s",
"AttributeDefinitions": [{"AttributeName":"pk","AttributeType":"S"}],
"KeySchema": [{"AttributeName":"pk","KeyType":"HASH"}],
"BillingMode": "PAY_PER_REQUEST"
}
}
}
}
""".formatted(tableName);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when().post("/").then().statusCode(200);
// CloudFormationQueryHandler awaits executeChangeSet before CreateStack returns, so this
// one-shot assertion verifies the handler's synchronous completion contract.
assertStackStatus(stackName, "CREATE_COMPLETE");
// Remove the table out-of-band — mimics a rollback having already deleted it.
given()
.contentType(DDB_CT)
.header("Authorization", DDB_AUTH)
.header("X-Amz-Target", "DynamoDB_20120810.DeleteTable")
.body("{\"TableName\":\"" + tableName + "\"}")
.when().post("/").then().statusCode(200);
// Deleting the stack must still succeed (was DELETE_FAILED: "Requested resource not found").
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when().post("/").then().statusCode(200);
// DeleteStack runs asynchronously: poll until the stack is gone (a successful delete removes it
// entirely). A failed delete would instead leave it queryable as DELETE_FAILED — fail fast on that.
awaitStackDeleted(stackName);
}
private void awaitStackDeleted(String stackName) throws InterruptedException {
for (int i = 0; i < 100; i++) {
String body = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when().post("/").then().extract().asString();
if (body.contains("does not exist")) {
return;
}
if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
fail("stack delete failed instead of treating the already-removed table as deleted: " + body);
}
Thread.sleep(50);
}
fail("stack " + stackName + " was not deleted within the timeout");
}
private void assertStackStatus(String stackName, String status) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>" + status + "</StackStatus>"));
}
}
@@ -0,0 +1,87 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
class CloudFormationDeleteIdempotencyTest {
private static final String REGION = "us-east-1";
private DynamoDbService dynamoDbService;
private LambdaService lambdaService;
private CloudFormationResourceProvisioner provisioner;
@BeforeEach
void setUp() {
dynamoDbService = mock(DynamoDbService.class);
lambdaService = mock(LambdaService.class);
provisioner = new CloudFormationResourceProvisioner(
null, null, null, dynamoDbService, lambdaService,
null, null, null, null, null,
null, null, null, null, null, null,
new ObjectMapper(),
null, null, null, null, null, null, null,
null, null, null, null, null, null, null,
new CloudFormationResourceRegistry(List.of()));
}
@Test
void missingDynamoDbTableIsAlreadyDeleted() {
doThrow(awsError("ResourceNotFoundException"))
.when(dynamoDbService).deleteTable("missing-table", REGION);
assertDoesNotThrow(() -> provisioner.delete("AWS::DynamoDB::Table", "missing-table", REGION));
verify(dynamoDbService).deleteTable("missing-table", REGION);
}
@Test
void missingLambdaFunctionIsAlreadyDeleted() {
doThrow(awsError("ResourceNotFoundException"))
.when(lambdaService).deleteFunction(REGION, "missing-function");
assertDoesNotThrow(() -> provisioner.delete("AWS::Lambda::Function", "missing-function", REGION));
verify(lambdaService).deleteFunction(REGION, "missing-function");
}
@Test
void dynamoDbDeleteFailureStillPropagates() {
AwsException expected = awsError("InternalServerError");
doThrow(expected).when(dynamoDbService).deleteTable("table", REGION);
AwsException actual = assertThrows(AwsException.class,
() -> provisioner.delete("AWS::DynamoDB::Table", "table", REGION));
assertSame(expected, actual);
}
@Test
void lambdaDeleteFailureStillPropagates() {
AwsException expected = awsError("ServiceException");
doThrow(expected).when(lambdaService).deleteFunction(REGION, "function");
AwsException actual = assertThrows(AwsException.class,
() -> provisioner.delete("AWS::Lambda::Function", "function", REGION));
assertSame(expected, actual);
}
private static AwsException awsError(String errorCode) {
return new AwsException(errorCode, "delete failed", 500);
}
}