Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(elbv2): provision ELBv2 resources via CloudFormation (#1121)

Hector Ventura4695103bf04e
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
index faa21f1ea7..4cde6b29b3 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
@@ -26,6 +26,13 @@ import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration;
import io.github.hectorvent.floci.services.ecs.model.NetworkMode;
import io.github.hectorvent.floci.services.ecs.model.PortMapping;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
+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.Listener;
+import io.github.hectorvent.floci.services.elbv2.model.LoadBalancer;
+import io.github.hectorvent.floci.services.elbv2.model.Rule;
+import io.github.hectorvent.floci.services.elbv2.model.RuleCondition;
+import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.kms.KmsService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
@@ -90,6 +97,7 @@ public class CloudFormationResourceProvisioner {
private final PipesService pipesService;
private final CognitoService cognitoService;
private final EcsService ecsService;
+ private final ElbV2Service elbV2Service;
@Inject
public CloudFormationResourceProvisioner(S3Service s3Service, SqsService sqsService,
@@ -103,7 +111,8 @@ public class CloudFormationResourceProvisioner {
EcrService ecrService,
PipesService pipesService,
CognitoService cognitoService,
- EcsService ecsService) {
+ EcsService ecsService,
+ ElbV2Service elbV2Service) {
this.s3Service = s3Service;
this.sqsService = sqsService;
this.snsService = snsService;
@@ -120,6 +129,7 @@ public class CloudFormationResourceProvisioner {
this.pipesService = pipesService;
this.cognitoService = cognitoService;
this.ecsService = ecsService;
+ this.elbV2Service = elbV2Service;
}
/**
@@ -196,6 +206,14 @@ public class CloudFormationResourceProvisioner {
case "AWS::ECS::Cluster" -> provisionEcsCluster(resource, properties, engine, region, stackName);
case "AWS::ECS::TaskDefinition" -> provisionEcsTaskDefinition(resource, properties, engine, region, stackName);
case "AWS::ECS::Service" -> provisionEcsService(resource, properties, engine, region, stackName);
+ case "AWS::ElasticLoadBalancingV2::LoadBalancer" ->
+ provisionLoadBalancer(resource, properties, engine, region, stackName);
+ case "AWS::ElasticLoadBalancingV2::TargetGroup" ->
+ provisionTargetGroup(resource, properties, engine, region, stackName);
+ case "AWS::ElasticLoadBalancingV2::Listener" ->
+ provisionListener(resource, properties, engine, region);
+ case "AWS::ElasticLoadBalancingV2::ListenerRule" ->
+ provisionListenerRule(resource, properties, engine, region);
default -> {
LOG.debugv("Stubbing unsupported resource type: {0} ({1})", resourceType, logicalId);
resource.setPhysicalId(logicalId + "-" + UUID.randomUUID().toString().substring(0, 8));
@@ -241,6 +259,10 @@ public class CloudFormationResourceProvisioner {
case "AWS::ECS::Cluster" -> ecsService.deleteCluster(physicalId, region);
case "AWS::ECS::TaskDefinition" -> ecsService.deregisterTaskDefinition(physicalId, region);
case "AWS::ECS::Service" -> deleteEcsServiceSafe(physicalId, region);
+ case "AWS::ElasticLoadBalancingV2::LoadBalancer" -> elbV2Service.deleteLoadBalancer(region, physicalId);
+ case "AWS::ElasticLoadBalancingV2::TargetGroup" -> elbV2Service.deleteTargetGroup(region, physicalId);
+ case "AWS::ElasticLoadBalancingV2::Listener" -> elbV2Service.deleteListener(region, physicalId);
+ case "AWS::ElasticLoadBalancingV2::ListenerRule" -> elbV2Service.deleteRule(region, physicalId);
default -> LOG.debugv("Skipping delete of unsupported resource type: {0}", resourceType);
}
} catch (Exception e) {
@@ -1957,6 +1979,320 @@ public class CloudFormationResourceProvisioner {
}
}
+ // ── ELBv2 ────────────────────────────────────────────────────────────────
+
+ private void provisionLoadBalancer(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
+ String region, String stackName) {
+ String name = resolveOptional(props, "Name", engine);
+ if (name == null || name.isBlank()) {
+ name = generateElbName(stackName, r.getLogicalId());
+ }
+ String scheme = resolveOptional(props, "Scheme", engine);
+ String type = resolveOptional(props, "Type", engine);
+ String ipAddressType = resolveOptional(props, "IpAddressType", engine);
+ List<String> subnets = resolveStringListOrEmpty(props, "Subnets", engine);
+ List<String> securityGroups = resolveStringListOrEmpty(props, "SecurityGroups", engine);
+ Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, engine);
+
+ LoadBalancer lb;
+ try {
+ lb = elbV2Service.createLoadBalancer(region, name, scheme, type, ipAddressType,
+ subnets, securityGroups, tags);
+ } catch (AwsException e) {
+ if ("DuplicateLoadBalancerName".equals(e.getErrorCode())) {
+ lb = elbV2Service.describeLoadBalancers(region, null, List.of(name), null, null).get(0);
+ } else {
+ throw e;
+ }
+ }
+
+ r.setPhysicalId(lb.getLoadBalancerArn());
+ r.getAttributes().put("LoadBalancerArn", lb.getLoadBalancerArn());
+ r.getAttributes().put("DNSName", lb.getDnsName());
+ r.getAttributes().put("CanonicalHostedZoneID", lb.getCanonicalHostedZoneId());
+ r.getAttributes().put("LoadBalancerName", lb.getLoadBalancerName());
+ r.getAttributes().put("LoadBalancerFullName", loadBalancerFullName(lb.getLoadBalancerArn()));
+ }
+
+ private void provisionTargetGroup(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
+ String region, String stackName) {
+ String name = resolveOptional(props, "Name", engine);
+ if (name == null || name.isBlank()) {
+ name = generateElbName(stackName, r.getLogicalId());
+ }
+ String protocol = resolveOptional(props, "Protocol", engine);
+ String protocolVersion = resolveOptional(props, "ProtocolVersion", engine);
+ Integer port = parseIntOrNull(resolveOptional(props, "Port", engine));
+ String vpcId = resolveOptional(props, "VpcId", engine);
+ String targetType = resolveOptional(props, "TargetType", engine);
+ String hcProtocol = resolveOptional(props, "HealthCheckProtocol", engine);
+ String hcPort = resolveOptional(props, "HealthCheckPort", engine);
+ Boolean hcEnabled = parseBooleanOrNull(resolveOptional(props, "HealthCheckEnabled", engine));
+ String hcPath = resolveOptional(props, "HealthCheckPath", engine);
+ Integer hcInterval = parseIntOrNull(resolveOptional(props, "HealthCheckIntervalSeconds", engine));
+ Integer hcTimeout = parseIntOrNull(resolveOptional(props, "HealthCheckTimeoutSeconds", engine));
+ Integer healthyThreshold = parseIntOrNull(resolveOptional(props, "HealthyThresholdCount", engine));
+ Integer unhealthyThreshold = parseIntOrNull(resolveOptional(props, "UnhealthyThresholdCount", engine));
+ String matcher = parseMatcher(props, engine);
+ String ipAddressType = resolveOptional(props, "IpAddressType", engine);
+ Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, engine);
+
+ TargetGroup tg;
+ try {
+ tg = elbV2Service.createTargetGroup(region, name, protocol, protocolVersion, port, vpcId, targetType,
+ hcProtocol, hcPort, hcEnabled, hcPath, hcInterval, hcTimeout,
+ healthyThreshold, unhealthyThreshold, matcher, ipAddressType, tags);
+ } catch (AwsException e) {
+ if ("DuplicateTargetGroupName".equals(e.getErrorCode())) {
+ tg = elbV2Service.describeTargetGroups(region, null, null, List.of(name)).get(0);
+ } else {
+ throw e;
+ }
+ }
+
+ r.setPhysicalId(tg.getTargetGroupArn());
+ r.getAttributes().put("TargetGroupArn", tg.getTargetGroupArn());
+ r.getAttributes().put("TargetGroupName", tg.getTargetGroupName());
+ r.getAttributes().put("TargetGroupFullName", targetGroupFullName(tg.getTargetGroupArn()));
+ }
+
+ private void provisionListener(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
+ String region) {
+ String lbArn = resolveOptional(props, "LoadBalancerArn", engine);
+ String protocol = resolveOrDefault(props, "Protocol", engine, "HTTP");
+ int port = intOrDefault(resolveOptional(props, "Port", engine), 80);
+ String sslPolicy = resolveOptional(props, "SslPolicy", engine);
+ List<String> certificates = parseCertificates(props, engine);
+ List<Action> defaultActions = parseCfnActions(props != null ? props.get("DefaultActions") : null, engine);
+
+ Listener listener;
+ if (r.getPhysicalId() == null) {
+ listener = elbV2Service.createListener(region, lbArn, protocol, port, sslPolicy, certificates,
+ defaultActions, null, Map.of());
+ } else {
+ listener = elbV2Service.modifyListener(region, r.getPhysicalId(), protocol, port, sslPolicy,
+ certificates, defaultActions, null);
+ }
+
+ r.setPhysicalId(listener.getListenerArn());
+ r.getAttributes().put("ListenerArn", listener.getListenerArn());
+ }
+
+ private void provisionListenerRule(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
+ String region) {
+ String listenerArn = resolveOptional(props, "ListenerArn", engine);
+ int priority = intOrDefault(resolveOptional(props, "Priority", engine), 1);
+ List<RuleCondition> conditions =
+ parseCfnRuleConditions(props != null ? props.get("Conditions") : null, engine);
+ List<Action> actions = parseCfnActions(props != null ? props.get("Actions") : null, engine);
+
+ Rule rule;
+ if (r.getPhysicalId() == null) {
+ rule = elbV2Service.createRule(region, listenerArn, conditions, priority, actions, Map.of());
+ } else {
+ rule = elbV2Service.modifyRule(region, r.getPhysicalId(), conditions, actions);
+ }
+
+ r.setPhysicalId(rule.getRuleArn());
+ r.getAttributes().put("RuleArn", rule.getRuleArn());
+ r.getAttributes().put("IsDefault", String.valueOf(rule.isDefault()));
+ }
+
+ private List<Action> parseCfnActions(JsonNode node, CloudFormationTemplateEngine engine) {
+ List<Action> result = new ArrayList<>();
+ if (node == null || node.isNull()) {
+ return result;
+ }
+ JsonNode resolved = engine.resolveNode(node);
+ if (!resolved.isArray()) {
+ return result;
+ }
+ for (JsonNode item : resolved) {
+ Action action = new Action();
+ action.setType(textOrNull(item, "Type"));
+ if (item.hasNonNull("Order")) {
+ action.setOrder(item.path("Order").asInt());
+ }
+ if (item.hasNonNull("TargetGroupArn")) {
+ action.setTargetGroupArn(item.path("TargetGroupArn").asText());
+ }
+ JsonNode forward = item.path("ForwardConfig");
+ if (forward.isObject()) {
+ JsonNode tgs = forward.path("TargetGroups");
+ if (tgs.isArray()) {
+ List<Action.TargetGroupTuple> tuples = new ArrayList<>();
+ for (JsonNode t : tgs) {
+ Action.TargetGroupTuple tuple = new Action.TargetGroupTuple();
+ if (t.hasNonNull("TargetGroupArn")) {
+ tuple.setTargetGroupArn(t.path("TargetGroupArn").asText());
+ }
+ if (t.hasNonNull("Weight")) {
+ tuple.setWeight(t.path("Weight").asInt());
+ }
+ tuples.add(tuple);
+ }
+ action.setTargetGroups(tuples);
+ }
+ JsonNode stickiness = forward.path("TargetGroupStickinessConfig");
+ if (stickiness.isObject()) {
+ if (stickiness.hasNonNull("Enabled")) {
+ action.setStickinessEnabled(stickiness.path("Enabled").asBoolean());
+ }
+ if (stickiness.hasNonNull("DurationSeconds")) {
+ action.setStickinessDurationSeconds(stickiness.path("DurationSeconds").asInt());
+ }
+ }
+ }
+ JsonNode redirect = item.path("RedirectConfig");
+ if (redirect.isObject()) {
+ action.setRedirectProtocol(textOrNull(redirect, "Protocol"));
+ action.setRedirectPort(textOrNull(redirect, "Port"));
+ action.setRedirectHost(textOrNull(redirect, "Host"));
+ action.setRedirectPath(textOrNull(redirect, "Path"));
+ action.setRedirectQuery(textOrNull(redirect, "Query"));
+ action.setRedirectStatusCode(textOrNull(redirect, "StatusCode"));
+ }
+ JsonNode fixed = item.path("FixedResponseConfig");
+ if (fixed.isObject()) {
+ action.setFixedResponseStatusCode(textOrNull(fixed, "StatusCode"));
+ action.setFixedResponseContentType(textOrNull(fixed, "ContentType"));
+ action.setFixedResponseMessageBody(textOrNull(fixed, "MessageBody"));
+ }
+ result.add(action);
+ }
+ return result;
+ }
+
+ private List<RuleCondition> parseCfnRuleConditions(JsonNode node, CloudFormationTemplateEngine engine) {
+ List<RuleCondition> result = new ArrayList<>();
+ if (node == null || node.isNull()) {
+ return result;
+ }
+ JsonNode resolved = engine.resolveNode(node);
+ if (!resolved.isArray()) {
+ return result;
+ }
+ for (JsonNode item : resolved) {
+ RuleCondition condition = new RuleCondition();
+ condition.setField(textOrNull(item, "Field"));
+ if (item.path("Values").isArray()) {
+ condition.setValues(jsonArrayToStringList(item.path("Values")));
+ }
+ JsonNode pathCfg = item.path("PathPatternConfig");
+ if (pathCfg.path("Values").isArray()) {
+ condition.setPathPatternValues(jsonArrayToStringList(pathCfg.path("Values")));
+ }
+ JsonNode hostCfg = item.path("HostHeaderConfig");
+ if (hostCfg.path("Values").isArray()) {
+ condition.setHostHeaderValues(jsonArrayToStringList(hostCfg.path("Values")));
+ }
+ JsonNode httpHeaderCfg = item.path("HttpHeaderConfig");
+ if (httpHeaderCfg.isObject()) {
+ condition.setHttpHeaderName(textOrNull(httpHeaderCfg, "HttpHeaderName"));
+ if (httpHeaderCfg.path("Values").isArray()) {
+ condition.setHttpHeaderValues(jsonArrayToStringList(httpHeaderCfg.path("Values")));
+ }
+ }
+ JsonNode methodCfg = item.path("HttpRequestMethodConfig");
+ if (methodCfg.path("Values").isArray()) {
+ condition.setHttpMethodValues(jsonArrayToStringList(methodCfg.path("Values")));
+ }
+ JsonNode sourceIpCfg = item.path("SourceIpConfig");
+ if (sourceIpCfg.path("Values").isArray()) {
+ condition.setSourceIpValues(jsonArrayToStringList(sourceIpCfg.path("Values")));
+ }
+ JsonNode queryCfg = item.path("QueryStringConfig");
+ if (queryCfg.path("Values").isArray()) {
+ List<RuleCondition.QueryStringPair> pairs = new ArrayList<>();
+ for (JsonNode q : queryCfg.path("Values")) {
+ RuleCondition.QueryStringPair pair = new RuleCondition.QueryStringPair();
+ pair.setKey(textOrNull(q, "Key"));
+ pair.setValue(textOrNull(q, "Value"));
+ pairs.add(pair);
+ }
+ condition.setQueryStringValues(pairs);
+ }
+ result.add(condition);
+ }
+ return result;
+ }
+
+ private List<String> parseCertificates(JsonNode props, CloudFormationTemplateEngine engine) {
+ List<String> result = new ArrayList<>();
+ if (props == null || !props.has("Certificates") || props.get("Certificates").isNull()) {
+ return result;
+ }
+ JsonNode resolved = engine.resolveNode(props.get("Certificates"));
+ if (resolved.isArray()) {
+ for (JsonNode c : resolved) {
+ if (c.hasNonNull("CertificateArn")) {
+ result.add(c.path("CertificateArn").asText());
+ }
+ }
+ }
+ return result;
+ }
+
+ private String parseMatcher(JsonNode props, CloudFormationTemplateEngine engine) {
+ if (props == null || !props.has("Matcher") || props.get("Matcher").isNull()) {
+ return null;
+ }
+ JsonNode m = engine.resolveNode(props.get("Matcher"));
+ if (m.hasNonNull("HttpCode")) {
+ return m.path("HttpCode").asText();
+ }
+ if (m.hasNonNull("GrpcCode")) {
+ return m.path("GrpcCode").asText();
+ }
+ return null;
+ }
+
+ private String loadBalancerFullName(String lbArn) {
+ // LB ARN resource: loadbalancer/<type>/<name>/<id> → full name drops the "loadbalancer/" prefix.
+ String resource = AwsArnUtils.parse(lbArn).resource();
+ String prefix = "loadbalancer/";
+ return resource.startsWith(prefix) ? resource.substring(prefix.length()) : resource;
+ }
+
+ private String targetGroupFullName(String tgArn) {
+ // TG full name keeps the "targetgroup/" prefix, e.g. targetgroup/<name>/<id>.
+ return AwsArnUtils.parse(tgArn).resource();
+ }
+
+ private static String generateElbName(String stackName, String logicalId) {
+ // ELBv2 names: ≤32 chars, [A-Za-z0-9-], no leading/trailing hyphen.
+ String base = (stackName + "-" + logicalId).replaceAll("[^A-Za-z0-9-]", "");
+ String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
+ int maxBase = 32 - 1 - suffix.length();
+ if (base.length() > maxBase) {
+ base = base.substring(0, maxBase);
+ }
+ base = base.replaceAll("-+$", "");
+ if (base.isEmpty()) {
+ base = "elb";
+ }
+ return base + "-" + suffix;
+ }
+
+ private static Integer parseIntOrNull(String value) {
+ if (value == null || value.isBlank()) {
+ return null;
+ }
+ try {
+ return Integer.valueOf(value);
+ } catch (NumberFormatException e) {
+ return null;
+ }
+ }
+
+ private static Boolean parseBooleanOrNull(String value) {
+ return (value == null || value.isBlank()) ? null : Boolean.valueOf(value);
+ }
+
+ private static String textOrNull(JsonNode node, String field) {
+ return node != null && node.hasNonNull(field) ? node.path(field).asText() : null;
+ }
+
private String resolveOptional(JsonNode props, String name, CloudFormationTemplateEngine engine) {
if (props == null || !props.has(name) || props.get(name).isNull()) {
return null;
diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java
index 19696d2c26..3614ad945c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java
@@ -384,6 +384,7 @@ public class ElbV2Service {
ruleArns.forEach(regionRules::remove);
}
tags.remove(listenerArn);
+ unlinkUnreferencedTargetGroups(region, listener.getLoadBalancerArn());
}
public Listener modifyListener(String region, String listenerArn, String protocol, Integer port,
@@ -506,6 +507,10 @@ public class ElbV2Service {
regionRules.remove(ruleArn);
listenerToRules.getOrDefault(listenerArn, List.of()).remove(ruleArn);
tags.remove(ruleArn);
+ Listener listener = listeners.getOrDefault(region, Map.of()).get(listenerArn);
+ if (listener != null) {
+ unlinkUnreferencedTargetGroups(region, listener.getLoadBalancerArn());
+ }
dataPlane.recompileRules(listenerArn, getListenerRules(region, listenerArn));
}
@@ -814,4 +819,42 @@ public class ElbV2Service {
}
}
}
+
+ /**
+ * Drops {@code lbArn} from every target group that is no longer referenced by any of the
+ * load balancer's remaining listeners or rules. Called after a listener or rule is removed
+ * so a target group can be deleted once nothing routes to it (avoids a stale "in use" guard
+ * during teardown).
+ */
+ private void unlinkUnreferencedTargetGroups(String region, String lbArn) {
+ Set<String> referenced = new HashSet<>();
+ Map<String, Listener> regionListeners = listeners.getOrDefault(region, Map.of());
+ for (Listener listener : regionListeners.values()) {
+ if (lbArn.equals(listener.getLoadBalancerArn())) {
+ listener.getDefaultActions().forEach(a -> collectActionTargetGroups(a, referenced));
+ }
+ }
+ for (Rule rule : rules.getOrDefault(region, Map.of()).values()) {
+ Listener listener = regionListeners.get(rule.getListenerArn());
+ if (listener != null && lbArn.equals(listener.getLoadBalancerArn())) {
+ rule.getActions().forEach(a -> collectActionTargetGroups(a, referenced));
+ }
+ }
+ tgToLbs.forEach((tgArn, lbSet) -> {
+ if (!referenced.contains(tgArn)) {
+ lbSet.remove(lbArn);
+ }
+ });
+ }
+
+ private static void collectActionTargetGroups(Action action, Set<String> out) {
+ if (action.getTargetGroupArn() != null) {
+ out.add(action.getTargetGroupArn());
+ }
+ for (Action.TargetGroupTuple t : action.getTargetGroups()) {
+ if (t.getTargetGroupArn() != null) {
+ out.add(t.getTargetGroupArn());
+ }
+ }
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
index e4f466a18d..8656de92b5 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
@@ -5094,4 +5094,358 @@ class CloudFormationIntegrationTest {
.statusCode(200)
.body("taskDefinition.status", equalTo("INACTIVE"));
}
+
+ // ── Issue #924: ELBv2 provisioning via CloudFormation ────────────────────
+
+ private static final String ELB_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260601/us-east-1/elasticloadbalancing/aws4_request";
+
+ private static String cfnOutputValue(String describeXml, String key) {
+ return describeXml.split("<OutputKey>" + key + "</OutputKey>")[1]
+ .split("<OutputValue>")[1].split("</OutputValue>")[0];
+ }
+
+ @Test
+ void createStack_withElbV2LoadBalancerTargetGroupListenerRule() {
+ String template = """
+ {
+ "Resources": {
+ "Alb": {
+ "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
+ "Properties": {
+ "Name": "cfn-alb",
+ "Type": "application",
+ "Scheme": "internet-facing",
+ "Subnets": ["subnet-aaa", "subnet-bbb"],
+ "SecurityGroups": ["sg-123"]
+ }
+ },
+ "Tg": {
+ "Type": "AWS::ElasticLoadBalancingV2::TargetGroup",
+ "Properties": {
+ "Name": "cfn-tg",
+ "Protocol": "HTTP",
+ "Port": 80,
+ "VpcId": "vpc-00000001",
+ "TargetType": "ip",
+ "HealthCheckPath": "/health",
+ "Matcher": { "HttpCode": "200-299" }
+ }
+ },
+ "Listener": {
+ "Type": "AWS::ElasticLoadBalancingV2::Listener",
+ "Properties": {
+ "LoadBalancerArn": { "Ref": "Alb" },
+ "Protocol": "HTTP",
+ "Port": 80,
+ "DefaultActions": [
+ { "Type": "forward", "TargetGroupArn": { "Ref": "Tg" } }
+ ]
+ }
+ },
+ "Rule": {
+ "Type": "AWS::ElasticLoadBalancingV2::ListenerRule",
+ "Properties": {
+ "ListenerArn": { "Ref": "Listener" },
+ "Priority": 10,
+ "Conditions": [
+ { "Field": "path-pattern", "PathPatternConfig": { "Values": ["/api/*"] } }
+ ],
+ "Actions": [
+ { "Type": "forward", "TargetGroupArn": { "Ref": "Tg" } }
+ ]
+ }
+ }
+ },
+ "Outputs": {
+ "AlbRef": { "Value": { "Ref": "Alb" } },
+ "AlbDns": { "Value": { "Fn::GetAtt": ["Alb", "DNSName"] } },
+ "AlbFullName": { "Value": { "Fn::GetAtt": ["Alb", "LoadBalancerFullName"] } },
+ "AlbCanonical": { "Value": { "Fn::GetAtt": ["Alb", "CanonicalHostedZoneID"] } },
+ "TgRef": { "Value": { "Ref": "Tg" } },
+ "TgFullName": { "Value": { "Fn::GetAtt": ["Tg", "TargetGroupFullName"] } },
+ "TgName": { "Value": { "Fn::GetAtt": ["Tg", "TargetGroupName"] } },
+ "ListenerRef": { "Value": { "Ref": "Listener" } },
+ "RuleRef": { "Value": { "Ref": "Rule" } }
+ }
+ }
+ """;
+
+ String stackName = "cfn-elbv2-stack";
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<StackId>"));
+
+ String describeXml = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
+ .extract().asString();
+
+ // Ref/GetAtt parity: every ELBv2 resource's Ref is its ARN.
+ String albArn = cfnOutputValue(describeXml, "AlbRef");
+ assertThat(albArn, startsWith(
+ "arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/app/cfn-alb/"));
+ assertThat(cfnOutputValue(describeXml, "AlbDns"), containsString(".elb.localhost"));
+ assertThat(cfnOutputValue(describeXml, "AlbFullName"), startsWith("app/cfn-alb/"));
+ assertThat(cfnOutputValue(describeXml, "AlbCanonical"), notNullValue());
+ String tgArn = cfnOutputValue(describeXml, "TgRef");
+ assertThat(tgArn, startsWith(
+ "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/cfn-tg/"));
+ assertThat(cfnOutputValue(describeXml, "TgFullName"), startsWith("targetgroup/cfn-tg/"));
+ assertThat(cfnOutputValue(describeXml, "TgName"), equalTo("cfn-tg"));
+ assertThat(cfnOutputValue(describeXml, "ListenerRef"), startsWith(
+ "arn:aws:elasticloadbalancing:us-east-1:000000000000:listener/app/cfn-alb/"));
+ assertThat(cfnOutputValue(describeXml, "RuleRef"), startsWith(
+ "arn:aws:elasticloadbalancing:us-east-1:000000000000:listener-rule/app/cfn-alb/"));
+
+ // Load balancer is live in the ELBv2 service
+ given()
+ .formParam("Action", "DescribeLoadBalancers")
+ .formParam("Names.member.1", "cfn-alb")
+ .header("Authorization", ELB_AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.LoadBalancerArn",
+ equalTo(albArn))
+ .body("DescribeLoadBalancersResponse.DescribeLoadBalancersResult.LoadBalancers.member.Type",
+ equalTo("application"));
+
+ // Target group carries its health check configuration
+ given()
+ .formParam("Action", "DescribeTargetGroups")
+ .formParam("Names.member.1", "cfn-tg")
+ .header("Authorization", ELB_AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeTargetGroupsResponse.DescribeTargetGroupsResult.TargetGroups.member.TargetGroupArn",
+ equalTo(tgArn))
+ .body("DescribeTargetGroupsResponse.DescribeTargetGroupsResult.TargetGroups.member.HealthCheckPath",
+ equalTo("/health"))
+ .body("DescribeTargetGroupsResponse.DescribeTargetGroupsResult.TargetGroups.member.Port",
+ equalTo("80"));
+
+ // Listener exists on port 80
+ given()
+ .formParam("Action", "DescribeListeners")
+ .formParam("LoadBalancerArn", albArn)
+ .header("Authorization", ELB_AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeListenersResponse.DescribeListenersResult.Listeners.member.Port", equalTo("80"))
+ .body("DescribeListenersResponse.DescribeListenersResult.Listeners.member.Protocol", equalTo("HTTP"));
+
+ // The explicit listener rule (priority 10, path-pattern /api/*) was created
+ String rulesXml = given()
+ .formParam("Action", "DescribeRules")
+ .formParam("ListenerArn", cfnOutputValue(describeXml, "ListenerRef"))
+ .header("Authorization", ELB_AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().asString();
+ assertThat(rulesXml, containsString("<Priority>10</Priority>"));
+ assertThat(rulesXml, containsString("/api/*"));
+ }
+
+ @Test
+ void updateStack_elbV2Listener_modifiesPort() {
+ String stackName = "cfn-elbv2-update-stack";
+ String template = """
+ {
+ "Resources": {
+ "Alb": {
+ "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
+ "Properties": { "Name": "cfn-upd-alb", "Type": "application" }
+ },
+ "Listener": {
+ "Type": "AWS::ElasticLoadBalancingV2::Listener",
+ "Properties": {
+ "LoadBalancerArn": { "Ref": "Alb" },
+ "Protocol": "HTTP",
+ "Port": %d,
+ "DefaultActions": [
+ {
+ "Type": "fixed-response",
+ "FixedResponseConfig": {
+ "StatusCode": "200",
+ "ContentType": "text/plain",
+ "MessageBody": "ok"
+ }
+ }
+ ]
+ }
+ }
+ },
+ "Outputs": {
+ "AlbRef": { "Value": { "Ref": "Alb" } }
+ }
+ }
+ """;
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template.formatted(80))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ String createXml = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().asString();
+ String albArn = cfnOutputValue(createXml, "AlbRef");
+
+ given()
+ .formParam("Action", "DescribeListeners")
+ .formParam("LoadBalancerArn", albArn)
+ .header("Authorization", ELB_AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeListenersResponse.DescribeListenersResult.Listeners.member.Port", equalTo("80"));
+
+ // Update: change the listener port 80 -> 8080 (criterion #7, listener modify path)
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template.formatted(8080))
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .formParam("Action", "DescribeListeners")
+ .formParam("LoadBalancerArn", albArn)
+ .header("Authorization", ELB_AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeListenersResponse.DescribeListenersResult.Listeners.member.Port", equalTo("8080"));
+ }
+
+ @Test
+ void deleteStack_elbV2_leavesNoOrphans() {
+ // Declares the load balancer before the target group so teardown deletes the target
+ // group (reverse order) while the load balancer still exists — exercising the
+ // listener/rule target-group unlink so the target group is not left orphaned.
+ String stackName = "cfn-elbv2-delete-stack";
+ String template = """
+ {
+ "Resources": {
+ "Alb": {
+ "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
+ "Properties": { "Name": "cfn-del-alb", "Type": "application" }
+ },
+ "Tg": {
+ "Type": "AWS::ElasticLoadBalancingV2::TargetGroup",
+ "Properties": {
+ "Name": "cfn-del-tg",
+ "Protocol": "HTTP",
+ "Port": 80,
+ "VpcId": "vpc-00000001",
+ "TargetType": "ip"
+ }
+ },
+ "Listener": {
+ "Type": "AWS::ElasticLoadBalancingV2::Listener",
+ "Properties": {
+ "LoadBalancerArn": { "Ref": "Alb" },
+ "Protocol": "HTTP",
+ "Port": 80,
+ "DefaultActions": [
+ { "Type": "forward", "TargetGroupArn": { "Ref": "Tg" } }
+ ]
+ }
+ }
+ }
+ }
+ """;
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ // Sanity: target group exists before delete
+ given()
+ .formParam("Action", "DescribeTargetGroups")
+ .formParam("Names.member.1", "cfn-del-tg")
+ .header("Authorization", ELB_AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("DescribeTargetGroupsResponse.DescribeTargetGroupsResult.TargetGroups.member.TargetGroupName",
+ equalTo("cfn-del-tg"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteStack")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ // Load balancer is gone
+ given()
+ .formParam("Action", "DescribeLoadBalancers")
+ .formParam("Names.member.1", "cfn-del-alb")
+ .header("Authorization", ELB_AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("LoadBalancerNotFound"));
+
+ // Target group is gone too — not left orphaned during teardown
+ String tgXml = given()
+ .formParam("Action", "DescribeTargetGroups")
+ .header("Authorization", ELB_AUTH)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().asString();
+ assertThat(tgXml, not(containsString("cfn-del-tg")));
+ }
+
}