fix(cloudformation): clean up, roll back and delete AWS::EC2::VPC like the other EC2 types (#5503)

* fix(cloudformation): clean up, roll back and delete AWS::EC2::VPC like the other EC2 types

A CidrBlock change, or a tenancy change other than dedicated to default,
replaces the VPC, but the provisioner never recorded the displaced one and had
no delete arm, so the old VPC was left behind; in-place Tags, EnableDnsSupport
and EnableDnsHostnames changes were not snapshotted, so a later failing
resource left the VPC changed and reported rollback as not implemented.

Ec2VpcCfnProvisioner now follows Ec2NetworkCfnProvisioner: ReplacementCleanup
records the displaced VPC and deletes it after the update commits or restores
it on rollback; a prior-state snapshot restores DNS attributes, tags and a
dedicated-to-default tenancy change on rollback, eagerly when provision itself
fails; and a delete arm through CfnDeletes.safeDelete removes the VPC on stack
teardown, tolerating only InvalidVpcID.NotFound so stack-external dependents
fail the delete with DependencyViolation, as on AWS.

* refactor(cloudformation): use the shared CfnRollback.guarded in the VPC provisioner

* fix(ec2): count instances and NAT gateways as subnet and VPC dependents

DeleteSubnet and DeleteVpc checked subnets, security groups, route tables,
ACLs, gateways and endpoints but not the instances and NAT gateways living in
a subnet, so a stack teardown could remove a subnet and its VPC out from under
an instance launched into it out of band. Both now fail with
DependencyViolation while an instance that is not terminated (shutting-down
still holds its interface) or a NAT gateway that is not deleted sits in the
subnet, as on AWS. The rollback integration test also pins Boom after the VPC
with DependsOn so the scenario cannot pass by ordering alone.

* fix(cloudformation): keep the VPC and subnet rollback snapshot until the restore succeeds

rollbackUpdate removed the in-place snapshot before restoring; a restore that
threw left the resource persisted as UPDATE_FAILED with no prior state for a
ContinueUpdateRollback retry. Ec2VpcCfnProvisioner and the pre-existing
Ec2NetworkCfnProvisioner now restore first and remove after, as the AgentCore
provisioner already did. The describeTags loop shared by Ec2Tags.reconcile and
the VPC snapshot moves to Ec2Tags.current.

* fix(ec2): count standalone network interfaces and interface endpoints as subnet dependents

A subnet is pinned by any network interface in it, not only the ones an
instance or NAT gateway owns: a standalone interface from
CreateNetworkInterface and an interface or Gateway Load Balancer endpoint
keep DeleteSubnet at DependencyViolation on AWS too. The endpoint test that
deleted a subnet out from under a live endpoint relied on that state being
reachable; it now asserts the refusal and that the published interface ids
are unchanged.

* fix(cloudformation): wait for terminated on instance delete and resolve VPC properties before creating

With real containers an instance is still shutting-down when the stack's
instance delete returns, so the subnet delete that follows was refused by the
new resident check and the stack ended DELETE_FAILED. The instance provisioner
now polls until the instance is terminated or gone, as CloudFormation does.

The VPC provisioner created the VPC before EnableDnsSupport, EnableDnsHostnames
and Tags were resolved, so a resolution failure left it untracked; the resolves
now run first, as the subnet provisioner does. Ec2Tags.current drops reserved
aws: keys so a rollback snapshot never tries to write one, and the replacement
integration test waits in the stack's own region.
This commit is contained in:
danielxoi authored and GitHub committed 2026-10-15 11:14:56 -04:00
1 parent a318dc7b90
commit fa682b2d62
14 files changed
+907 -69

No files matched your search

@@ -41,6 +41,9 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
private static final String DECLARED_IAM_PROFILE_ATTR = "__FlociDeclaredIamInstanceProfile";
private final Ec2Service ec2Service;
/** How long {@link #delete} waits for a terminated instance; package-visible so tests can shorten it. */
long terminateTimeoutMillis = 90_000L;
long terminatePollMillis = 250L;
@Inject
public Ec2InstanceCfnProvisioner(Ec2Service ec2Service) {
@@ -393,11 +396,63 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
return ReplacementCleanup.rollback(resource, this::delete);
}
/**
* Terminates the instance and waits until EC2 reports it {@code terminated} (or gone). With
* real containers the instance sits in {@code shutting-down} until the container manager's
* executor finishes, and a subnet or VPC delete that follows in the same stack delete refuses
* a resident that is still shutting down. In mock mode the terminate is synchronous, so the
* first describe already sees {@code terminated}.
*/
@Override
public void delete(String resourceType, String physicalId, String region) {
// Tolerate an instance already terminated out of band, so DeleteStack does not fail on it.
CfnDeletes.safeDelete("EC2 instance", physicalId,
() -> ec2Service.terminateInstances(region, List.of(physicalId)),
"InvalidInstanceID.NotFound");
awaitTerminated(region, physicalId);
}
private void awaitTerminated(String region, String instanceId) {
long deadline = System.currentTimeMillis() + terminateTimeoutMillis;
while (true) {
if (isTerminatedOrGone(region, instanceId)) {
return;
}
if (System.currentTimeMillis() >= deadline) {
throw new AwsException("ValidationError", "Instance " + instanceId
+ " did not reach terminated within " + (terminateTimeoutMillis / 1000) + "s", 400);
}
try {
Thread.sleep(terminatePollMillis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AwsException("ValidationError",
"Interrupted while waiting for instance " + instanceId + " to terminate", 400);
}
}
}
private boolean isTerminatedOrGone(String region, String instanceId) {
List<Reservation> reservations;
try {
reservations = ec2Service.describeInstances(region, List.of(instanceId), null);
} catch (AwsException e) {
if ("InvalidInstanceID.NotFound".equals(e.getErrorCode())) {
return true;
}
throw e;
}
if (reservations == null) {
return true;
}
for (Reservation reservation : reservations) {
for (Instance instance : reservation.getInstances()) {
if (instanceId.equals(instance.getInstanceId())) {
InstanceState state = instance.getState();
return state != null && "terminated".equals(state.getName());
}
}
}
return true;
}
}
@@ -122,10 +122,12 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
/**
* A replacement is undone through the cleanup record: the displaced entity was never touched.
* A reused entity that an update changed in place (tags, a subnet's MapPublicIpOnLaunch, a
* route's target) is put back from the snapshot taken before the change. Without either, the
* update changed nothing about the entity. A provision that fails mid-way restores its own
* snapshot before the failure propagates (see {@link #guarded}), so the previous metadata the
* engine restores for that resource matches the entity again.
* route's target) is put back from the snapshot taken before the change; the snapshot is
* removed only after the restore succeeds, so a restore that throws keeps it for a
* ContinueUpdateRollback retry. Without either, the update changed nothing about the entity.
* A provision that fails mid-way restores its own snapshot before the failure propagates (see
* {@link #guarded}), so the previous metadata the engine restores for that resource matches
* the entity again.
*/
@Override
public boolean rollbackUpdate(StackResource resource) {
@@ -133,10 +135,7 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR);
return true;
}
String snapshot = resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR);
if (snapshot != null) {
restoreInPlace(resource, snapshot);
}
undoInPlace(resource);
return true;
}
@@ -9,9 +9,9 @@ import java.util.List;
import java.util.Map;
/**
* Tag reconciliation shared by the EC2 provisioners ({@code Ec2InstanceCfnProvisioner} and
* {@code Ec2SecurityGroupCfnProvisioner}). Both drive it from the desired tags resolved via
* {@link ProvisionContext#resolveTags}; the reconcile itself is identical.
* Tag reconciliation shared by the EC2 provisioners ({@code Ec2InstanceCfnProvisioner},
* {@code Ec2SecurityGroupCfnProvisioner} and {@code Ec2VpcCfnProvisioner}). They drive it from the
* desired tags resolved via {@link ProvisionContext#resolveTags}; the reconcile itself is identical.
*/
final class Ec2Tags {
@@ -26,17 +26,27 @@ final class Ec2Tags {
}
/**
* Brings a resource's tags to {@code desired}: removes the keys AWS currently has that the
* template no longer declares, then creates or overwrites the declared ones.
* The user tags EC2 currently holds for the resource, keyed by tag key in DescribeTags order.
* Reserved {@code aws:} keys are never part of the user tag set, so neither {@link #reconcile}
* nor a rollback snapshot taken from this map can try to write one.
*/
static void reconcile(Ec2Service ec2Service, String region, String resourceId, Map<String, String> desired) {
List<Tag> add = validatedTags(desired);
static Map<String, String> current(Ec2Service ec2Service, String region, String resourceId) {
Map<String, String> current = new LinkedHashMap<>();
for (Map<String, String> entry : ec2Service.describeTags(region, Map.of("resource-id", List.of(resourceId)))) {
if (!Ec2Service.isAwsTagKey(entry.get("key"))) {
current.put(entry.get("key"), entry.get("value"));
}
}
return current;
}
/**
* Brings a resource's tags to {@code desired}: removes the keys AWS currently has that the
* template no longer declares, then creates or overwrites the declared ones.
*/
static void reconcile(Ec2Service ec2Service, String region, String resourceId, Map<String, String> desired) {
List<Tag> add = validatedTags(desired);
Map<String, String> current = current(ec2Service, region, resourceId);
List<String> stale = ProvisionContext.staleTagKeys(current, desired);
if (!stale.isEmpty()) {
List<Tag> remove = new ArrayList<>();
@@ -1,6 +1,9 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.CidrCanonicalizer;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
@@ -11,6 +14,7 @@ import io.github.hectorvent.floci.services.ec2.model.VpcIpv6CidrBlockAssociation
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -32,12 +36,26 @@ import java.util.stream.Collectors;
* instance and security-group provisioners: a key the template dropped is deleted. Stack-level
* tags and the {@code aws:cloudformation:*} system tags are not applied here, matching every other
* EC2 provisioner in this package.
*
* <p>A replacement leaves the displaced VPC to the {@link ReplacementCleanup} record: it is deleted
* once the update commits, or the resource is pointed back at it when a later resource fails the
* update and it rolls back. An in-place change to a reused VPC is snapshotted before it is written
* (tenancy, the DNS attributes and the tag set), so the same rollback puts them back; a provision
* that fails mid-way restores its own snapshot before the failure propagates. The stack delete
* removes the VPC; it tolerates only {@code InvalidVpcID.NotFound}, so a VPC that still has
* dependents outside the stack fails the delete with {@code DependencyViolation}, as on AWS.
*/
@ApplicationScoped
public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
private static final String DEFAULT_TENANCY = "default";
private static final String DEDICATED_TENANCY = "dedicated";
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* What an in-place update changed on a reused VPC, recorded before the change so a stack
* rollback can put it back. Internal, like the other {@code __Floci} attributes.
*/
static final String IN_PLACE_PRIOR_ATTR = "__FlociEc2VpcPrior";
private final Ec2Service ec2Service;
@@ -53,33 +71,37 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
String region = ctx.region();
String cidr = ctx.resolveOptional(props, "CidrBlock");
String tenancy = ctx.resolveOptional(props, "InstanceTenancy");
String desiredTenancy = tenancy == null || tenancy.isBlank() ? DEFAULT_TENANCY : tenancy;
Vpc reconciled = existingVpcToReconcile(ctx.isUpdate() ? ctx.priorPhysicalId() : null, cidr, desiredTenancy, region);
Vpc vpc = reconciled != null
? reconciled
: ec2Service.createVpc(region, cidr, false, false, desiredTenancy);
String vpcId = vpc.getVpcId();
if (reconciled != null && isDedicatedToDefault(vpc, desiredTenancy)) {
ec2Service.modifyVpcTenancy(region, vpcId, desiredTenancy);
}
// AWS defaults for a non-default VPC: DnsSupport on, DnsHostnames off. A template that
// omits the property (or resolves it to AWS::NoValue, which the engine renders blank) gets
// the default, as CloudFormation applies it on every update too.
String dnsSupport = ctx.resolveOrDefault(props, "EnableDnsSupport", "true");
String dnsHostnames = ctx.resolveOrDefault(props, "EnableDnsHostnames", "false");
ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsSupport",
String.valueOf(Boolean.parseBoolean(dnsSupport)));
ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsHostnames",
String.valueOf(Boolean.parseBoolean(dnsHostnames)));
Ec2Tags.reconcile(ec2Service, region, vpcId, ctx.resolveTags(props, "Tags"));
// the default, as CloudFormation applies it on every update too. Every property resolves
// before the VPC exists, so a resolution failure cannot leave a VPC outside the guard.
boolean dnsSupport = Boolean.parseBoolean(ctx.resolveOrDefault(props, "EnableDnsSupport", "true"));
boolean dnsHostnames = Boolean.parseBoolean(ctx.resolveOrDefault(props, "EnableDnsHostnames", "false"));
Map<String, String> desiredTags = ctx.resolveTags(props, "Tags");
Vpc reconciled = existingVpcToReconcile(ctx.isUpdate() ? ctx.priorPhysicalId() : null, cidr, desiredTenancy, region);
boolean reused = reconciled != null;
Vpc vpc = reused ? reconciled : ec2Service.createVpc(region, cidr, false, false, desiredTenancy);
String vpcId = vpc.getVpcId();
r.setPhysicalId(vpcId);
r.getAttributes().put("VpcId", vpcId);
CfnRollback.guarded(r, ctx, !reused, () -> ec2Service.deleteVpc(region, vpcId), () -> undoInPlace(r), () -> {
if (reused) {
snapshotInPlace(r, vpc, desiredTenancy, dnsSupport, dnsHostnames, desiredTags, region);
}
if (reused && isDedicatedToDefault(vpc, desiredTenancy)) {
ec2Service.modifyVpcTenancy(region, vpcId, desiredTenancy);
}
ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsSupport", String.valueOf(dnsSupport));
ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsHostnames", String.valueOf(dnsHostnames));
Ec2Tags.reconcile(ec2Service, region, vpcId, desiredTags);
});
if (vpc.getCidrBlock() != null) {
r.getAttributes().put("CidrBlock", vpc.getCidrBlock());
}
@@ -89,7 +111,7 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
r.getAttributes().put("Ipv6CidrBlocks", vpc.getIpv6CidrBlockAssociationSet().stream()
.map(VpcIpv6CidrBlockAssociation::getIpv6CidrBlock)
.collect(Collectors.joining(",")));
// Fn::GetAtt DefaultSecurityGroup — CDK's Custom::VpcRestrictDefaultSG handler
// Fn::GetAtt DefaultSecurityGroup: CDK's Custom::VpcRestrictDefaultSG handler
// depends on it resolving to the VPC's default security group id.
ec2Service.describeSecurityGroups(region, List.of(), List.of("default"), Map.of()).stream()
.filter(sg -> vpcId.equals(sg.getVpcId()))
@@ -100,6 +122,123 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
.map(NetworkAcl::getNetworkAclId)
.findFirst()
.ifPresent(aclId -> r.getAttributes().put("DefaultNetworkAcl", aclId));
// A provision that left the resource with a new physical id replaced the VPC: the
// displaced one is deleted once the update commits, or restored if the update rolls back.
ReplacementCleanup.record(r, ctx, attributesBefore);
}
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return ReplacementCleanup.hasReplacement(resource);
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
return ReplacementCleanup.cleanupPhysicalId(resource);
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR);
return ReplacementCleanup.complete(resource, this::delete);
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR);
ReplacementCleanup.clear(resource);
}
/**
* A replacement is undone through the cleanup record: the displaced VPC was never touched. A
* reused VPC that an update changed in place is put back from the snapshot taken before the
* change; the snapshot is removed only after the restore succeeds, so a restore that throws
* keeps it for a ContinueUpdateRollback retry. Without either, the update changed nothing
* about the VPC.
*/
@Override
public boolean rollbackUpdate(StackResource resource) {
if (ReplacementCleanup.rollback(resource, this::delete)) {
resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR);
return true;
}
undoInPlace(resource);
return true;
}
@Override
public void delete(String resourceType, String physicalId, String region) {
if (physicalId == null || physicalId.isBlank()) {
return;
}
CfnDeletes.safeDelete("VPC", physicalId, () -> ec2Service.deleteVpc(region, physicalId), "InvalidVpcID.NotFound");
}
/**
* Records what the update is about to change on a reused VPC, only when something differs: an
* unchanged reuse leaves no snapshot and rolls back as complete. The tag set comes from
* DescribeTags, the same source {@link Ec2Tags#reconcile} compares against.
*/
private void snapshotInPlace(StackResource r, Vpc vpc, String desiredTenancy, boolean dnsSupport,
boolean dnsHostnames, Map<String, String> desiredTags, String region) {
Map<String, String> currentTags = Ec2Tags.current(ec2Service, region, vpc.getVpcId());
boolean tenancyChanges = isDedicatedToDefault(vpc, desiredTenancy);
boolean changed = tenancyChanges
|| vpc.isEnableDnsSupport() != dnsSupport
|| vpc.isEnableDnsHostnames() != dnsHostnames
|| !currentTags.equals(desiredTags);
if (!changed) {
return;
}
ObjectNode prior = MAPPER.createObjectNode();
prior.put("region", region);
prior.put("vpcId", vpc.getVpcId());
if (tenancyChanges) {
prior.put("instanceTenancy", vpc.getInstanceTenancy());
}
prior.put("enableDnsSupport", vpc.isEnableDnsSupport());
prior.put("enableDnsHostnames", vpc.isEnableDnsHostnames());
ObjectNode tags = prior.putObject("tags");
currentTags.forEach(tags::put);
r.getAttributes().put(IN_PLACE_PRIOR_ATTR, prior.toString());
}
/**
* Puts the DNS attributes and the tag set back, then the tenancy last. The only tenancy change
* applied in place is {@code dedicated} to {@code default}, and EC2 refuses the reverse, so a
* rollback of that change fails on the ModifyVpcTenancy call after everything else is restored
* and the stack reports UPDATE_ROLLBACK_FAILED for the VPC rather than claiming it is back.
*/
private void restoreInPlace(StackResource resource, String snapshot) {
ObjectNode prior;
try {
prior = (ObjectNode) MAPPER.readTree(snapshot);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Unreadable in-place snapshot on " + resource.getLogicalId(), e);
}
String region = prior.path("region").asText();
String vpcId = prior.path("vpcId").asText();
ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsSupport", prior.path("enableDnsSupport").asText());
ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsHostnames", prior.path("enableDnsHostnames").asText());
Map<String, String> priorTags = new LinkedHashMap<>();
prior.path("tags").fields().forEachRemaining(f -> priorTags.put(f.getKey(), f.getValue().asText()));
Ec2Tags.reconcile(ec2Service, region, vpcId, priorTags);
if (prior.hasNonNull("instanceTenancy")) {
ec2Service.modifyVpcTenancy(region, vpcId, prior.get("instanceTenancy").asText());
}
}
/**
* The in-place undo handed to {@link CfnRollback#guarded}: puts a reused VPC back from its
* snapshot. The snapshot is removed only after a successful restore, so a failed one keeps it
* for the rollback walker's retry.
*/
private void undoInPlace(StackResource r) {
String snapshot = r.getAttributes().get(IN_PLACE_PRIOR_ATTR);
if (snapshot != null) {
restoreInPlace(r, snapshot);
r.getAttributes().remove(IN_PLACE_PRIOR_ATTR);
}
}
/**
@@ -142,8 +281,4 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
private static boolean isDedicatedToDefault(Vpc existing, String desiredTenancy) {
return DEDICATED_TENANCY.equals(existing.getInstanceTenancy()) && DEFAULT_TENANCY.equals(desiredTenancy);
}
// No delete override: the switch this replaces had no AWS::EC2::VPC delete arm,
// so stack teardown leaves the VPC alone. Adding one here would change teardown
// behavior beyond the scope of this extraction.
}
@@ -4755,12 +4755,17 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
/**
* DeleteVpc only removes the resources AWS creates with the VPC (default security group, main
* route table, default network ACL). A subnet, or a security group, route table or network ACL the
* caller made, an internet gateway still attached, or a VPC endpoint must be removed first,
* otherwise AWS answers {@code DependencyViolation}.
* caller made, an internet gateway still attached, a VPC endpoint, or an instance or NAT gateway
* still sitting in one of its subnets must be removed first, otherwise AWS answers
* {@code DependencyViolation}.
*/
private void requireNoVpcDependents(String region, String vpcId) {
boolean hasDependents = subnets.scan(k -> k.startsWith(region + "::")).stream()
.anyMatch(subnet -> vpcId.equals(subnet.getVpcId()))
String message = "The vpc '" + vpcId + "' has dependencies and cannot be deleted.";
Set<String> vpcSubnetIds = subnets.scan(k -> k.startsWith(region + "::")).stream()
.filter(subnet -> vpcId.equals(subnet.getVpcId()))
.map(Subnet::getSubnetId)
.collect(Collectors.toSet());
boolean hasDependents = !vpcSubnetIds.isEmpty()
|| securityGroups.scan(k -> k.startsWith(region + "::")).stream()
.anyMatch(group -> vpcId.equals(group.getVpcId())
&& !"default".equals(group.getGroupName()))
@@ -4775,8 +4780,38 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
|| vpcEndpoints.scan(k -> k.startsWith(region + "::")).stream()
.anyMatch(endpoint -> vpcId.equals(endpoint.getVpcId()));
if (hasDependents) {
throw new AwsException("DependencyViolation",
"The vpc '" + vpcId + "' has dependencies and cannot be deleted.", 400);
throw new AwsException("DependencyViolation", message, 400);
}
requireNoSubnetResidents(region, vpcSubnetIds, message);
}
/**
* Anything still holding a network interface in one of the subnets pins the subnet, and through
* it the VPC: an instance, a NAT gateway, a standalone network interface, or an interface or
* Gateway Load Balancer endpoint. A {@code shutting-down} instance still holds its interface and
* a {@code deleting} NAT gateway still holds its address, so only {@code terminated} and
* {@code deleted} release the subnet; a standalone interface is removed from the store on
* delete, so its presence alone counts. AWS answers {@code DependencyViolation} until then.
*/
private void requireNoSubnetResidents(String region, Set<String> subnetIds, String message) {
if (subnetIds.isEmpty()) {
return;
}
String regionPrefix = region + "::";
boolean occupied = instances.scan(k -> k.startsWith(regionPrefix)).stream()
.anyMatch(instance -> subnetIds.contains(instance.getSubnetId())
&& (instance.getState() == null
|| !"terminated".equals(instance.getState().getName())))
|| natGateways.scan(k -> k.startsWith(regionPrefix)).stream()
.anyMatch(natGateway -> subnetIds.contains(natGateway.getSubnetId())
&& !"deleted".equals(natGateway.getState()))
|| networkInterfaces.scan(k -> k.startsWith(regionPrefix)).stream()
.anyMatch(ni -> subnetIds.contains(ni.getSubnetId()))
|| vpcEndpoints.scan(k -> k.startsWith(regionPrefix)).stream()
.anyMatch(endpoint -> !"deleted".equals(endpoint.getState())
&& nullToEmpty(endpoint.getSubnetIds()).stream().anyMatch(subnetIds::contains));
if (occupied) {
throw new AwsException("DependencyViolation", message, 400);
}
}
@@ -5920,6 +5955,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
requireNoTransitGatewayAttachment(region,
attachment -> attachment.getSubnetIds().contains(subnetId),
"The subnet '" + subnetId + "' has dependencies and cannot be deleted.");
requireNoSubnetResidents(region, Set.of(subnetId),
"The subnet '" + subnetId + "' has dependencies and cannot be deleted.");
subnets.delete(key(region, subnetId));
}
if (vpcNetworkManager != null) {