fix(cloudformation): move a kept load balancer onto the template's subnets (#5881)

* fix(cloudformation): move a kept load balancer onto the template's subnets

An update that changed an ELBv2 load balancer's Subnets (or SubnetMappings)
kept the balancer on its old subnets, so it went on listing subnets the
template had dropped or replaced, which the update cleanup then deleted.
The provisioner now moves a kept balancer onto the template's subnets, as
SetSubnets does, and keeps the prior list in a hidden attribute so a
rolled-back update moves it back. A failed move back is reported as the
rollback failure and keeps the prior list for another try. SubnetMappings
gives the subnets when Subnets is absent.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): refuse a load balancer subnet mapping without a subnet

SubnetId is required in an ELBv2 SubnetMapping, but the provisioner
skipped a mapping without one, or with a blank one, so a template whose
mappings named no subnet created or kept a load balancer with no subnets.
A mapping without SubnetId now fails the resource with the schema error
before anything is created or moved, and a blank SubnetId is passed on
for ELBv2 to refuse as an unknown subnet.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): leave out a subnet mapping an Fn::If drops

SubnetMappings was resolved with AWS::NoValue kept as an empty value, so
a mapping an Fn::If dropped read as a mapping without SubnetId and the
new required-key check failed the stack, and a SubnetId an Fn::If dropped
failed as an unknown blank subnet. SubnetMappings is now resolved with
those values left out, as CloudFormation does: a dropped mapping is
skipped and a dropped SubnetId is reported as the missing required key.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(cloudformation): read stack event reasons decoded

The subnet mapping test matched the raw DescribeStackEvents body, where
ResourceStatusReason is XML-escaped, so the blank SubnetId reason with
its quotes never matched. It now reads the reasons with XmlParser.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): refuse a load balancer with subnets and subnet mappings

With both Subnets and SubnetMappings set the provisioner quietly took
Subnets, where the resource allows one or the other and CreateLoadBalancer
refuses both. Both together now fail the resource with the same
ValidationError before anything is created or moved, and the mappings are
checked for a SubnetId even when Subnets is set.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(cloudformation): pin an empty subnet mapping list beside subnets

An empty SubnetMappings beside Subnets, as an Fn::If that drops every
mapping leaves, is allowed; a test now holds that. The templateSubnets
Javadoc says how a blank SubnetId counts, and the integration test class
says it also covers both properties together.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

---------

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-18 21:07:26 -04:00
1 parent d273d4f4e0
commit 94288dadd9
4 files changed
+488 -8

No files matched your search

@@ -0,0 +1,145 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.LinkedHashMap;
import java.util.List;
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.assertTrue;
/**
* {@code SubnetId} is required in a load balancer's {@code SubnetMappings}. A mapping that names no
* subnet fails its stack, as on AWS, rather than the balancer being created with no subnets, while a
* mapping an {@code Fn::If} drops with {@code AWS::NoValue} is left out. {@code Subnets} and
* {@code SubnetMappings} together fail it too, as ELBv2 takes one or the other.
*/
@QuarkusTest
class CloudFormationElbV2SubnetMappingsIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261018/us-east-1/cloudformation/aws4_request";
private static final String ELB_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261018/us-east-1/elasticloadbalancing/aws4_request";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
/**
* A mapping with no {@code SubnetId}, one whose {@code SubnetId} an {@code Fn::If} drops, and one
* whose {@code SubnetId} is blank, each with the reason the resource fails with.
*/
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"{\"AllocationId\": \"eipalloc-12345678\"}|required key [SubnetId] not found",
"{\"SubnetId\": {\"Fn::If\": [\"Never\", {\"Ref\": \"SubnetA\"}, {\"Ref\": \"AWS::NoValue\"}]}}|required key [SubnetId] not found",
"{\"SubnetId\": \"\"}|The subnet ID '' does not exist"
})
void aSubnetMappingThatNamesNoSubnetFailsTheStackWithoutALoadBalancer(String mapping, String reason) {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "nlb-mappings-" + suffix;
String name = "nlb-" + suffix;
try {
request(CFN_AUTH, "CreateStack", "StackName", stack, "TemplateBody", template(name, mapping))
.statusCode(200);
CfnStackWaits.awaitStatus(stack, "ROLLBACK_COMPLETE");
String events = request(CFN_AUTH, "DescribeStackEvents", "StackName", stack).statusCode(200)
.extract().asString();
List<String> reasons = XmlParser.extractAll(events, "ResourceStatusReason");
assertTrue(reasons.stream().anyMatch(r -> r.contains(reason)), String.join(" | ", reasons));
request(ELB_AUTH, "DescribeLoadBalancers", "Names.member.1", name).statusCode(400)
.body(containsString("LoadBalancerNotFound"));
} finally {
request(CFN_AUTH, "DeleteStack", "StackName", stack);
}
}
/** {@code Subnets} and {@code SubnetMappings} together fail the stack, as ELBv2 refuses both. */
@Test
void subnetsAndSubnetMappingsTogetherFailTheStack() {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "nlb-both-" + suffix;
String name = "nlb-both-" + suffix;
String template = template(name, "{\"SubnetId\": {\"Ref\": \"SubnetA\"}}")
.replace("\"SubnetMappings\":", "\"Subnets\": [{\"Ref\": \"SubnetB\"}], \"SubnetMappings\":");
try {
request(CFN_AUTH, "CreateStack", "StackName", stack, "TemplateBody", template).statusCode(200);
CfnStackWaits.awaitStatus(stack, "ROLLBACK_COMPLETE");
String events = request(CFN_AUTH, "DescribeStackEvents", "StackName", stack).statusCode(200)
.extract().asString();
List<String> reasons = XmlParser.extractAll(events, "ResourceStatusReason");
assertTrue(reasons.stream().anyMatch(r -> r.contains("either subnets or subnet mappings, not both")),
String.join(" | ", reasons));
request(ELB_AUTH, "DescribeLoadBalancers", "Names.member.1", name).statusCode(400)
.body(containsString("LoadBalancerNotFound"));
} finally {
request(CFN_AUTH, "DeleteStack", "StackName", stack);
}
}
/** A second mapping an {@code Fn::If} drops leaves the balancer on the first mapping's subnet. */
@Test
void aMappingAnFnIfDropsIsLeftOut() {
String suffix = Long.toString(System.nanoTime(), 36);
String stack = "nlb-mappings-if-" + suffix;
String name = "nlb-if-" + suffix;
String mappings = "{\"SubnetId\": {\"Ref\": \"SubnetA\"}}, "
+ "{\"Fn::If\": [\"Never\", {\"SubnetId\": {\"Ref\": \"SubnetB\"}}, {\"Ref\": \"AWS::NoValue\"}]}";
try {
request(CFN_AUTH, "CreateStack", "StackName", stack, "TemplateBody", template(name, mappings))
.statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE");
String outputs = request(CFN_AUTH, "DescribeStacks", "StackName", stack).statusCode(200)
.extract().asString();
String subnetA = XmlParser.extractPairs(outputs, "member", "OutputKey", "OutputValue").get("SubnetA");
String described = request(ELB_AUTH, "DescribeLoadBalancers", "Names.member.1", name).statusCode(200)
.extract().asString();
assertEquals(List.of(subnetA), XmlParser.extractAll(described, "SubnetId"));
} finally {
request(CFN_AUTH, "DeleteStack", "StackName", stack);
}
}
/** A VPC with two subnets and a network load balancer with the given mappings. */
private static String template(String name, String mappings) {
return """
{
"Conditions": {"Never": {"Fn::Equals": ["a", "b"]}},
"Resources": {
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.97.0.0/16"}},
"SubnetA": {"Type": "AWS::EC2::Subnet", "Properties": {"VpcId": {"Ref": "Vpc"},
"CidrBlock": "10.97.1.0/24", "AvailabilityZone": "us-east-1a"}},
"SubnetB": {"Type": "AWS::EC2::Subnet", "Properties": {"VpcId": {"Ref": "Vpc"},
"CidrBlock": "10.97.2.0/24", "AvailabilityZone": "us-east-1b"}},
"Nlb": {
"Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
"Properties": {"Name": "%s", "Type": "network", "Scheme": "internal", "SubnetMappings": [%s]}
}
},
"Outputs": {"SubnetA": {"Value": {"Ref": "SubnetA"}}}
}
""".formatted(name, mappings);
}
private static ValidatableResponse request(String auth, String action, String... values) {
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("Action", action);
for (int i = 0; i < values.length; i += 2) {
parameters.put(values[i], values[i + 1]);
}
return given().contentType("application/x-www-form-urlencoded").header("Authorization", auth)
.formParams(parameters).when().post("/").then().log().ifValidationFails();
}
}
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplate
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
import io.github.hectorvent.floci.services.elbv2.model.Action;
import io.github.hectorvent.floci.services.elbv2.model.AvailabilityZone;
import io.github.hectorvent.floci.services.elbv2.model.Listener;
import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer;
import io.github.hectorvent.floci.services.elbv2.model.Rule;
@@ -40,6 +41,7 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
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;
@@ -73,6 +75,7 @@ class ElbV2CfnProvisionerTest {
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(inv -> inv.getArgument(0));
// resolveStringList delegates to the real engine method; for the literal arrays these
// tests use it just walks the array and calls resolve(...) per element, stubbed above.
when(engine.resolveStringList(any())).thenCallRealMethod();
@@ -405,13 +408,259 @@ class ElbV2CfnProvisionerTest {
lb.getAttributes().put("LoadBalancerName", "web");
provisioner.provision(lb, mapper.createObjectNode().put("Name", "web"), ctx(LB_ARN));
// Every property is create-only and the update only described the existing balancer, so a
// rollback is complete with nothing to do; the engine must not report it as unimplemented.
// The update declared no subnets, so it only described the existing balancer and a rollback
// is complete with nothing to do; the engine must not report it as unimplemented.
assertTrue(provisioner.rollbackUpdate(lb));
assertEquals(LB_ARN, lb.getPhysicalId());
verify(elb, never()).deleteLoadBalancer(anyString(), anyString());
}
private LoadBalancer loadBalancerOn(String name, String... subnetIds) {
LoadBalancer lb = loadBalancer(name);
for (String subnetId : subnetIds) {
AvailabilityZone zone = new AvailabilityZone();
zone.setSubnetId(subnetId);
lb.getAvailabilityZones().add(zone);
}
return lb;
}
private StackResource keptLoadBalancerUpdatedTo(LoadBalancer existing, String... subnets) {
when(elb.createLoadBalancer(eq(REGION), eq("web"), isNull(), isNull(), isNull(), anyList(), anyList(), any()))
.thenThrow(new AwsException("DuplicateLoadBalancerName", "exists", 400));
when(elb.describeLoadBalancers(REGION, null, List.of("web"), null, null)).thenReturn(List.of(existing));
ObjectNode props = mapper.createObjectNode().put("Name", "web");
ArrayNode subnetList = props.putArray("Subnets");
for (String subnet : subnets) {
subnetList.add(subnet);
}
StackResource lb = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");
lb.getAttributes().put("LoadBalancerName", "web");
provisioner.provision(lb, props, ctx(LB_ARN));
return lb;
}
@Test
void anUpdateMovesTheKeptLoadBalancerOntoTheTemplateSubnetsAndARollbackMovesItBack() {
StackResource lb = keptLoadBalancerUpdatedTo(loadBalancerOn("web", "subnet-1", "subnet-2"),
"subnet-1", "subnet-3");
verify(elb).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-3"));
assertEquals(LB_ARN, lb.getPhysicalId());
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
}
@Test
void theSameSubnetsInAnotherOrderLeaveTheKeptLoadBalancerAlone() {
StackResource lb = keptLoadBalancerUpdatedTo(loadBalancerOn("web", "subnet-1", "subnet-2"),
"subnet-2", "subnet-1");
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb, never()).setSubnets(anyString(), anyString(), anyList());
}
@Test
void aCommittedUpdateForgetsThePriorSubnets() {
StackResource lb = keptLoadBalancerUpdatedTo(loadBalancerOn("web", "subnet-1", "subnet-2"),
"subnet-1", "subnet-3");
lb.setStatus("UPDATE_COMPLETE");
provisioner.completeUpdate(lb);
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-3"));
verify(elb, never()).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
}
@Test
void aFailedMoveBackPropagatesAndKeepsThePriorSubnetsForAnotherTry() {
StackResource lb = keptLoadBalancerUpdatedTo(loadBalancerOn("web", "subnet-1", "subnet-2"),
"subnet-1", "subnet-3");
doThrow(new AwsException("SubnetNotFound", "The subnet ID 'subnet-2' does not exist", 400)).doNothing()
.when(elb).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
AwsException failure = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(lb));
assertEquals("SubnetNotFound", failure.getErrorCode());
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb, times(2)).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
}
@Test
void aClearedUpdateForgetsThePriorSubnets() {
StackResource lb = keptLoadBalancerUpdatedTo(loadBalancerOn("web", "subnet-1", "subnet-2"),
"subnet-1", "subnet-3");
provisioner.clearUpdate(lb);
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb, never()).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
}
@Test
void aLaterUpdateThatLeavesTheSubnetsAloneDropsAStaleSnapshot() {
StackResource lb = keptLoadBalancerUpdatedTo(loadBalancerOn("web", "subnet-1", "subnet-2"),
"subnet-1", "subnet-3");
ObjectNode props = mapper.createObjectNode().put("Name", "web");
props.putArray("Subnets").add("subnet-2").add("subnet-1");
provisioner.provision(lb, props, ctx(LB_ARN));
assertTrue(provisioner.rollbackUpdate(lb));
verify(elb, never()).setSubnets(REGION, LB_ARN, List.of("subnet-1", "subnet-2"));
}
@Test
void aCreateThatFindsTheNameTakenLeavesThatLoadBalancerOnItsSubnets() {
when(elb.createLoadBalancer(eq(REGION), eq("web"), isNull(), isNull(), isNull(), anyList(), anyList(), any()))
.thenThrow(new AwsException("DuplicateLoadBalancerName", "exists", 400));
when(elb.describeLoadBalancers(REGION, null, List.of("web"), null, null))
.thenReturn(List.of(loadBalancerOn("web", "subnet-1", "subnet-2")));
ObjectNode props = mapper.createObjectNode().put("Name", "web");
props.putArray("Subnets").add("subnet-3").add("subnet-4");
provisioner.provision(resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb"), props, ctx());
verify(elb, never()).setSubnets(anyString(), anyString(), anyList());
}
@Test
void subnetMappingsGiveTheSubnetsWhenSubnetsIsAbsent() {
when(elb.createLoadBalancer(eq(REGION), eq("nlb"), isNull(), eq("network"), isNull(),
eq(List.of("subnet-1", "subnet-2")), anyList(), any())).thenReturn(loadBalancer("nlb"));
ObjectNode props = mapper.createObjectNode().put("Name", "nlb").put("Type", "network");
ArrayNode mappings = props.putArray("SubnetMappings");
mappings.addObject().put("SubnetId", "subnet-1").put("AllocationId", "eipalloc-1");
mappings.addObject().put("SubnetId", "subnet-2");
StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Nlb");
provisioner.provision(r, props, ctx());
assertEquals(LB_ARN, r.getPhysicalId());
}
/**
* {@code SubnetId} is required in a {@code SubnetMapping}. A mapping without one fails the
* resource before any load balancer is created, rather than leaving a balancer with no subnets.
*/
@Test
void aSubnetMappingWithoutASubnetIdIsRefusedBeforeTheLoadBalancerIsCreated() {
ObjectNode props = mapper.createObjectNode().put("Name", "nlb").put("Type", "network");
props.putArray("SubnetMappings").addObject().put("AllocationId", "eipalloc-1");
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(
resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Nlb"), props, ctx()));
assertEquals("InvalidRequest", e.getErrorCode());
assertTrue(e.getMessage().contains("#/SubnetMappings/0: required key [SubnetId] not found"), e.getMessage());
verify(elb, never()).createLoadBalancer(anyString(), anyString(), any(), any(), any(), anyList(), anyList(), any());
}
/** The same mapping on an update of a kept load balancer fails before it is moved anywhere. */
@Test
void anUpdateWithASubnetMappingWithoutASubnetIdLeavesTheKeptLoadBalancerAlone() {
ObjectNode props = mapper.createObjectNode().put("Name", "web");
ArrayNode mappings = props.putArray("SubnetMappings");
mappings.addObject().put("SubnetId", "subnet-1");
mappings.addObject().put("PrivateIPv4Address", "10.0.2.10");
StackResource lb = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");
lb.getAttributes().put("LoadBalancerName", "web");
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(lb, props, ctx(LB_ARN)));
assertTrue(e.getMessage().contains("#/SubnetMappings/1: required key [SubnetId] not found"), e.getMessage());
verify(elb, never()).createLoadBalancer(anyString(), anyString(), any(), any(), any(), anyList(), anyList(), any());
verify(elb, never()).setSubnets(anyString(), anyString(), anyList());
}
/**
* A blank {@code SubnetId} is passed on as given, so ELBv2 refuses it as an unknown subnet
* rather than the mapping being dropped and the balancer created without it.
*/
@Test
void aBlankSubnetIdIsPassedOnRatherThanDropped() {
when(elb.createLoadBalancer(eq(REGION), eq("nlb"), isNull(), eq("network"), isNull(),
eq(List.of(" ")), anyList(), any()))
.thenThrow(new AwsException("SubnetNotFound", "The subnet ID ' ' does not exist", 400));
ObjectNode props = mapper.createObjectNode().put("Name", "nlb").put("Type", "network");
props.putArray("SubnetMappings").addObject().put("SubnetId", " ");
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(
resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Nlb"), props, ctx()));
assertEquals("SubnetNotFound", e.getErrorCode());
}
/** On an update of a kept load balancer, a blank {@code SubnetId} reaches SetSubnets for ELBv2 to refuse. */
@Test
void anUpdateWithABlankSubnetIdIsRefusedByTheMoveAndKeepsNoSnapshot() {
when(elb.createLoadBalancer(eq(REGION), eq("web"), isNull(), isNull(), isNull(), anyList(), anyList(), any()))
.thenThrow(new AwsException("DuplicateLoadBalancerName", "exists", 400));
when(elb.describeLoadBalancers(REGION, null, List.of("web"), null, null))
.thenReturn(List.of(loadBalancerOn("web", "subnet-1", "subnet-2")));
doThrow(new AwsException("SubnetNotFound", "The subnet ID ' ' does not exist", 400))
.when(elb).setSubnets(REGION, LB_ARN, List.of(" "));
ObjectNode props = mapper.createObjectNode().put("Name", "web");
props.putArray("SubnetMappings").addObject().put("SubnetId", " ");
StackResource lb = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");
lb.getAttributes().put("LoadBalancerName", "web");
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(lb, props, ctx(LB_ARN)));
assertEquals("SubnetNotFound", e.getErrorCode());
assertNull(lb.getAttributes().get(CfnRollback.LOAD_BALANCER_SUBNETS_UPDATE_SNAPSHOT_ATTR));
}
/**
* {@code Subnets} and {@code SubnetMappings} together fail the resource with the error ELBv2's
* CreateLoadBalancer gives for both, before any load balancer is created.
*/
@Test
void subnetsAndSubnetMappingsTogetherAreRefusedBeforeTheLoadBalancerIsCreated() {
ObjectNode props = mapper.createObjectNode().put("Name", "nlb").put("Type", "network");
props.putArray("Subnets").add("subnet-1");
props.putArray("SubnetMappings").addObject().put("SubnetId", "subnet-2");
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(
resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Nlb"), props, ctx()));
assertEquals("ValidationError", e.getErrorCode());
assertEquals("You can specify either subnets or subnet mappings, not both", e.getMessage());
verify(elb, never()).createLoadBalancer(anyString(), anyString(), any(), any(), any(), anyList(), anyList(), any());
}
/** An empty {@code SubnetMappings} beside {@code Subnets}, as an Fn::If that drops each leaves, is allowed. */
@Test
void anEmptySubnetMappingsBesideSubnetsIsAllowed() {
when(elb.createLoadBalancer(eq(REGION), eq("alb"), isNull(), isNull(), isNull(),
eq(List.of("subnet-1", "subnet-2")), anyList(), any())).thenReturn(loadBalancer("alb"));
ObjectNode props = mapper.createObjectNode().put("Name", "alb");
props.putArray("Subnets").add("subnet-1").add("subnet-2");
props.putArray("SubnetMappings");
StackResource r = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");
provisioner.provision(r, props, ctx());
assertEquals(LB_ARN, r.getPhysicalId());
}
/** The same on an update of a kept load balancer, before it is moved anywhere. */
@Test
void anUpdateWithSubnetsAndSubnetMappingsTogetherLeavesTheKeptLoadBalancerAlone() {
ObjectNode props = mapper.createObjectNode().put("Name", "web");
props.putArray("Subnets").add("subnet-1").add("subnet-3");
props.putArray("SubnetMappings").addObject().put("SubnetId", "subnet-3");
StackResource lb = resource("AWS::ElasticLoadBalancingV2::LoadBalancer", "Alb");
lb.getAttributes().put("LoadBalancerName", "web");
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(lb, props, ctx(LB_ARN)));
assertEquals("ValidationError", e.getErrorCode());
verify(elb, never()).createLoadBalancer(anyString(), anyString(), any(), any(), any(), anyList(), anyList(), any());
verify(elb, never()).setSubnets(anyString(), anyString(), anyList());
}
@Test
void anInPlaceListenerUpdateIsNotRolledBackHere() {
when(elb.describeListeners(REGION, null, List.of(LISTENER_ARN))).thenReturn(List.of(listener(LB_ARN)));