fix(cloudformation): fail stack delete when a managed resource cannot be deleted (#1554)

DeleteStack swallowed every resource-deletion failure and always reported
DELETE_COMPLETE. Deleting a stack that owned a non-empty AWS::S3::Bucket
therefore "succeeded" while the bucket and its objects were left behind,
which diverges from AWS (S3 refuses to delete a non-empty bucket, so the
stack must end in DELETE_FAILED).

- CloudFormationResourceProvisioner#delete no longer wraps resource deletion
  in a catch-all; failures propagate to the stack-level handler. The lenient
  *Safe helpers and the intentional KMS key no-op are preserved.
- CloudFormationService#deleteStackResources now records per-resource
  failures: the resource is marked DELETE_FAILED with a reason and event,
  remaining resources are still attempted, and the stack settles into
  DELETE_FAILED (retaining the stack and its exports) instead of being
  reported as deleted. Resources left in DELETE_FAILED are re-attempted on a
  subsequent delete, matching AWS retry behavior.

This corrects the same silent-success deviation for every managed resource
type, not just S3 buckets.

Adds a Java integration regression test and AWS CLI compatibility tests
covering both the non-empty (DELETE_FAILED) and empty (DELETE_COMPLETE)
bucket cases.

Fixes #1539
This commit is contained in:
Dixit R Jain authored and GitHub committed 2026-06-25 22:47:19 -05:00
1 parent 56f846988f
commit 0530ca11ab
4 files changed
+292 -59

No files matched your search

@@ -389,63 +389,67 @@ public class CloudFormationResourceProvisioner {
delete(resourceType, resource.getPhysicalId(), region);
}
/**
* Deletes a single resource by type + physical id. Failures propagate to the caller
* (CloudFormationService#deleteStackResources) so the stack transitions to DELETE_FAILED,
* matching AWS — e.g. deleting a non-empty S3 bucket raises BucketNotEmpty and must not be
* silently reported as a successful stack deletion. Resource types that AWS itself treats
* leniently keep their dedicated handling: the {@code *Safe} helpers below swallow expected
* conflicts, and KMS keys are intentionally left for scheduled deletion.
*/
public void delete(String resourceType, String physicalId, String region) {
try {
switch (resourceType) {
case "AWS::S3::Bucket" -> s3Service.deleteBucket(physicalId);
case "AWS::SQS::Queue" -> sqsService.deleteQueue(physicalId, region);
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::IAM::Role" -> deleteRoleSafe(physicalId);
case "AWS::IAM::Policy", "AWS::IAM::ManagedPolicy" -> deletePolicySafe(physicalId);
case "AWS::IAM::InstanceProfile" -> iamService.deleteInstanceProfile(physicalId);
case "AWS::SSM::Parameter" -> ssmService.deleteParameter(physicalId, region);
case "AWS::KMS::Key" -> {
} // KMS keys can't be immediately deleted; skip
case "AWS::KMS::Alias" -> kmsService.deleteAlias(physicalId, region);
case "AWS::SecretsManager::Secret" ->
secretsManagerService.deleteSecret(physicalId, null, true, region);
case "AWS::Events::Rule" -> deleteEventBridgeRuleSafe(physicalId, region);
case "AWS::ApiGateway::RestApi" -> apiGatewayService.deleteRestApi(region, physicalId);
case "AWS::ApiGatewayV2::Api" -> apiGatewayV2Service.deleteApi(region, physicalId);
case "AWS::ECR::Repository" ->
ecrService.deleteRepository(physicalId, null, true, region);
case "AWS::Pipes::Pipe" -> pipesService.deletePipe(physicalId, region);
case "AWS::StepFunctions::StateMachine" -> stepFunctionsService.deleteStateMachine(physicalId);
case "AWS::Lambda::EventSourceMapping" -> lambdaService.deleteEventSourceMapping(physicalId);
case "AWS::Lambda::LayerVersion" -> deleteLambdaLayerVersion(physicalId, region);
case "AWS::Cognito::UserPool" -> cognitoService.deleteUserPool(physicalId);
case "AWS::Cognito::UserPoolClient" -> cognitoService.deleteUserPoolClient(physicalId);
case "AWS::ECS::Cluster" -> ecsService.deleteCluster(physicalId, region);
case "AWS::ECS::TaskDefinition" -> ecsService.deregisterTaskDefinition(physicalId, region);
case "AWS::ECS::Service" -> deleteEcsServiceSafe(physicalId, region);
case "AWS::ElasticLoadBalancingV2::LoadBalancer" -> elbV2Service.deleteLoadBalancer(region, physicalId);
case "AWS::ElasticLoadBalancingV2::TargetGroup" -> elbV2Service.deleteTargetGroup(region, physicalId);
case "AWS::ElasticLoadBalancingV2::Listener" -> elbV2Service.deleteListener(region, physicalId);
case "AWS::ElasticLoadBalancingV2::ListenerRule" -> elbV2Service.deleteRule(region, physicalId);
case "AWS::KinesisFirehose::DeliveryStream" -> firehoseService.deleteDeliveryStream(physicalId);
case "AWS::EC2::SecurityGroup" -> ec2Service.deleteSecurityGroup(region, physicalId);
case "AWS::EC2::Instance" -> ec2Service.terminateInstances(region, List.of(physicalId));
case "AWS::RDS::DBInstance" -> rdsService.deleteDbInstance(physicalId);
case "AWS::RDS::DBCluster" -> rdsService.deleteDbCluster(physicalId);
case "AWS::RDS::DBSubnetGroup" -> rdsService.deleteDbSubnetGroup(physicalId);
case "AWS::RDS::DBParameterGroup" -> rdsService.deleteDbParameterGroup(physicalId);
case "AWS::RDS::DBClusterParameterGroup" -> rdsService.deleteDbClusterParameterGroup(physicalId);
case "AWS::EKS::Cluster" -> eksService.deleteCluster(physicalId);
case "AWS::Logs::LogGroup" -> logsService.deleteLogGroup(physicalId, region);
case "AWS::Kinesis::Stream" -> kinesisService.deleteStream(physicalId, region);
case "AWS::CloudWatch::Alarm" ->
cloudWatchMetricsService.deleteAlarms(List.of(physicalId), region);
case "AWS::AutoScaling::LaunchConfiguration" ->
autoScalingService.deleteLaunchConfiguration(region, physicalId);
case "AWS::AutoScaling::AutoScalingGroup" ->
autoScalingService.deleteAutoScalingGroup(region, physicalId, true);
default -> LOG.debugv("Skipping delete of unsupported resource type: {0}", resourceType);
}
} catch (Exception e) {
LOG.debugv("Error deleting {0} ({1}): {2}", resourceType, physicalId, e.getMessage());
switch (resourceType) {
case "AWS::S3::Bucket" -> s3Service.deleteBucket(physicalId);
case "AWS::SQS::Queue" -> sqsService.deleteQueue(physicalId, region);
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::IAM::Role" -> deleteRoleSafe(physicalId);
case "AWS::IAM::Policy", "AWS::IAM::ManagedPolicy" -> deletePolicySafe(physicalId);
case "AWS::IAM::InstanceProfile" -> iamService.deleteInstanceProfile(physicalId);
case "AWS::SSM::Parameter" -> ssmService.deleteParameter(physicalId, region);
case "AWS::KMS::Key" -> {
} // KMS keys can't be immediately deleted; skip
case "AWS::KMS::Alias" -> kmsService.deleteAlias(physicalId, region);
case "AWS::SecretsManager::Secret" ->
secretsManagerService.deleteSecret(physicalId, null, true, region);
case "AWS::Events::Rule" -> deleteEventBridgeRuleSafe(physicalId, region);
case "AWS::ApiGateway::RestApi" -> apiGatewayService.deleteRestApi(region, physicalId);
case "AWS::ApiGatewayV2::Api" -> apiGatewayV2Service.deleteApi(region, physicalId);
case "AWS::ECR::Repository" ->
ecrService.deleteRepository(physicalId, null, true, region);
case "AWS::Pipes::Pipe" -> pipesService.deletePipe(physicalId, region);
case "AWS::StepFunctions::StateMachine" -> stepFunctionsService.deleteStateMachine(physicalId);
case "AWS::Lambda::EventSourceMapping" -> lambdaService.deleteEventSourceMapping(physicalId);
case "AWS::Lambda::LayerVersion" -> deleteLambdaLayerVersion(physicalId, region);
case "AWS::Cognito::UserPool" -> cognitoService.deleteUserPool(physicalId);
case "AWS::Cognito::UserPoolClient" -> cognitoService.deleteUserPoolClient(physicalId);
case "AWS::ECS::Cluster" -> ecsService.deleteCluster(physicalId, region);
case "AWS::ECS::TaskDefinition" -> ecsService.deregisterTaskDefinition(physicalId, region);
case "AWS::ECS::Service" -> deleteEcsServiceSafe(physicalId, region);
case "AWS::ElasticLoadBalancingV2::LoadBalancer" -> elbV2Service.deleteLoadBalancer(region, physicalId);
case "AWS::ElasticLoadBalancingV2::TargetGroup" -> elbV2Service.deleteTargetGroup(region, physicalId);
case "AWS::ElasticLoadBalancingV2::Listener" -> elbV2Service.deleteListener(region, physicalId);
case "AWS::ElasticLoadBalancingV2::ListenerRule" -> elbV2Service.deleteRule(region, physicalId);
case "AWS::KinesisFirehose::DeliveryStream" -> firehoseService.deleteDeliveryStream(physicalId);
case "AWS::EC2::SecurityGroup" -> ec2Service.deleteSecurityGroup(region, physicalId);
case "AWS::EC2::Instance" -> ec2Service.terminateInstances(region, List.of(physicalId));
case "AWS::RDS::DBInstance" -> rdsService.deleteDbInstance(physicalId);
case "AWS::RDS::DBCluster" -> rdsService.deleteDbCluster(physicalId);
case "AWS::RDS::DBSubnetGroup" -> rdsService.deleteDbSubnetGroup(physicalId);
case "AWS::RDS::DBParameterGroup" -> rdsService.deleteDbParameterGroup(physicalId);
case "AWS::RDS::DBClusterParameterGroup" -> rdsService.deleteDbClusterParameterGroup(physicalId);
case "AWS::EKS::Cluster" -> eksService.deleteCluster(physicalId);
case "AWS::Logs::LogGroup" -> logsService.deleteLogGroup(physicalId, region);
case "AWS::Kinesis::Stream" -> kinesisService.deleteStream(physicalId, region);
case "AWS::CloudWatch::Alarm" ->
cloudWatchMetricsService.deleteAlarms(List.of(physicalId), region);
case "AWS::AutoScaling::LaunchConfiguration" ->
autoScalingService.deleteLaunchConfiguration(region, physicalId);
case "AWS::AutoScaling::AutoScalingGroup" ->
autoScalingService.deleteAutoScalingGroup(region, physicalId, true);
default -> LOG.debugv("Skipping delete of unsupported resource type: {0}", resourceType);
}
}
@@ -549,17 +549,49 @@ public class CloudFormationService {
List<StackResource> resources = new ArrayList<>(stack.getResources().values());
Collections.reverse(resources); // Delete in reverse order
List<String> failedResources = new ArrayList<>();
for (StackResource resource : resources) {
if (resource.getPhysicalId() != null && "CREATE_COMPLETE".equals(resource.getStatus())) {
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "DELETE_IN_PROGRESS", null);
// CREATE_COMPLETE: first delete attempt. DELETE_FAILED: a previous delete left the
// resource behind (e.g. the bucket was non-empty); AWS re-attempts it on retry.
boolean deletable = "CREATE_COMPLETE".equals(resource.getStatus())
|| "DELETE_FAILED".equals(resource.getStatus());
if (resource.getPhysicalId() == null || !deletable) {
continue;
}
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "DELETE_IN_PROGRESS", null);
try {
provisioner.delete(resource, region);
resource.setStatus("DELETE_COMPLETE");
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "DELETE_COMPLETE", null);
} catch (Exception e) {
// AWS leaves the stack in DELETE_FAILED when a managed resource cannot be
// deleted (e.g. a non-empty S3 bucket raises BucketNotEmpty). The stack must
// not be reported as a successful deletion while the resource still exists.
// Remaining resources are still attempted, matching AWS.
failedResources.add(resource.getLogicalId());
resource.setStatus("DELETE_FAILED");
resource.setStatusReason(e.getMessage());
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "DELETE_FAILED", e.getMessage());
LOG.warnv("Failed to delete {0} ({1}) in stack {2}: {3}",
resource.getResourceType(), resource.getPhysicalId(),
stack.getStackName(), e.getMessage());
}
}
if (!failedResources.isEmpty()) {
String reason = "The following resource(s) failed to delete: ["
+ String.join(", ", failedResources) + "].";
stack.setStatus("DELETE_FAILED");
stack.setStatusReason(reason);
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "DELETE_FAILED", reason);
LOG.errorv("Stack {0} delete failed: {1}", stack.getStackName(), reason);
return;
}
stack.setStatus("DELETE_COMPLETE");
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "DELETE_COMPLETE", null);