fix(cloudformation): keep unchanged VPCs and security groups on stack update (#3033)

* fix(cloudformation): keep unchanged VPCs and security groups on stack update

provision() re-runs for every resource on every UpdateStack, changed or not.
Ec2VpcCfnProvisioner called createVpc() and provisionSecurityGroup() called
createSecurityGroup() unconditionally, so an untouched VPC or security group was
re-created under a fresh id on every update - silently orphaning every subnet,
route table and group that referenced the old one.

The security group case hid behind the VPC one: because the VPC id changed too,
the (name, vpcId) duplicate check never fired, so the stack still reported
UPDATE_COMPLETE while leaking a second group.

Both now reuse the resource the stack already points at. A changed CidrBlock
(VPC) or a changed GroupName (security group) is still treated as a replacement,
and a resource deleted out of band still falls back to create.

Adds CfnUnchangedResourceUpdateIntegrationTest, which asserts physical-id
retention across an update for VPC, security group, S3 bucket, SQS, SNS, log
group, ECR, KMS alias and Kinesis. Asserting UPDATE_COMPLETE alone is not
enough - a re-created resource passes that while breaking every reference to it.

* fix(cloudformation): reconcile a reused security group's inline rules

Reusing an unchanged security group instead of re-creating it exposed a second
bug in the same arm: authorizeSecurityGroupIngress/Egress append without a
duplicate check, and the inline SecurityGroupIngress/SecurityGroupEgress loops
run on every provision pass. A reused group therefore accumulated another copy
of every inline rule on each UpdateStack. Re-creating the group had masked
this, since each update authorized onto a brand new group.

Clear the rule sets the template declares before re-authorizing, which also
drops rules the template no longer lists. A set the template does not declare is
left alone, so a group keeps its default egress.

Also narrows reuse: GroupName, GroupDescription and VpcId are immutable on a
security group, so a template that changes one wants a new group rather than an
edit to this one. Only the GroupName check was exercised before.

Adds securityGroupInlineRulesAreNotDuplicatedByAnUpdate, which asserts the
group still describes each inline rule exactly once after an update. Verified
non-vacuous: without the revoke it fails with the rule present twice.

* test(cloudformation): focused provisioner coverage for AWS::EC2::VPC

Mirrors S3CfnProvisionerTest: mocks only Ec2Service and pins the create path's
Fn::GetAtt keys (VpcId, CidrBlock, DefaultSecurityGroup) alongside the three
update outcomes - reuse when nothing changed, replacement on a changed
CidrBlock, and a fresh create when the VPC is gone from the backend.

The integration test asserts physical-id retention end to end but cannot show
which service call was made; this pins that createVpc is not called at all on
an unchanged update.

* fix(cloudformation): authorize only the inline rules a group is missing

Clearing the declared rule sets before re-authorizing fixed the duplication but
introduced a worse defect: a group can also carry rules from standalone
AWS::EC2::SecurityGroupIngress/Egress resources, and the revoke took those with
it, so an unrelated stack update silently closed ports another resource owns. A
rule rejected mid-authorize also left the prior set already deleted, with
nothing to restore it.

Reconciliation is now additive. Each declared rule is authorized only when the
group does not already carry it, compared on a canonical key since IpPermission
and its range types define no equals. Nothing is revoked, so neither failure
mode is reachable.

The trade-off is explicit: a rule dropped from the template is no longer
revoked. Doing that safely needs the provisioner to record which rules it
authorized, which this arm cannot do while it lives in the legacy monolith.

Also compares the VpcId a template would actually resolve to rather than the
raw property. createSecurityGroup resolves an omitted VpcId to the region's
default VPC, so the stored group always has one - comparing against a null
property let a template that drops VpcId keep a group in the VPC it had named.

Adds anUpdateLeavesRulesOwnedByStandaloneResourcesAlone. Verified non-vacuous:
restoring the revoke fails it with the standalone rule gone.

* fix(cloudformation): branch AWS::EC2::VPC on the context's prior id

provision() serves create and update, and assigns the new physical id onto the
resource as it runs, so deciding create-vs-update by reading that id back flips
mid-method. AGENTS.md step 4 asks for ctx.isUpdate()/ctx.priorPhysicalId()
instead, and the Scheduler provisioner shed the same pattern in #2985.

The two agree on today's call path, since the engine seeds both from the same
existing id, so this is the convention rather than a live defect. The test was
the part that had it wrong: it built a create-path context and set the prior id
only on the resource, so it passed either way.

Pinned by anIdOnTheResourceAloneDoesNotCountAsAnUpdate, which provisions a
resource carrying an id under a create context and fails when the VPC is looked
up for reuse instead of created.

* fix(cloudformation): match a security group rule that names its peer

A rule naming its peer through SourceSecurityGroupName was re-authorized on
every update. Ec2Service.resolveGroupReferences fills in groupId on the pair as
it records the rule, the declaration toIpPermission hands back on the next pass
carries only the name, and the duplicate key preferred the id whenever one was
present, so the two forms never matched and the group accumulated another copy
of the rule each time.

Both sides now resolve a bare name to its group id before keying, the same
lookup the service performs, confined to the group's own VPC because names are
unique per VPC. A name matching nothing there stays a name, which is also what
the service does, so an unresolvable peer still compares equal to itself.

Pinned by aRuleNamingItsPeerByNameIsNotDuplicatedByAnUpdate, which reports the
rule twice when the resolution is dropped. Its DependsOn is load-bearing: the
peer has to exist when the rule is first authorized, or the stored pair keeps
the unresolved name and both sides agree for the wrong reason.

Also moves a doc comment back onto the test it describes.

* test(cloudformation): parse the describe body with XmlParser

The physical-id helper pulled LogicalResourceId/PhysicalResourceId pairs out of
the DescribeStackResources response with a regex, which the repo rules forbid
for XML. extractGroups on "member" gives the same pairs as a map per resource,
so the member is picked by its logical id rather than by matching across tags.
This commit is contained in:
Jerald Lindberg authored and GitHub committed 2026-09-09 18:12:47 -05:00
1 parent cf1aabce39
commit dde11aeb6a
4 files changed
+691 -10

No files matched your search

@@ -0,0 +1,351 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* UpdateStack must leave an unchanged resource alone, whatever its type.
*
* <p>{@code provision()} re-runs for every resource on every update, changed or not, so a
* provisioner that calls create unconditionally either collides with itself (rolling the stack
* back) or quietly mints a new physical id, orphaning everything that referenced the old one.
* Each case here builds a stack holding one resource plus a throwaway queue, updates only the
* queue, and asserts both that the stack reached UPDATE_COMPLETE and that the untouched resource
* kept its physical id.
*
* <p>Regression cover for "CloudFormation update recreates unchanged named resources"
* (floci-io/floci#2134).
*/
@QuarkusTest
class CfnUnchangedResourceUpdateIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260808/us-west-2/cloudformation/aws4_request";
private static String stackWith(String namedResourceJson, String queueName) {
return """
{
"Resources": {
%s,
"ChurnQueue": {
"Type": "AWS::SQS::Queue",
"Properties": {"QueueName": "%s"}
}
}
}
""".formatted(namedResourceJson, queueName);
}
/**
* Pulls the PhysicalResourceId of one logical resource out of a DescribeStackResources body.
* The member ordering is not guaranteed, so pick the member by its LogicalResourceId rather
* than by position.
*/
private static String physicalIdOf(String describeBody, String logicalId) {
return XmlParser.extractGroups(describeBody, "member").stream()
.filter(member -> logicalId.equals(member.get("LogicalResourceId")))
.map(member -> member.get("PhysicalResourceId"))
.findFirst()
.orElse(null);
}
private String namedPhysicalId(String stackName) {
String body = given()
.contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackResources").formParam("StackName", stackName)
.when().post("/").then().statusCode(200)
.extract().body().asString();
return physicalIdOf(body, "Named");
}
/**
* Creates the stack, updates it with only the churn queue renamed, then asserts both that the
* update completed and that the untouched resource kept its physical id. The second assertion
* is the load-bearing one: a provisioner that re-creates the resource under a fresh id can
* still report UPDATE_COMPLETE while silently orphaning whatever referenced the old id.
*/
private void assertUnchangedResourceSurvivesUpdate(String label, String namedResourceJson) {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "probe-" + label + "-" + suffix;
String body = namedResourceJson.replace("SUFFIX", suffix);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", stackWith(body, "probe-q-a-" + suffix))
.when().post("/").then().statusCode(200);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks").formParam("StackName", stackName)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
String before = namedPhysicalId(stackName);
assertNotNull(before, "no PhysicalResourceId for Named after create");
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack").formParam("StackName", stackName)
.formParam("TemplateBody", stackWith(body, "probe-q-b-" + suffix))
.when().post("/").then().statusCode(200);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks").formParam("StackName", stackName)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
.body(not(containsString("ROLLBACK")));
assertEquals(before, namedPhysicalId(stackName),
label + ": unchanged resource was re-created under a new physical id");
}
private static final String EC2_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260808/us-west-2/ec2/aws4_request";
/** Runs create-then-update and hands back the Named physical id before and after. */
private String[] createThenUpdate(String label, String createBody, String updateBody) {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "probe-" + label + "-" + suffix;
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", stackWith(createBody.replace("SUFFIX", suffix), "probe-q-a-" + suffix))
.when().post("/").then().statusCode(200);
String before = namedPhysicalId(stackName);
assertNotNull(before, "no PhysicalResourceId for Named after create");
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack").formParam("StackName", stackName)
.formParam("TemplateBody", stackWith(updateBody.replace("SUFFIX", suffix), "probe-q-b-" + suffix))
.when().post("/").then().statusCode(200);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks").formParam("StackName", stackName)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
.body(not(containsString("ROLLBACK")));
return new String[] {before, namedPhysicalId(stackName)};
}
private static final String SG_WITH_INGRESS = """
"Named": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupName": "probe-sg-SUFFIX",
"GroupDescription": "probe DESCRIPTION",
"SecurityGroupIngress": [
{"IpProtocol": "tcp", "FromPort": 22, "ToPort": 22, "CidrIp": "10.0.0.0/8"}
]
}
}""";
/**
* A group can carry rules from standalone AWS::EC2::SecurityGroupIngress resources as well as
* its own inline ones. Reconciling the inline set by clearing the group first would revoke
* those too, so a stack update unrelated to them would silently close their ports.
*/
@Test
void anUpdateLeavesRulesOwnedByStandaloneResourcesAlone() {
String body = """
"Named": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupName": "probe-sg-mixed-SUFFIX",
"GroupDescription": "probe mixed",
"SecurityGroupIngress": [
{"IpProtocol": "tcp", "FromPort": 22, "ToPort": 22, "CidrIp": "10.0.0.0/8"}
]
}
},
"ExtraRule": {
"Type": "AWS::EC2::SecurityGroupIngress",
"Properties": {
"GroupId": {"Ref": "Named"},
"IpProtocol": "tcp",
"FromPort": 8080,
"ToPort": 8080,
"CidrIp": "10.9.0.0/16"
}
}""";
String[] ids = createThenUpdate("sg-mixed", body, body);
assertEquals(ids[0], ids[1], "unchanged security group was re-created under a new physical id");
String described = given()
.contentType("application/x-www-form-urlencoded").header("Authorization", EC2_AUTH)
.formParam("Action", "DescribeSecurityGroups").formParam("GroupId.1", ids[1])
.when().post("/").then().statusCode(200)
.extract().body().asString();
assertEquals(1, described.split("<fromPort>22</fromPort>", -1).length - 1,
"inline rule should appear exactly once after an update");
assertEquals(1, described.split("<fromPort>8080</fromPort>", -1).length - 1,
"the standalone resource's rule was revoked by the inline reconciliation");
}
/**
* AuthorizeSecurityGroupIngress appends without a duplicate check, so re-running provision on a
* reused group stacks another copy of every inline rule on each update. Retaining the group id
* is not enough on its own: the group has to still describe the rules the template declares,
* once each.
*/
@Test
void securityGroupInlineRulesAreNotDuplicatedByAnUpdate() {
String body = SG_WITH_INGRESS.replace("DESCRIPTION", "stable");
String[] ids = createThenUpdate("sg-rules", body, body);
assertEquals(ids[0], ids[1], "unchanged security group was re-created under a new physical id");
String described = given()
.contentType("application/x-www-form-urlencoded").header("Authorization", EC2_AUTH)
.formParam("Action", "DescribeSecurityGroups").formParam("GroupId.1", ids[1])
.when().post("/").then().statusCode(200)
.extract().body().asString();
int occurrences = described.split("<fromPort>22</fromPort>", -1).length - 1;
assertEquals(1, occurrences,
"inline ingress rule appears " + occurrences + " times after one update; "
+ "provision re-authorized it on the reused group");
}
/**
* A rule naming its peer through SourceSecurityGroupName is the case the CidrIp rules above
* cannot reach. Ec2Service resolves the name to a group id as it records the rule, while the
* declaration the template hands back on the next update still carries only the name, so
* comparing the two forms directly finds no match and re-authorizes the rule every time.
*
* <p>DependsOn is load-bearing: the peer has to exist when the rule is first authorized, or
* the stored pair keeps the unresolved name and both sides agree for the wrong reason.
*/
@Test
void aRuleNamingItsPeerByNameIsNotDuplicatedByAnUpdate() {
String body = """
"Peer": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupName": "probe-sg-peer-SUFFIX",
"GroupDescription": "probe peer"
}
},
"Named": {
"Type": "AWS::EC2::SecurityGroup",
"DependsOn": "Peer",
"Properties": {
"GroupName": "probe-sg-byname-SUFFIX",
"GroupDescription": "probe by name",
"SecurityGroupIngress": [
{"IpProtocol": "tcp", "FromPort": 5432, "ToPort": 5432,
"SourceSecurityGroupName": "probe-sg-peer-SUFFIX"}
]
}
}""";
String[] ids = createThenUpdate("sg-byname", body, body);
assertEquals(ids[0], ids[1], "unchanged security group was re-created under a new physical id");
String described = given()
.contentType("application/x-www-form-urlencoded").header("Authorization", EC2_AUTH)
.formParam("Action", "DescribeSecurityGroups").formParam("GroupId.1", ids[1])
.when().post("/").then().statusCode(200)
.extract().body().asString();
int occurrences = described.split("<fromPort>5432</fromPort>", -1).length - 1;
assertEquals(1, occurrences,
"name-based ingress rule appears " + occurrences + " times after one update; "
+ "the stored peer is keyed by id and the declared one by name");
}
@Test
void logGroup() {
assertUnchangedResourceSurvivesUpdate("loggroup", """
"Named": {
"Type": "AWS::Logs::LogGroup",
"Properties": {"LogGroupName": "/probe/log-SUFFIX"}
}""");
}
@Test
void snsTopic() {
assertUnchangedResourceSurvivesUpdate("sns", """
"Named": {
"Type": "AWS::SNS::Topic",
"Properties": {"TopicName": "probe-topic-SUFFIX"}
}""");
}
@Test
void sqsQueue() {
assertUnchangedResourceSurvivesUpdate("sqs", """
"Named": {
"Type": "AWS::SQS::Queue",
"Properties": {"QueueName": "probe-queue-SUFFIX"}
}""");
}
@Test
void ecrRepository() {
assertUnchangedResourceSurvivesUpdate("ecr", """
"Named": {
"Type": "AWS::ECR::Repository",
"Properties": {"RepositoryName": "probe-repo-SUFFIX"}
}""");
}
@Test
void kmsAlias() {
assertUnchangedResourceSurvivesUpdate("kms", """
"Key": {"Type": "AWS::KMS::Key", "Properties": {}},
"Named": {
"Type": "AWS::KMS::Alias",
"Properties": {"AliasName": "alias/probe-SUFFIX", "TargetKeyId": {"Ref": "Key"}}
}""");
}
@Test
void kinesisStream() {
assertUnchangedResourceSurvivesUpdate("kinesis", """
"Named": {
"Type": "AWS::Kinesis::Stream",
"Properties": {"Name": "probe-stream-SUFFIX", "ShardCount": 1}
}""");
}
@Test
void securityGroup() {
assertUnchangedResourceSurvivesUpdate("sg", """
"Vpc": {
"Type": "AWS::EC2::VPC",
"Properties": {"CidrBlock": "10.99.0.0/16"}
},
"Named": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"GroupName": "probe-sg-SUFFIX",
"GroupDescription": "probe",
"VpcId": {"Ref": "Vpc"}
}
}""");
}
@Test
void vpc() {
assertUnchangedResourceSurvivesUpdate("vpc", """
"Named": {
"Type": "AWS::EC2::VPC",
"Properties": {"CidrBlock": "10.98.0.0/16"}
}""");
}
@Test
void s3Bucket() {
assertUnchangedResourceSurvivesUpdate("s3", """
"Named": {
"Type": "AWS::S3::Bucket",
"Properties": {"BucketName": "probe-bucket-SUFFIX"}
}""");
}
}
@@ -0,0 +1,155 @@
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;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
import io.github.hectorvent.floci.services.ec2.model.Vpc;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** {@code AWS::EC2::VPC}. */
class Ec2VpcCfnProvisionerTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String REGION = "us-east-1";
private Ec2Service ec2;
private Ec2VpcCfnProvisioner provisioner;
private CloudFormationTemplateEngine engine;
@BeforeEach
void setUp() {
ec2 = mock(Ec2Service.class);
provisioner = new Ec2VpcCfnProvisioner(ec2);
engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(i -> {
JsonNode node = i.getArgument(0);
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(i -> i.getArgument(0));
when(ec2.describeSecurityGroups(anyString(), any(), any(), any())).thenReturn(List.of());
}
private static JsonNode props(String json) {
try {
return MAPPER.readTree(json);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
private static Vpc vpc(String id, String cidr) {
Vpc v = new Vpc();
v.setVpcId(id);
v.setCidrBlock(cidr);
return v;
}
/**
* Provisions the way the engine does: an update arrives with the prior id on both the context
* and the resource, so a provisioner reading the wrong one still looks correct here. The
* create-path cases below are what separate them.
*/
private StackResource provision(String priorPhysicalId, String json) {
return provision(priorPhysicalId, priorPhysicalId, json);
}
private StackResource provision(String contextPriorId, String resourcePhysicalId, String json) {
StackResource r = new StackResource();
r.setLogicalId("Vpc");
r.setResourceType("AWS::EC2::VPC");
r.setPhysicalId(resourcePhysicalId);
ProvisionContext ctx =
new ProvisionContext(engine, REGION, "000000000000", "my-stack", contextPriorId);
provisioner.provision(r, props(json), ctx);
return r;
}
@Test
void refIsTheVpcIdAndGetAttExposesTheDocumentedAttributes() {
when(ec2.createVpc(anyString(), anyString(), anyBoolean())).thenReturn(vpc("vpc-new", "10.0.0.0/16"));
SecurityGroup def = new SecurityGroup();
def.setGroupId("sg-default");
def.setVpcId("vpc-new");
when(ec2.describeSecurityGroups(REGION, List.of(), List.of("default"), Map.of()))
.thenReturn(List.of(def));
StackResource r = provision(null, """
{"CidrBlock": "10.0.0.0/16"}""");
assertEquals("vpc-new", r.getPhysicalId());
assertEquals("vpc-new", r.getAttributes().get("VpcId"));
assertEquals("10.0.0.0/16", r.getAttributes().get("CidrBlock"));
assertEquals("sg-default", r.getAttributes().get("DefaultSecurityGroup"));
}
@Test
void anUnchangedVpcIsReusedInsteadOfCreatedAgain() {
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of()))
.thenReturn(List.of(vpc("vpc-existing", "10.0.0.0/16")));
StackResource r = provision("vpc-existing", """
{"CidrBlock": "10.0.0.0/16"}""");
verify(ec2, never()).createVpc(anyString(), anyString(), anyBoolean());
assertEquals("vpc-existing", r.getPhysicalId(),
"reusing must keep the id every subnet and route table already references");
}
@Test
void aChangedCidrBlockCreatesAReplacement() {
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of()))
.thenReturn(List.of(vpc("vpc-existing", "10.0.0.0/16")));
when(ec2.createVpc(anyString(), anyString(), anyBoolean())).thenReturn(vpc("vpc-replaced", "10.1.0.0/16"));
StackResource r = provision("vpc-existing", """
{"CidrBlock": "10.1.0.0/16"}""");
verify(ec2).createVpc(REGION, "10.1.0.0/16", false);
assertEquals("vpc-replaced", r.getPhysicalId());
}
@Test
void anIdOnTheResourceAloneDoesNotCountAsAnUpdate() {
when(ec2.createVpc(anyString(), anyString(), anyBoolean())).thenReturn(vpc("vpc-new", "10.0.0.0/16"));
// A resource carrying a physical id under a create context: what provision() itself
// produces the moment it assigns the new id. Reading create-vs-update off the resource
// makes that state indistinguishable from a real update.
StackResource r = provision(null, "vpc-assigned-mid-method", """
{"CidrBlock": "10.0.0.0/16"}""");
verify(ec2, never()).describeVpcs(anyString(), any(), any());
verify(ec2).createVpc(REGION, "10.0.0.0/16", false);
assertEquals("vpc-new", r.getPhysicalId());
}
@Test
void aVpcDeletedOutOfBandFallsBackToCreate() {
when(ec2.describeVpcs(REGION, List.of("vpc-gone"), Map.of()))
.thenThrow(new AwsException("InvalidVpcID.NotFound", "not found", 400));
when(ec2.createVpc(anyString(), anyString(), anyBoolean())).thenReturn(vpc("vpc-fresh", "10.0.0.0/16"));
StackResource r = provision("vpc-gone", """
{"CidrBlock": "10.0.0.0/16"}""");
verify(ec2).createVpc(REGION, "10.0.0.0/16", false);
assertEquals("vpc-fresh", r.getPhysicalId());
}
}