Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): clean up, roll back and delete AWS::EC2::VPC like the other EC2 types (#5503)
danielxoifa682b2d6278
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.mdindex dfbdbac872..e6006163cf 100644--- a/docs/services/cloudformation.md+++ b/docs/services/cloudformation.md@@ -162,7 +162,7 @@ cross-resource references.| ElastiCache | `CacheCluster` (starts a real container; modifying an existing cluster in place is not supported), `SubnetGroup`, `User` (Tags are ignored), `UserGroup` (Tags are ignored), `ServerlessCache` (GetAtt uses the dotted Endpoint.* and ReaderEndpoint.* form) || Redshift | `Cluster` (single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported), `ClusterParameterGroup`, `ClusterSubnetGroup`, `ClusterSecurityGroup` (accepted; no EC2-Classic security group model) || Redshift Serverless | `Namespace` (ManageAdminPassword is accepted and not applied; GetAtt uses the dotted Namespace.* form), `Workgroup` (starts a real container; one workgroup per namespace; capacity, VPC and price-performance settings are stored only; snapshot restore properties are ignored; GetAtt uses the dotted Workgroup.* form) |-| EC2 | `VPC`, `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` |+| EC2 | `VPC` (deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS), `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` || Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` || Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook`, `ScalingPolicy` || Application Auto Scaling | `ScalableTarget` (`ScheduledActions` are accepted and not run; Floci has no scheduled scaling), `ScalingPolicy` |diff --git a/docs/services/ec2.md b/docs/services/ec2.mdindex 2dfbab9fe7..49df196569 100644--- a/docs/services/ec2.md+++ b/docs/services/ec2.md@@ -222,7 +222,7 @@ Floci seeds the following resources on first use in each region so Terraform, th|--------|-------------|| CreateVpc | Creates a VPC with the requested CIDR block. `InstanceTenancy` accepts `default` or `dedicated`; `host` is rejected with `InvalidParameterValue`, as on AWS. || DescribeVpcs | Lists or returns stored VPCs. |-| DeleteVpc | Deletes a VPC from the local EC2 store, together with its default security group and rules, main route table and default network ACL. Fails with `DependencyViolation` while the VPC still has a subnet, a security group, route table or network ACL other than those defaults, a VPC endpoint, or an attached internet gateway. Instances, NAT gateways and other subnet-resident resources are not checked. |+| DeleteVpc | Deletes a VPC from the local EC2 store, together with its default security group and rules, main route table and default network ACL. Fails with `DependencyViolation` while the VPC still has a subnet, a security group, route table or network ACL other than those defaults, a VPC endpoint, an attached internet gateway, a transit gateway attachment, or anything still holding a network interface in one of its subnets: an instance that is not terminated, a NAT gateway that is not deleted, a standalone network interface, or an interface endpoint. || ModifyVpcAttribute | Updates supported VPC attributes. || DescribeVpcAttribute | Returns a supported VPC attribute. || DescribeVpcEndpointServices | Lists common AWS interface endpoint services and S3 (gateway and interface) in every availability zone, named per partition (see [Partitions](../configuration/partitions.md)). A `ServiceName` filter is echoed back as asked. |@@ -247,7 +247,7 @@ gateway lifecycles.|--------|-------------|| CreateSubnet | Creates a subnet in a VPC. || DescribeSubnets | Lists or returns stored subnets. |-| DeleteSubnet | Deletes a subnet from the local EC2 store. |+| DeleteSubnet | Deletes a subnet from the local EC2 store. Fails with `DependencyViolation` while the subnet still has a transit gateway attachment or anything holding a network interface in it: an instance that is not terminated, a NAT gateway that is not deleted, a standalone network interface, or an interface endpoint. || ModifySubnetAttribute | Updates supported subnet attributes. |### Security Groupsdiff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.javaindex 701f7a0e5d..1054ac7818 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java@@ -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;@Injectpublic 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}.+ */@Overridepublic 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;}}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.javaindex 262809b293..57da848c80 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java@@ -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.*/@Overridepublic 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;}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2Tags.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2Tags.javaindex ab45cf38f8..d507778f26 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2Tags.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2Tags.java@@ -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<>();diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.javaindex 782f42293d..a7184e3cfc 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java@@ -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.VpcIpv6CidrBlockAssociationimport 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.*/@ApplicationScopedpublic 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 {@Overridepublic 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.}diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.javaindex 7f087e8b93..8506c5bded 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java@@ -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, ResettabrequireNoTransitGatewayAttachment(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) {diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationVpcReplacementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationVpcReplacementIntegrationTest.javanew file mode 100644index 0000000000..a4bc5af2fb--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationVpcReplacementIntegrationTest.java@@ -0,0 +1,222 @@+package io.github.hectorvent.floci.services.cloudformation;++import io.github.hectorvent.floci.core.common.XmlParser;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.path.xml.XmlPath;+import io.restassured.specification.RequestSpecification;+import org.junit.jupiter.api.Test;++import java.util.Map;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * The lifecycle of {@code AWS::EC2::VPC} beyond its first create: a changed CidrBlock replaces the+ * VPC and the displaced one (with the subnet it held) is removed once the update commits, an+ * in-place tag and DNS change next to a resource that fails the update is rolled back, DeleteStack+ * removes the VPC together with its subnet, and an instance launched into the subnet out of band+ * fails that delete with {@code DependencyViolation} until it is terminated.+ */+@QuarkusTest+class CloudFormationVpcReplacementIntegrationTest {++ private static final String CFN_AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20260205/eu-west-3/cloudformation/aws4_request";+ private static final String EC2_AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20260205/eu-west-3/ec2/aws4_request";++ /** A VPC and a subnet inside it; the subnet's CIDR follows the VPC's second octet. */+ private static String template(String octet, String name) {+ return """+ {+ "Resources": {+ "Vpc": {+ "Type": "AWS::EC2::VPC",+ "Properties": {+ "CidrBlock": "10.%1$s.0.0/16",+ "Tags": [{"Key": "Name", "Value": "%2$s"}]+ }+ },+ "Subnet": {+ "Type": "AWS::EC2::Subnet",+ "Properties": {"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.%1$s.1.0/24"}+ }+ },+ "Outputs": {+ "VpcId": {"Value": {"Ref": "Vpc"}},+ "SubnetId": {"Value": {"Ref": "Subnet"}}+ }+ }+ """.formatted(octet, name);+ }++ /**+ * A VPC alone; the second form flips the mutable properties and adds a resource that cannot be+ * created. Boom depends on the VPC so its failure lands after the in-place change was written.+ */+ private static String rollbackTemplate(boolean changed) {+ String failing = changed+ ? ",\n \"Boom\": {\"Type\": \"AWS::SecretsManager::Secret\", \"DependsOn\": \"Vpc\","+ + " \"Properties\": {\"SecretString\": \"x\", \"GenerateSecretString\": {\"SecretStringTemplate\": \"{}\", \"GenerateStringKey\": \"p\"}}}"+ : "";+ return """+ {+ "Resources": {+ "Vpc": {+ "Type": "AWS::EC2::VPC",+ "Properties": {+ "CidrBlock": "10.47.0.0/16",+ "EnableDnsHostnames": %1$s,+ "Tags": [{"Key": "Name", "Value": "%2$s"}]+ }+ }%3$s+ },+ "Outputs": {"VpcId": {"Value": {"Ref": "Vpc"}}}+ }+ """.formatted(changed ? "false" : "true", changed ? "after" : "before", failing);+ }++ @Test+ void aChangedCidrBlockReplacesTheVpcAndTheDisplacedOneIsRemovedOnceTheUpdateCommits() {+ String stack = "cfn-vpc-replace-" + Long.toString(System.nanoTime(), 36);+ cloudFormation(stack, "CreateStack", template("45", "first"));+ Map<String, String> before = outputs(stack, "CREATE_COMPLETE");++ cloudFormation(stack, "UpdateStack", template("46", "second"));++ Map<String, String> after = outputs(stack, "UPDATE_COMPLETE");+ assertFalse(before.get("VpcId").equals(after.get("VpcId")), "a changed CidrBlock must replace the VPC");+ assertFalse(before.get("SubnetId").equals(after.get("SubnetId")), "the subnet follows its VPC");+ String vpcs = ec2("DescribeVpcs");+ assertFalse(vpcs.contains(before.get("VpcId")), "the displaced VPC must be gone: " + vpcs);+ assertTrue(vpcs.contains(after.get("VpcId")));+ String replacement = ec2("DescribeVpcs", Map.of("VpcId.1", after.get("VpcId")));+ assertTrue(replacement.contains("<cidrBlock>10.46.0.0/16</cidrBlock>"), replacement);+ assertTrue(replacement.contains("<key>Name</key>") && replacement.contains("<value>second</value>"),+ "the replacement carries the stack's tags: " + replacement);+ assertFalse(ec2("DescribeSubnets").contains(before.get("SubnetId")), "the displaced subnet must be gone");++ cloudFormation(stack, "DeleteStack", null);+ CfnStackWaits.awaitStackDeleted(stack, CFN_AUTH);+ assertFalse(ec2("DescribeVpcs").contains(after.get("VpcId")), "stack delete must remove the VPC");+ assertFalse(ec2("DescribeSubnets").contains(after.get("SubnetId")), "stack delete must remove the subnet");+ }++ @Test+ void anInPlaceChangeNextToAFailingResourceIsRolledBack() {+ String stack = "cfn-vpc-rollback-" + Long.toString(System.nanoTime(), 36);+ cloudFormation(stack, "CreateStack", rollbackTemplate(false));+ String vpcId = outputs(stack, "CREATE_COMPLETE").get("VpcId");+ assertTrue(describeVpc(vpcId).contains("<value>before</value>"));+ assertEquals("true", dnsHostnames(vpcId));++ cloudFormation(stack, "UpdateStack", rollbackTemplate(true));++ describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE");+ String vpc = describeVpc(vpcId);+ assertTrue(vpc.contains("<value>before</value>") && !vpc.contains("<value>after</value>"),+ "the VPC's prior tag must be back: " + vpc);+ assertEquals("true", dnsHostnames(vpcId), "the VPC's prior EnableDnsHostnames must be back");++ cloudFormation(stack, "DeleteStack", null);+ CfnStackWaits.awaitStackDeleted(stack, CFN_AUTH);+ assertFalse(ec2("DescribeVpcs").contains(vpcId), "stack delete must remove the VPC");+ }++ @Test+ void anInstanceLaunchedIntoTheSubnetOutOfBandFailsTheDeleteUntilItIsTerminated() {+ String stack = "cfn-vpc-resident-" + Long.toString(System.nanoTime(), 36);+ cloudFormation(stack, "CreateStack", template("48", "resident"));+ Map<String, String> created = outputs(stack, "CREATE_COMPLETE");+ String subnetId = created.get("SubnetId");+ String instanceId = XmlPath.from(ec2("RunInstances", Map.of(+ "ImageId", "ami-1234567890abcdef0", "InstanceType", "t3.micro",+ "MinCount", "1", "MaxCount", "1", "SubnetId", subnetId)))+ .getString("RunInstancesResponse.instancesSet.item.instanceId");++ cloudFormation(stack, "DeleteStack", null);++ CfnStackWaits.StackState failed = CfnStackWaits.awaitTerminal(stack, CFN_AUTH);+ assertEquals("DELETE_FAILED", failed.status(), failed.reason());+ // The event carries the EC2 DependencyViolation message; the engine records the message, not the code.+ String subnetFailure = XmlPath.from(cloudFormationQuery(stack, "DescribeStackEvents"))+ .getString("DescribeStackEventsResponse.DescribeStackEventsResult.StackEvents.member"+ + ".find { it.LogicalResourceId == 'Subnet' && it.ResourceStatus == 'DELETE_FAILED' }"+ + ".ResourceStatusReason");+ assertEquals("The subnet '" + subnetId + "' has dependencies and cannot be deleted.", subnetFailure,+ "the subnet's delete must report the resident instance");+ assertTrue(ec2("DescribeSubnets").contains(subnetId), "the pinned subnet must still exist");+ assertTrue(ec2("DescribeVpcs").contains(created.get("VpcId")), "the VPC behind it must still exist");++ ec2("TerminateInstances", Map.of("InstanceId.1", instanceId));+ cloudFormation(stack, "DeleteStack", null);++ CfnStackWaits.awaitStackDeleted(stack, CFN_AUTH);+ assertFalse(ec2("DescribeSubnets").contains(subnetId), "stack delete must remove the subnet");+ assertFalse(ec2("DescribeVpcs").contains(created.get("VpcId")), "stack delete must remove the VPC");+ }++ private static String describeVpc(String vpcId) {+ return ec2("DescribeVpcs", Map.of("VpcId.1", vpcId));+ }++ private static String dnsHostnames(String vpcId) {+ return XmlPath.from(ec2("DescribeVpcAttribute", Map.of("VpcId", vpcId, "Attribute", "enableDnsHostnames")))+ .getString("DescribeVpcAttributeResponse.enableDnsHostnames.value");+ }++ private static Map<String, String> outputs(String stack, String expectedStatus) {+ return XmlParser.extractPairs(describeStacks(stack, expectedStatus), "Outputs", "OutputKey", "OutputValue");+ }++ private static void cloudFormation(String stack, String action, String templateBody) {+ RequestSpecification request = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", action)+ .formParam("StackName", stack);+ if (templateBody != null) {+ request.formParam("TemplateBody", templateBody);+ }+ request.when().post("/").then().statusCode(200);+ }++ private static String describeStacks(String stack, String expectedStatus) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stack)+ .when().post("/").then().statusCode(200)+ .body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))+ .extract().asString();+ }++ private static String cloudFormationQuery(String stack, String action) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", action)+ .formParam("StackName", stack)+ .when().post("/").then().statusCode(200)+ .extract().asString();+ }++ private static String ec2(String action) {+ return ec2(action, Map.of());+ }++ private static String ec2(String action, Map<String, String> params) {+ RequestSpecification request = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", EC2_AUTH)+ .formParam("Action", action)+ .formParam("Version", "2016-11-15");+ params.forEach(request::formParam);+ return request.when().post("/").then().statusCode(200).extract().asString();+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.javaindex 6fe15689e2..ca25788b21 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java@@ -208,6 +208,50 @@ class Ec2InstanceCfnProvisionerTest {assertEquals("DependencyViolation", failure.getErrorCode());}+ @Test+ void deleteWaitsUntilTheInstanceIsTerminated() {+ provisioner.terminatePollMillis = 1L;+ Instance shuttingDown = new Instance();+ shuttingDown.setInstanceId("i-1");+ shuttingDown.setState(InstanceState.shuttingDown());+ Instance terminated = new Instance();+ terminated.setInstanceId("i-1");+ terminated.setState(InstanceState.terminated());+ when(ec2.describeInstances("us-east-1", List.of("i-1"), null))+ .thenReturn(List.of(reservationOf(shuttingDown)))+ .thenReturn(List.of(reservationOf(shuttingDown)))+ .thenReturn(List.of(reservationOf(terminated)));++ assertDoesNotThrow(() -> provisioner.delete(TYPE, "i-1", "us-east-1"));++ InOrder order = inOrder(ec2);+ order.verify(ec2).terminateInstances("us-east-1", List.of("i-1"));+ order.verify(ec2, times(3)).describeInstances("us-east-1", List.of("i-1"), null);+ }++ @Test+ void deleteTreatsAnInstanceGoneAfterTerminateAsTerminated() {+ when(ec2.describeInstances("us-east-1", List.of("i-1"), null))+ .thenThrow(new AwsException("InvalidInstanceID.NotFound", "gone", 400));++ assertDoesNotThrow(() -> provisioner.delete(TYPE, "i-1", "us-east-1"));+ }++ @Test+ void deleteFailsWhenTheInstanceNeverReachesTerminated() {+ provisioner.terminateTimeoutMillis = 20L;+ provisioner.terminatePollMillis = 1L;+ Instance shuttingDown = new Instance();+ shuttingDown.setInstanceId("i-1");+ shuttingDown.setState(InstanceState.shuttingDown());+ when(ec2.describeInstances("us-east-1", List.of("i-1"), null))+ .thenReturn(List.of(reservationOf(shuttingDown)));++ AwsException failure = assertThrows(AwsException.class,+ () -> provisioner.delete(TYPE, "i-1", "us-east-1"));+ assertTrue(failure.getMessage().contains("Instance i-1 did not reach terminated"), failure.getMessage());+ }+@Testvoid updateWithoutACreateOnlyChangeReusesTheInstance() throws Exception {Instance i1 = new Instance();diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisionerTest.javaindex c788f7a559..9f8783127d 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisionerTest.java@@ -296,6 +296,25 @@ class Ec2NetworkCfnProvisionerTest {assertFalse(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));}+ @Test+ void aRestoreThatThrowsKeepsTheSnapshotForTheRetry() {+ when(ec2.describeSubnets(REGION, List.of(SUBNET_ID), Map.of())).thenReturn(List.of(subnet()));+ StackResource r = prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of("SubnetId", SUBNET_ID, "VpcId", VPC_ID, "AvailabilityZone", "us-east-1a"));+ ObjectNode props = mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24")+ .put("AvailabilityZone", "us-east-1a").put("MapPublicIpOnLaunch", true);+ provisioner.provision(r, props, ctx(SUBNET_ID));+ String snapshot = r.getAttributes().get(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR);+ assertTrue(snapshot != null, "the prior MapPublicIpOnLaunch is snapshotted");+ doThrow(new AwsException("InternalError", "ec2 is down", 500))+ .when(ec2).modifySubnetAttribute(REGION, SUBNET_ID, "mapPublicIpOnLaunch", "false");++ AwsException failure = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));++ assertEquals("InternalError", failure.getErrorCode());+ assertEquals(snapshot, r.getAttributes().get(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR),+ "a failed restore keeps the snapshot for a ContinueUpdateRollback retry");+ }+@Testvoid anUnchangedSubnetWhoseTemplateCidrHasHostBitsIsKept() {Subnet current = subnet();diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisionerTest.javaindex dbd19f7bd4..61b1a4f67f 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisionerTest.java@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;import io.github.hectorvent.floci.services.cloudformation.model.StackResource;import io.github.hectorvent.floci.services.ec2.Ec2Service;@@ -19,14 +20,20 @@ import java.util.Map;import java.util.Set;import java.util.stream.Collectors;+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyBoolean;import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.ArgumentMatchers.argThat;import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;+import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;@@ -89,10 +96,19 @@ class Ec2VpcCfnProvisionerTest {}private StackResource provision(String contextPriorId, String resourcePhysicalId, String json) {+ return provision(contextPriorId, resourcePhysicalId, Map.of(), json);+ }++ private StackResource provision(String priorPhysicalId, Map<String, String> priorAttributes, String json) {+ return provision(priorPhysicalId, priorPhysicalId, priorAttributes, json);+ }++ private StackResource provision(String contextPriorId, String resourcePhysicalId, Map<String, String> priorAttributes, String json) {StackResource r = new StackResource();r.setLogicalId("Vpc");r.setResourceType("AWS::EC2::VPC");r.setPhysicalId(resourcePhysicalId);+ r.getAttributes().putAll(priorAttributes);ProvisionContext ctx =new ProvisionContext(engine, REGION, "000000000000", "my-stack", contextPriorId);provisioner.provision(r, props(json), ctx);@@ -215,7 +231,7 @@ class Ec2VpcCfnProvisionerTest {}@Test- void aChangedCidrBlockCreatesAReplacement() {+ void aChangedCidrBlockCreatesAReplacementAndTheDisplacedVpcIsDeletedOnceTheUpdateCommits() {when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())).thenReturn(List.of(vpc("vpc-existing", "10.0.0.0/16")));stubCreate(vpc("vpc-replaced", "10.1.0.0/16"));@@ -225,6 +241,13 @@ class Ec2VpcCfnProvisionerTest {verify(ec2).createVpc(REGION, "10.1.0.0/16", false, false, "default");assertEquals("vpc-replaced", r.getPhysicalId());+ assertTrue(provisioner.hasReplacementUpdate(r), "the stack enters UPDATE_COMPLETE_CLEANUP_IN_PROGRESS");+ assertEquals("vpc-existing", provisioner.updateCleanupPhysicalId(r));++ assertTrue(provisioner.completeUpdate(r).complete());+ verify(ec2).deleteVpc(REGION, "vpc-existing");+ provisioner.clearUpdate(r);+ assertFalse(provisioner.hasReplacementUpdate(r));}@Test@@ -237,6 +260,7 @@ class Ec2VpcCfnProvisionerTest {{"CidrBlock": "10.0.0.0/16", "InstanceTenancy": "default"}""");assertEquals("vpc-existing", kept.getPhysicalId());verify(ec2).modifyVpcTenancy(REGION, "vpc-existing", "default");+ assertFalse(provisioner.hasReplacementUpdate(kept));// Now a default VPC asked to become dedicated: the only in-place direction is dedicated->default.dedicated.setInstanceTenancy("default");@@ -245,6 +269,187 @@ class Ec2VpcCfnProvisionerTest {{"CidrBlock": "10.0.0.0/16", "InstanceTenancy": "dedicated"}""");assertEquals("vpc-replaced", replaced.getPhysicalId());verify(ec2).createVpc(eq(REGION), eq("10.0.0.0/16"), eq(false), eq(false), eq("dedicated"));+ assertEquals("vpc-existing", provisioner.updateCleanupPhysicalId(replaced), "the displaced VPC is owed a delete");+ }++ @Test+ void aRolledBackReplacementDeletesTheNewVpcAndNamesThePriorOneAgain() {+ when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of()))+ .thenReturn(List.of(vpc("vpc-existing", "10.0.0.0/16")));+ stubCreate(vpc("vpc-replaced", "10.1.0.0/16"));+ StackResource r = provision("vpc-existing", Map.of("VpcId", "vpc-existing", "CidrBlock", "10.0.0.0/16"), """+ {"CidrBlock": "10.1.0.0/16"}""");+ assertEquals("10.1.0.0/16", r.getAttributes().get("CidrBlock"));++ assertTrue(provisioner.rollbackUpdate(r));++ verify(ec2).deleteVpc(REGION, "vpc-replaced");+ verify(ec2, never()).deleteVpc(REGION, "vpc-existing");+ assertEquals("vpc-existing", r.getPhysicalId());+ assertEquals("vpc-existing", r.getAttributes().get("VpcId"));+ assertEquals("10.0.0.0/16", r.getAttributes().get("CidrBlock"), "Fn::GetAtt answers the prior VPC again");+ assertFalse(provisioner.hasReplacementUpdate(r), "nothing is owed a delete once the prior VPC stands again");+ }++ @Test+ void anInPlaceChangeIsRolledBackToThePriorDnsAttributesTagsAndTenancy() {+ Vpc existing = vpc("vpc-existing", "10.0.0.0/16");+ existing.setInstanceTenancy("dedicated");+ existing.setEnableDnsSupport(true);+ existing.setEnableDnsHostnames(false);+ when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())).thenReturn(List.of(existing));+ when(ec2.describeTags(REGION, Map.of("resource-id", List.of("vpc-existing"))))+ .thenReturn(List.of(Map.of("key", "Name", "value", "old"), Map.of("key", "team", "value", "net")))+ // The snapshot reads the prior set once; every later read sees what the update wrote.+ .thenReturn(List.of(Map.of("key", "Name", "value", "new"), Map.of("key", "env", "value", "test")));++ StackResource r = provision("vpc-existing", """+ {"CidrBlock": "10.0.0.0/16", "InstanceTenancy": "default", "EnableDnsHostnames": true,+ "Tags": [{"Key": "Name", "Value": "new"}, {"Key": "env", "Value": "test"}]}""");+ assertTrue(r.getAttributes().containsKey(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR), "the prior state is snapshotted");+ verify(ec2).modifyVpcAttribute(REGION, "vpc-existing", "enableDnsHostnames", "true");+ verify(ec2).createTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("Name=new", "env=test")));++ assertTrue(provisioner.rollbackUpdate(r));++ verify(ec2).modifyVpcAttribute(REGION, "vpc-existing", "enableDnsHostnames", "false");+ verify(ec2, times(2)).modifyVpcAttribute(REGION, "vpc-existing", "enableDnsSupport", "true");+ verify(ec2).deleteTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("env=test")));+ verify(ec2).createTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("Name=old", "team=net")));+ verify(ec2).modifyVpcTenancy(REGION, "vpc-existing", "dedicated");+ assertFalse(r.getAttributes().containsKey(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR));+ }++ @Test+ void aRestoreThatThrowsKeepsTheSnapshotForTheRetry() {+ Vpc existing = vpc("vpc-existing", "10.0.0.0/16");+ existing.setEnableDnsSupport(true);+ existing.setEnableDnsHostnames(false);+ when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())).thenReturn(List.of(existing));+ when(ec2.describeTags(REGION, Map.of("resource-id", List.of("vpc-existing")))).thenReturn(List.of());+ StackResource r = provision("vpc-existing", """+ {"CidrBlock": "10.0.0.0/16", "EnableDnsHostnames": true}""");+ String snapshot = r.getAttributes().get(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR);+ assertTrue(snapshot != null, "the prior state is snapshotted");+ doThrow(new AwsException("InternalError", "ec2 is down", 500))+ .when(ec2).modifyVpcAttribute(REGION, "vpc-existing", "enableDnsHostnames", "false");++ AwsException failure = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));++ assertEquals("InternalError", failure.getErrorCode());+ assertEquals(snapshot, r.getAttributes().get(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR),+ "a failed restore keeps the snapshot for a ContinueUpdateRollback retry");+ }++ @Test+ void anUnchangedReuseLeavesNoSnapshotAndRollsBackAsComplete() {+ Vpc existing = vpc("vpc-existing", "10.0.0.0/16");+ existing.setEnableDnsSupport(true);+ when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())).thenReturn(List.of(existing));+ when(ec2.describeTags(REGION, Map.of("resource-id", List.of("vpc-existing"))))+ .thenReturn(List.of(Map.of("key", "Name", "value", "same")));++ StackResource r = provision("vpc-existing", """+ {"CidrBlock": "10.0.0.0/16", "Tags": [{"Key": "Name", "Value": "same"}]}""");++ assertFalse(r.getAttributes().containsKey(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR));+ assertTrue(provisioner.rollbackUpdate(r));+ verify(ec2, never()).deleteTags(any(), any(), any());+ verify(ec2, never()).modifyVpcTenancy(any(), any(), any());+ verify(ec2, never()).deleteVpc(any(), any());+ }++ @Test+ void completingOrClearingAnUpdateDropsTheSnapshot() {+ StackResource r = new StackResource();+ r.setResourceType("AWS::EC2::VPC");+ r.getAttributes().put(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR, "{}");+ provisioner.completeUpdate(r);+ assertFalse(r.getAttributes().containsKey(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR));+ r.getAttributes().put(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR, "{}");+ provisioner.clearUpdate(r);+ assertFalse(r.getAttributes().containsKey(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR));+ }++ @Test+ void aFailedStepOnAReusedVpcRestoresTheSnapshotBeforeTheFailurePropagates() {+ Vpc existing = vpc("vpc-existing", "10.0.0.0/16");+ existing.setEnableDnsSupport(true);+ when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())).thenReturn(List.of(existing));+ doThrow(new AwsException("TagLimitExceeded", "too many tags", 400)).when(ec2).createTags(any(), any(), any());++ AwsException e = assertThrows(AwsException.class, () -> provision("vpc-existing", """+ {"CidrBlock": "10.0.0.0/16", "EnableDnsHostnames": true, "Tags": [{"Key": "k", "Value": "v"}]}"""));++ assertEquals("TagLimitExceeded", e.getErrorCode());+ verify(ec2).modifyVpcAttribute(REGION, "vpc-existing", "enableDnsHostnames", "false");+ verify(ec2, never()).deleteVpc(any(), any());+ }++ @Test+ void aFailedStepAfterACreateDeletesTheVpcAgain() {+ stubCreate(vpc("vpc-new", "10.0.0.0/16"));+ doThrow(new AwsException("TagLimitExceeded", "too many tags", 400)).when(ec2).createTags(any(), any(), any());++ assertThrows(AwsException.class, () -> provision(null, """+ {"CidrBlock": "10.0.0.0/16", "Tags": [{"Key": "k", "Value": "v"}]}"""));++ verify(ec2).deleteVpc(REGION, "vpc-new");+ }++ @Test+ void aTagResolutionFailureHappensBeforeTheVpcIsCreated() {+ // A missing Fn::ImportValue fails resolution; the VPC must not exist by then, or it would+ // sit outside the rollback guard and leak.+ when(engine.resolveNode(argThat(node -> node != null && node.isArray())))+ .thenThrow(new AwsException("ValidationError", "No export named Shared-Tag found", 400));++ AwsException e = assertThrows(AwsException.class, () -> provision(null, """+ {"CidrBlock": "10.0.0.0/16", "Tags": [{"Key": "k", "Value": {"Fn::ImportValue": "Shared-Tag"}}]}"""));++ assertEquals("ValidationError", e.getErrorCode());+ verify(ec2, never()).createVpc(anyString(), anyString(), anyBoolean(), anyBoolean(), anyString());+ verify(ec2, never()).deleteVpc(any(), any());+ }++ @Test+ void reservedAwsTagsAreNeverSnapshottedNorWrittenBack() {+ Vpc existing = vpc("vpc-existing", "10.0.0.0/16");+ existing.setEnableDnsSupport(true);+ when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())).thenReturn(List.of(existing));+ when(ec2.describeTags(REGION, Map.of("resource-id", List.of("vpc-existing")))).thenReturn(List.of(+ Map.of("key", "aws:cloudformation:stack-name", "value", "my-stack"),+ Map.of("key", "Name", "value", "old")));++ StackResource r = provision("vpc-existing", """+ {"CidrBlock": "10.0.0.0/16", "Tags": [{"Key": "Name", "Value": "new"}]}""");++ String snapshot = r.getAttributes().get(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR);+ assertTrue(snapshot.contains("\"Name\":\"old\""), snapshot);+ assertFalse(snapshot.contains("aws:cloudformation"), snapshot);+ verify(ec2, never()).deleteTags(any(), any(), any());++ assertTrue(provisioner.rollbackUpdate(r));++ verify(ec2).createTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("Name=new")));+ verify(ec2).createTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("Name=old")));+ verify(ec2, never()).createTags(eq(REGION), any(), argThat(actual -> actual != null+ && actual.stream().anyMatch(t -> t.getKey().startsWith("aws:"))));+ verify(ec2, never()).deleteTags(eq(REGION), any(), argThat(actual -> actual != null+ && actual.stream().anyMatch(t -> t.getKey().startsWith("aws:"))));+ }++ @Test+ void deleteToleratesOnlyAVpcThatIsAlreadyGone() {+ doThrow(new AwsException("InvalidVpcID.NotFound", "does not exist", 400)).when(ec2).deleteVpc(REGION, "vpc-gone");+ assertDoesNotThrow(() -> provisioner.delete("AWS::EC2::VPC", "vpc-gone", REGION));++ doThrow(new AwsException("DependencyViolation", "has dependencies", 400)).when(ec2).deleteVpc(REGION, "vpc-busy");+ AwsException e = assertThrows(AwsException.class, () -> provisioner.delete("AWS::EC2::VPC", "vpc-busy", REGION));+ assertEquals("DependencyViolation", e.getErrorCode(), "a VPC with dependents outside the stack fails the delete, as on AWS");++ assertDoesNotThrow(() -> provisioner.delete("AWS::EC2::VPC", null, REGION));+ verify(ec2, times(2)).deleteVpc(any(), any());}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.javaindex e97f7dce99..fed2017657 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ServiceTest.java@@ -23,6 +23,7 @@ import io.github.hectorvent.floci.services.ec2.model.KeyPair;import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;import io.github.hectorvent.floci.services.ec2.model.ManagedPrefixList;+import io.github.hectorvent.floci.services.ec2.model.NatGateway;import io.github.hectorvent.floci.services.ec2.model.NetworkInterface;import io.github.hectorvent.floci.services.ec2.model.NetworkInterfaceAssociation;import io.github.hectorvent.floci.services.ec2.model.NetworkInterfaceListResult;@@ -410,6 +411,123 @@ class Ec2ServiceTest {service.deleteVpc(region, vpcId);}+ @Test+ void deleteSubnetFailsUntilItsInstanceIsTerminated() {+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),+ mock(Ec2PortForwardManager.class),+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),+ new InMemoryStorageFactory());+ String region = "us-east-1";+ String vpcId = service.createVpc(region, "10.81.0.0/16", false).getVpcId();+ String subnetId = service.createSubnet(region, vpcId, "10.81.1.0/24", "us-east-1a").getSubnetId();+ Instance instance = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",+ 1, 1, null, List.of(), subnetId, null, List.of(), null, null).getInstances().getFirst();++ AwsException running = assertThrows(AwsException.class, () -> service.deleteSubnet(region, subnetId));+ assertEquals("DependencyViolation", running.getErrorCode());+ assertEquals("The subnet '" + subnetId + "' has dependencies and cannot be deleted.", running.getMessage());++ // Still holds its network interface while shutting down, so the subnet stays pinned.+ instance.setState(InstanceState.shuttingDown());+ assertEquals("DependencyViolation", assertThrows(AwsException.class,+ () -> service.deleteSubnet(region, subnetId)).getErrorCode());++ instance.setState(InstanceState.terminated());+ service.deleteSubnet(region, subnetId);+ assertTrue(service.describeSubnets(region, List.of(), Map.of()).stream()+ .noneMatch(subnet -> subnetId.equals(subnet.getSubnetId())));+ }++ @Test+ void deleteSubnetFailsUntilItsNatGatewayIsDeleted() {+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),+ mock(Ec2PortForwardManager.class),+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),+ new InMemoryStorageFactory());+ String region = "us-east-1";+ String vpcId = service.createVpc(region, "10.82.0.0/16", false).getVpcId();+ String subnetId = service.createSubnet(region, vpcId, "10.82.1.0/24", "us-east-1a").getSubnetId();+ NatGateway natGateway = service.createNatGateway(region, subnetId, null, "private", List.of());++ assertEquals("DependencyViolation", assertThrows(AwsException.class,+ () -> service.deleteSubnet(region, subnetId)).getErrorCode());++ // Still holds its address while deleting, so the subnet stays pinned.+ natGateway.setState("deleting");+ assertEquals("DependencyViolation", assertThrows(AwsException.class,+ () -> service.deleteSubnet(region, subnetId)).getErrorCode());++ service.deleteNatGateway(region, natGateway.getNatGatewayId());+ service.deleteSubnet(region, subnetId);+ assertTrue(service.describeSubnets(region, List.of(), Map.of()).stream()+ .noneMatch(subnet -> subnetId.equals(subnet.getSubnetId())));+ }++ @Test+ void deleteSubnetFailsUntilItsStandaloneNetworkInterfaceIsDeleted() {+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),+ mock(Ec2PortForwardManager.class),+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),+ new InMemoryStorageFactory());+ String region = "us-east-1";+ String vpcId = service.createVpc(region, "10.83.0.0/16", false).getVpcId();+ String subnetId = service.createSubnet(region, vpcId, "10.83.1.0/24", "us-east-1a").getSubnetId();+ String eniId = service.createNetworkInterface(region, subnetId, null, null, List.of(), List.of(), List.of())+ .getNetworkInterfaceId();++ // An available interface is still an interface in the subnet, so the subnet stays pinned.+ assertEquals("DependencyViolation", assertThrows(AwsException.class,+ () -> service.deleteSubnet(region, subnetId)).getErrorCode());++ service.deleteNetworkInterface(region, eniId);+ service.deleteSubnet(region, subnetId);+ }++ @Test+ void deleteSubnetFailsUntilItsInterfaceEndpointIsDeleted() {+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),+ mock(Ec2PortForwardManager.class),+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),+ new InMemoryStorageFactory());+ String region = "us-east-1";+ String vpcId = service.createVpc(region, "10.84.0.0/16", false).getVpcId();+ String subnetId = service.createSubnet(region, vpcId, "10.84.1.0/24", "us-east-1a").getSubnetId();+ String endpointId = service.createVpcEndpoint(region, vpcId, "com.amazonaws.us-east-1.sqs", "Interface",+ List.of(), List.of(subnetId), List.of(), null, null, List.of()).getVpcEndpointId();++ assertEquals("DependencyViolation", assertThrows(AwsException.class,+ () -> service.deleteSubnet(region, subnetId)).getErrorCode());++ service.deleteVpcEndpoints(region, List.of(endpointId));+ service.deleteSubnet(region, subnetId);+ }++ @Test+ void deleteVpcFailsWhileAnInstanceSitsInOneOfItsSubnets() {+ Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),+ mock(Ec2PortForwardManager.class),+ mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),+ new InMemoryStorageFactory());+ String region = "us-east-1";+ String vpcId = service.createVpc(region, "10.83.0.0/16", false).getVpcId();+ String subnetId = service.createSubnet(region, vpcId, "10.83.1.0/24", "us-east-1a").getSubnetId();+ String instanceId = service.runInstances(region, "ami-1234567890abcdef0", "t3.micro",+ 1, 1, null, List.of(), subnetId, null, List.of(), null, null)+ .getInstances().getFirst().getInstanceId();++ AwsException pinned = assertThrows(AwsException.class, () -> service.deleteVpc(region, vpcId));+ assertEquals("DependencyViolation", pinned.getErrorCode());+ assertEquals("The vpc '" + vpcId + "' has dependencies and cannot be deleted.", pinned.getMessage());+ assertEquals("DependencyViolation", assertThrows(AwsException.class,+ () -> service.deleteSubnet(region, subnetId)).getErrorCode());++ service.terminateInstances(region, List.of(instanceId));+ service.deleteSubnet(region, subnetId);+ service.deleteVpc(region, vpcId);+ assertTrue(service.describeVpcs(region, List.of(), Map.of()).stream()+ .noneMatch(vpc -> vpcId.equals(vpc.getVpcId())));+ }+@Testvoid attachingAnInternetGatewayToAMissingVpcFails() {Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest.javaindex e77bdf4049..71e723f4e3 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest.java@@ -12,6 +12,7 @@ import java.util.List;import static io.restassured.RestAssured.given;import static org.hamcrest.MatcherAssert.assertThat;+import static org.hamcrest.Matchers.equalTo;import static org.hamcrest.Matchers.everyItem;import static org.hamcrest.Matchers.matchesPattern;import static org.junit.jupiter.api.Assertions.assertEquals;@@ -121,16 +122,11 @@ class Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest {}@Test- void theWireIdsAreTheInterfacesFlowLogAttributionReads() {- // THE PROPERTY THE DESIGN RESTS ON, and the one the other tests do not reach.- // They pin count, shape, distinctness and stability -- all of which an- // implementation deriving ids from the subnet id alone would satisfy while- // reporting interfaces that endpointNetworkInterfaces() denies exist. That is- // not hypothetical: an earlier version of endpointNetworkInterfaceIds called- // endpointEniId itself, lacked this method's skip of a vanished subnet, and the- // two were measured reporting different sets after a subnet was deleted out from- // under a live endpoint. Flow-log attribution reads the service side; Terraform- // reads the wire side; they have to be the same list.+ void aSubnetUnderALiveEndpointCannotBeDeletedAndTheWireIdsStayTheServiceIds() {+ // The interface an endpoint holds in a subnet pins that subnet, as on AWS: DeleteSubnet+ // answers DependencyViolation until the endpoint is gone. Flow-log attribution reads+ // the service side and Terraform reads the wire side, so after the refused delete both+ // must still report the same two interfaces, in the same order.String vpcId = createVpc("10.77.0.0/16");String subnetA = createSubnet(vpcId, "10.77.1.0/24", "us-east-1a");String subnetB = createSubnet(vpcId, "10.77.2.0/24", "us-east-1b");@@ -139,15 +135,12 @@ class Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest {"CreateVpcEndpointResponse.vpcEndpoint.vpcEndpointId","VpcId", vpcId, "ServiceName", "com.amazonaws.us-east-1.ec2","VpcEndpointType", "Interface", "SubnetId.1", subnetA, "SubnetId.2", subnetB);+ List<String> before = eniIdsOf(endpointId);- // DELETE A SUBNET OUT FROM UNDER THE LIVE ENDPOINT. Without this the test is- // decorative: both derivations agree whenever every subnet still exists, so a- // version that skipped the vanished-subnet filter passed this assertion happily.- // Measured -- the first draft of this test did exactly that. Real AWS answers- // DependencyViolation here and Terraform's graph destroys the endpoint first, so- // the state is reachable only in an emulator; that is precisely why the emulator- // has to stay self-consistent in it rather than report two different answers.- ec2Value("DeleteSubnet", "DeleteSubnetResponse.return", "SubnetId", subnetB);+ given().formParam("Action", "DeleteSubnet").formParam("SubnetId", subnetB)+ .header("Authorization", AUTH_HEADER)+ .when().post("/").then().statusCode(400)+ .body("Response.Errors.Error.Code", equalTo("DependencyViolation"));List<String> onTheWire = eniIdsOf(endpointId);@@ -160,11 +153,11 @@ class Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest {}}+ assertEquals(before, onTheWire, "a refused delete changes nothing about the endpoint");assertEquals(fromTheService, onTheWire,"the ids DescribeVpcEndpoints publishes must be the interfaces the "+ "service reports, in the same order");- assertEquals(1, onTheWire.size(),- "the endpoint has one surviving subnet, so it reports one interface");+ assertEquals(2, onTheWire.size(), "both subnets survive, so both interfaces are reported");}@Testdiff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yamlindex 7d1aeb959c..9cd4c00316 100644--- a/tools/docs/cfn_resource_types.yaml+++ b/tools/docs/cfn_resource_types.yaml@@ -177,6 +177,7 @@ notes:AWS::Lambda::EventSourceMapping: 'SQS, Kinesis, DynamoDB Streams; `ParallelizationFactor` and `TumblingWindowInSeconds` are ignored'AWS::Lambda::Alias: also what SAM's `AutoPublishAlias` expands intoAWS::Lambda::EventInvokeConfig: also what a SAM function's `EventInvokeConfig` expands into+ AWS::EC2::VPC: 'deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS'AWS::EC2::SecurityGroup: inline `SecurityGroupIngress`/`SecurityGroupEgress` supportedAWS::ApplicationAutoScaling::ScalableTarget: '`ScheduledActions` are accepted and not run; Floci has no scheduled scaling'AWS::RDS::DBInstance: starts a real container