From 1743cb5f7518e6ccd12fcfc41c9cb66bcc48ea7e Mon Sep 17 00:00:00 2001 From: Jackson Price <59149601+jprice8@users.noreply.github.com> Date: Wed, 4 Nov 2026 03:26:03 -0600 Subject: [PATCH] fix(autoscaling): derive group zones from selected subnets (#7475) --- .../sdk-test-python/conftest.py | 29 +++- .../tests/test_autoscaling_describe_tags.py | 87 +++++------ .../tests/test_autoscaling_placement.py | 64 ++++---- .../test_autoscaling_subnet_whitespace.py | 107 ++++++-------- .../tests/test_autoscaling_subnet_zones.py | 137 ++++++++++++++++++ docs/services/autoscaling.md | 6 + .../autoscaling/AutoScalingService.java | 23 ++- 7 files changed, 304 insertions(+), 149 deletions(-) create mode 100644 compatibility-tests/sdk-test-python/tests/test_autoscaling_subnet_zones.py diff --git a/compatibility-tests/sdk-test-python/conftest.py b/compatibility-tests/sdk-test-python/conftest.py index 7b1a52474b..3d86a90202 100644 --- a/compatibility-tests/sdk-test-python/conftest.py +++ b/compatibility-tests/sdk-test-python/conftest.py @@ -1,12 +1,12 @@ """Shared fixtures for AWS service integration tests.""" import datetime +import io +import logging import os import uuid -import io import zipfile - -import logging +from contextlib import ExitStack, closing import boto3 import pytest @@ -222,6 +222,13 @@ def ec2_client(aws_config, client_config): return boto3.client("ec2", config=client_config, **aws_config) +@pytest.fixture +def autoscaling_client(aws_config, client_config): + """Create an Auto Scaling client and close it after the test.""" + with closing(boto3.client("autoscaling", config=client_config, **aws_config)) as client: + yield client + + @pytest.fixture def elbv2_client(aws_config, client_config): """Create Elastic Load Balancing v2 client.""" @@ -296,6 +303,22 @@ def make_self_signed_certificate(): # ============================================ +@pytest.fixture +def test_launch_template(ec2_client, unique_name): + """Create an image and launch template, cleaning up both after the test.""" + with ExitStack() as cleanup: + image = ec2_client.register_image( + Name=unique_name, Architecture="x86_64", RootDeviceName="/dev/sda1" + )["ImageId"] + cleanup.callback(ec2_client.deregister_image, ImageId=image) + template = ec2_client.create_launch_template( + LaunchTemplateName=unique_name, + LaunchTemplateData={"ImageId": image, "InstanceType": "t3.nano"}, + )["LaunchTemplate"]["LaunchTemplateId"] + cleanup.callback(ec2_client.delete_launch_template, LaunchTemplateId=template) + yield template + + @pytest.fixture def test_bucket(s3_client, unique_name): """Create and cleanup a test S3 bucket.""" diff --git a/compatibility-tests/sdk-test-python/tests/test_autoscaling_describe_tags.py b/compatibility-tests/sdk-test-python/tests/test_autoscaling_describe_tags.py index 5f1baa02ea..b2a94bc46d 100644 --- a/compatibility-tests/sdk-test-python/tests/test_autoscaling_describe_tags.py +++ b/compatibility-tests/sdk-test-python/tests/test_autoscaling_describe_tags.py @@ -1,6 +1,5 @@ """DescribeTags validation observed on AWS, 2026-10-17.""" -import uuid from contextlib import ExitStack, closing import boto3 @@ -9,53 +8,45 @@ from botocore.config import Config from botocore.exceptions import ClientError -def test_describe_tags_filter_validation(ec2_client, aws_config, client_config): - name = "tag-validation-" + uuid.uuid4().hex[:12] - with closing(boto3.client("autoscaling", config=client_config, **aws_config)) as autoscaling: - with ExitStack() as cleanup: - image = ec2_client.register_image( - Name=name, Architecture="x86_64", RootDeviceName="/dev/sda1" - )["ImageId"] - cleanup.callback(ec2_client.deregister_image, ImageId=image) - template = ec2_client.create_launch_template( - LaunchTemplateName=name, - LaunchTemplateData={"ImageId": image, "InstanceType": "t3.micro"}, - )["LaunchTemplate"]["LaunchTemplateId"] - cleanup.callback(ec2_client.delete_launch_template, LaunchTemplateId=template) - autoscaling.create_auto_scaling_group( - AutoScalingGroupName=name, MinSize=0, MaxSize=0, DesiredCapacity=0, - AvailabilityZones=[aws_config["region_name"] + "a"], - LaunchTemplate={"LaunchTemplateId": template}, - Tags=[ - {"Key": "propagated", "Value": "Yes", "PropagateAtLaunch": True}, - {"Key": "not-propagated", "Value": "No", "PropagateAtLaunch": False}, - ], - ) - cleanup.callback(autoscaling.delete_auto_scaling_group, - AutoScalingGroupName=name, ForceDelete=True) - group_filter = {"Name": "auto-scaling-group", "Values": [name]} - for filter_name, values, expected in [ - ("KEY", ["propagated"], ["propagated"]), - ("\u212Aey", ["propagated"], ["propagated"]), - ("key", ["PROPAGATED"], []), - ("propagate-at-launch", ["TrUe"], ["propagated"]), - ("propagate-at-launch", [" false "], ["not-propagated"]), - ("propagate-at-launch", ["\tTRUE\n"], ["propagated"]), - ("propagate-at-launch", [], ["not-propagated", "propagated"]), - ]: - tags = autoscaling.describe_tags(Filters=[ - group_filter, {"Name": filter_name, "Values": values}, - ])["Tags"] - assert sorted(tag["Key"] for tag in tags) == expected - for filter_value in [ - {"Name": "key"}, {"Values": ["propagated"]}, - {"Name": "unknown", "Values": []}, - {"Name": "propagate-at-launch", "Values": ["1"]}, - {"Name": "propagate-at-launch", "Values": ["tru e"]}, - ]: - with pytest.raises(ClientError) as failure: - autoscaling.describe_tags(Filters=[group_filter, filter_value]) - assert failure.value.response["Error"]["Code"] == "ValidationError" +def test_describe_tags_filter_validation( + autoscaling_client, test_launch_template, aws_config, unique_name +): + name = unique_name + with ExitStack() as cleanup: + autoscaling_client.create_auto_scaling_group( + AutoScalingGroupName=name, MinSize=0, MaxSize=0, DesiredCapacity=0, + AvailabilityZones=[aws_config["region_name"] + "a"], + LaunchTemplate={"LaunchTemplateId": test_launch_template}, + Tags=[ + {"Key": "propagated", "Value": "Yes", "PropagateAtLaunch": True}, + {"Key": "not-propagated", "Value": "No", "PropagateAtLaunch": False}, + ], + ) + cleanup.callback(autoscaling_client.delete_auto_scaling_group, + AutoScalingGroupName=name, ForceDelete=True) + group_filter = {"Name": "auto-scaling-group", "Values": [name]} + for filter_name, values, expected in [ + ("KEY", ["propagated"], ["propagated"]), + ("\u212Aey", ["propagated"], ["propagated"]), + ("key", ["PROPAGATED"], []), + ("propagate-at-launch", ["TrUe"], ["propagated"]), + ("propagate-at-launch", [" false "], ["not-propagated"]), + ("propagate-at-launch", ["\tTRUE\n"], ["propagated"]), + ("propagate-at-launch", [], ["not-propagated", "propagated"]), + ]: + tags = autoscaling_client.describe_tags(Filters=[ + group_filter, {"Name": filter_name, "Values": values}, + ])["Tags"] + assert sorted(tag["Key"] for tag in tags) == expected + for filter_value in [ + {"Name": "key"}, {"Values": ["propagated"]}, + {"Name": "unknown", "Values": []}, + {"Name": "propagate-at-launch", "Values": ["1"]}, + {"Name": "propagate-at-launch", "Values": ["tru e"]}, + ]: + with pytest.raises(ClientError) as failure: + autoscaling_client.describe_tags(Filters=[group_filter, filter_value]) + assert failure.value.response["Error"]["Code"] == "ValidationError" def test_describe_tags_pagination_validation(aws_config): diff --git a/compatibility-tests/sdk-test-python/tests/test_autoscaling_placement.py b/compatibility-tests/sdk-test-python/tests/test_autoscaling_placement.py index 53b7e3df5a..09fff6a1c5 100644 --- a/compatibility-tests/sdk-test-python/tests/test_autoscaling_placement.py +++ b/compatibility-tests/sdk-test-python/tests/test_autoscaling_placement.py @@ -1,9 +1,14 @@ """Synchronous placement inputs, checked against live AWS on 2026-10-12.""" -import uuid -from contextlib import ExitStack, closing +from contextlib import ExitStack -import boto3 +import pytest + + +@pytest.fixture +def aws_config(aws_config): + """Keep the observed us-east-1 placement cases in their original region.""" + return {**aws_config, "region_name": "us-east-1"} def test_subnet_counts_track_address_allocation(ec2_client): @@ -26,38 +31,23 @@ def test_subnet_counts_track_address_allocation(ec2_client): def test_zone_only_groups_accept_real_zones_outside_local_subnet_catalog( - aws_config, client_config + autoscaling_client, test_launch_template, unique_name ): - name = "zone-placement-" + uuid.uuid4().hex[:12] - aws_config = {**aws_config, "region_name": "us-east-1"} - with ( - closing(boto3.client("ec2", config=client_config, **aws_config)) as ec2_client, - closing(boto3.client("autoscaling", config=client_config, **aws_config)) as autoscaling, - ): - with ExitStack() as cleanup: - image = ec2_client.register_image( - Name=name, Architecture="x86_64", RootDeviceName="/dev/sda1" - )["ImageId"] - cleanup.callback(ec2_client.deregister_image, ImageId=image) - template = ec2_client.create_launch_template( - LaunchTemplateName=name, - LaunchTemplateData={"ImageId": image, "InstanceType": "t3.nano"}, - )["LaunchTemplate"]["LaunchTemplateId"] - cleanup.callback(ec2_client.delete_launch_template, LaunchTemplateId=template) - autoscaling.create_auto_scaling_group( - AutoScalingGroupName=name, - MinSize=0, MaxSize=0, DesiredCapacity=0, - LaunchTemplate={"LaunchTemplateId": template}, - AvailabilityZones=["us-east-1d"], - ) - cleanup.callback(autoscaling.delete_auto_scaling_group, - AutoScalingGroupName=name, ForceDelete=True) - group = autoscaling.describe_auto_scaling_groups( - AutoScalingGroupNames=[name])["AutoScalingGroups"][0] - assert group["AvailabilityZones"] == ["us-east-1d"] - autoscaling.update_auto_scaling_group( - AutoScalingGroupName=name, AvailabilityZones=["us-east-1d", "us-east-1f"]) - group = autoscaling.describe_auto_scaling_groups( - AutoScalingGroupNames=[name])["AutoScalingGroups"][0] - assert group["AvailabilityZones"] == ["us-east-1d", "us-east-1f"] - assert group["Instances"] == [] + with ExitStack() as cleanup: + autoscaling_client.create_auto_scaling_group( + AutoScalingGroupName=unique_name, + MinSize=0, MaxSize=0, DesiredCapacity=0, + LaunchTemplate={"LaunchTemplateId": test_launch_template}, + AvailabilityZones=["us-east-1d"], + ) + cleanup.callback(autoscaling_client.delete_auto_scaling_group, + AutoScalingGroupName=unique_name, ForceDelete=True) + group = autoscaling_client.describe_auto_scaling_groups( + AutoScalingGroupNames=[unique_name])["AutoScalingGroups"][0] + assert group["AvailabilityZones"] == ["us-east-1d"] + autoscaling_client.update_auto_scaling_group( + AutoScalingGroupName=unique_name, AvailabilityZones=["us-east-1d", "us-east-1f"]) + group = autoscaling_client.describe_auto_scaling_groups( + AutoScalingGroupNames=[unique_name])["AutoScalingGroups"][0] + assert group["AvailabilityZones"] == ["us-east-1d", "us-east-1f"] + assert group["Instances"] == [] diff --git a/compatibility-tests/sdk-test-python/tests/test_autoscaling_subnet_whitespace.py b/compatibility-tests/sdk-test-python/tests/test_autoscaling_subnet_whitespace.py index 172c538b7a..384a567860 100644 --- a/compatibility-tests/sdk-test-python/tests/test_autoscaling_subnet_whitespace.py +++ b/compatibility-tests/sdk-test-python/tests/test_autoscaling_subnet_whitespace.py @@ -1,66 +1,55 @@ """CreateAutoScalingGroup delimiter parity observed on AWS, 2026-10-12.""" -import uuid -from contextlib import ExitStack, closing - -import boto3 +from contextlib import ExitStack -def test_subnet_comma_space_is_normalized(ec2_client, aws_config, client_config): - name = "subnet-whitespace-" + uuid.uuid4().hex[:12] +def test_subnet_comma_space_is_normalized( + ec2_client, autoscaling_client, test_launch_template, aws_config, unique_name +): + name = unique_name region = aws_config["region_name"] zones = [region + "a", region + "b"] - with closing(boto3.client("autoscaling", config=client_config, **aws_config)) as autoscaling: - with ExitStack() as cleanup: - vpc = ec2_client.create_vpc(CidrBlock="10.98.0.0/16")["Vpc"]["VpcId"] - cleanup.callback(ec2_client.delete_vpc, VpcId=vpc) - subnets = [] - for index, zone in enumerate(zones): - subnet = ec2_client.create_subnet( - VpcId=vpc, - CidrBlock=f"10.98.{index}.0/24", - AvailabilityZone=zone, - )["Subnet"]["SubnetId"] - cleanup.callback(ec2_client.delete_subnet, SubnetId=subnet) - subnets.append(subnet) - image = ec2_client.register_image( - Name=name, Architecture="x86_64", RootDeviceName="/dev/sda1" - )["ImageId"] - cleanup.callback(ec2_client.deregister_image, ImageId=image) - template = ec2_client.create_launch_template( - LaunchTemplateName=name, - LaunchTemplateData={"ImageId": image, "InstanceType": "t3.micro"}, - )["LaunchTemplate"]["LaunchTemplateId"] - cleanup.callback(ec2_client.delete_launch_template, LaunchTemplateId=template) + with ExitStack() as cleanup: + vpc = ec2_client.create_vpc(CidrBlock="10.98.0.0/16")["Vpc"]["VpcId"] + cleanup.callback(ec2_client.delete_vpc, VpcId=vpc) + subnets = [] + for index, zone in enumerate(zones): + subnet = ec2_client.create_subnet( + VpcId=vpc, + CidrBlock=f"10.98.{index}.0/24", + AvailabilityZone=zone, + )["Subnet"]["SubnetId"] + cleanup.callback(ec2_client.delete_subnet, SubnetId=subnet) + subnets.append(subnet) - configurations = [] - for suffix, separator in [("space", ", "), ("no-space", ",")]: - group_name = name + "-" + suffix - autoscaling.create_auto_scaling_group( - AutoScalingGroupName=group_name, - MinSize=0, - MaxSize=0, - DesiredCapacity=0, - AvailabilityZones=zones, - LaunchTemplate={"LaunchTemplateId": template, "Version": "1"}, - VPCZoneIdentifier=separator.join(subnets), - ) - cleanup.callback( - autoscaling.delete_auto_scaling_group, - AutoScalingGroupName=group_name, - ForceDelete=True, - ) - groups = autoscaling.describe_auto_scaling_groups( - AutoScalingGroupNames=[group_name] - )["AutoScalingGroups"] - assert len(groups) == 1 - group = groups[0] - assert group["VPCZoneIdentifier"] == ",".join(subnets) - assert set(group["AvailabilityZones"]) == set(zones) - assert group["Instances"] == [] - assert group["MinSize"] == group["MaxSize"] == group["DesiredCapacity"] == 0 - configurations.append({ - key: value for key, value in group.items() - if key not in {"AutoScalingGroupName", "AutoScalingGroupARN", "CreatedTime"} - }) - assert configurations[0] == configurations[1] + configurations = [] + for suffix, separator in [("space", ", "), ("no-space", ",")]: + group_name = name + "-" + suffix + autoscaling_client.create_auto_scaling_group( + AutoScalingGroupName=group_name, + MinSize=0, + MaxSize=0, + DesiredCapacity=0, + AvailabilityZones=zones, + LaunchTemplate={"LaunchTemplateId": test_launch_template, "Version": "1"}, + VPCZoneIdentifier=separator.join(subnets), + ) + cleanup.callback( + autoscaling_client.delete_auto_scaling_group, + AutoScalingGroupName=group_name, + ForceDelete=True, + ) + groups = autoscaling_client.describe_auto_scaling_groups( + AutoScalingGroupNames=[group_name] + )["AutoScalingGroups"] + assert len(groups) == 1 + group = groups[0] + assert group["VPCZoneIdentifier"] == ",".join(subnets) + assert set(group["AvailabilityZones"]) == set(zones) + assert group["Instances"] == [] + assert group["MinSize"] == group["MaxSize"] == group["DesiredCapacity"] == 0 + configurations.append({ + key: value for key, value in group.items() + if key not in {"AutoScalingGroupName", "AutoScalingGroupARN", "CreatedTime"} + }) + assert configurations[0] == configurations[1] diff --git a/compatibility-tests/sdk-test-python/tests/test_autoscaling_subnet_zones.py b/compatibility-tests/sdk-test-python/tests/test_autoscaling_subnet_zones.py new file mode 100644 index 0000000000..fcf47cd316 --- /dev/null +++ b/compatibility-tests/sdk-test-python/tests/test_autoscaling_subnet_zones.py @@ -0,0 +1,137 @@ +"""Group zone readback follows the selected VPC subnets.""" + +import uuid +from contextlib import ExitStack + +import pytest +from botocore.exceptions import ClientError + + +@pytest.mark.parametrize("explicit_initial_zones", [False, True]) +def test_subnet_zones_follow_create_and_update( + ec2_client, autoscaling_client, test_launch_template, unique_name, explicit_initial_zones +): + zones = [ + zone["ZoneName"] + for zone in ec2_client.describe_availability_zones( + Filters=[{"Name": "state", "Values": ["available"]}] + )["AvailabilityZones"] + ][:2] + assert len(zones) == 2 + with ExitStack() as cleanup: + vpc = ec2_client.create_vpc(CidrBlock="10.94.0.0/16")["Vpc"]["VpcId"] + cleanup.callback(ec2_client.delete_vpc, VpcId=vpc) + subnets = [] + for index, zone in enumerate([zones[0], zones[0], zones[1]]): + subnet = ec2_client.create_subnet( + VpcId=vpc, + CidrBlock=f"10.94.{index}.0/24", + AvailabilityZone=zone, + )["Subnet"]["SubnetId"] + cleanup.callback(ec2_client.delete_subnet, SubnetId=subnet) + subnets.append(subnet) + placement = {"AvailabilityZones": zones} if explicit_initial_zones else {} + autoscaling_client.create_auto_scaling_group( + AutoScalingGroupName=unique_name, + MinSize=0, + MaxSize=0, + DesiredCapacity=0, + LaunchTemplate={"LaunchTemplateId": test_launch_template}, + VPCZoneIdentifier=",".join(subnets), + **placement, + ) + cleanup.callback( + autoscaling_client.delete_auto_scaling_group, + AutoScalingGroupName=unique_name, + ForceDelete=True, + ) + + def described(): + return autoscaling_client.describe_auto_scaling_groups( + AutoScalingGroupNames=[unique_name] + )["AutoScalingGroups"][0] + + group = described() + assert sorted(group["AvailabilityZones"]) == sorted(zones) + assert group["VPCZoneIdentifier"] == ",".join(subnets) + assert group["Instances"] == [] + + autoscaling_client.update_auto_scaling_group( + AutoScalingGroupName=unique_name, VPCZoneIdentifier=subnets[2] + ) + group = described() + assert group["AvailabilityZones"] == [zones[1]] + assert group["VPCZoneIdentifier"] == subnets[2] + autoscaling_client.update_auto_scaling_group( + AutoScalingGroupName=unique_name, DefaultCooldown=60 + ) + group = described() + assert group["AvailabilityZones"] == [zones[1]] + assert group["VPCZoneIdentifier"] == subnets[2] + assert group["DefaultCooldown"] == 60 + + +@pytest.mark.parametrize("include_valid_subnet", [False, True]) +def test_missing_subnets_leave_group_unchanged( + ec2_client, autoscaling_client, test_launch_template, unique_name, include_valid_subnet +): + with ExitStack() as cleanup: + vpc = ec2_client.create_vpc(CidrBlock="10.95.0.0/16")["Vpc"]["VpcId"] + cleanup.callback(ec2_client.delete_vpc, VpcId=vpc) + subnet = ec2_client.create_subnet(VpcId=vpc, CidrBlock="10.95.0.0/24")["Subnet"]["SubnetId"] + cleanup.callback(ec2_client.delete_subnet, SubnetId=subnet) + autoscaling_client.create_auto_scaling_group( + AutoScalingGroupName=unique_name, + MinSize=0, + MaxSize=1, + DesiredCapacity=0, + DefaultCooldown=300, + LaunchTemplate={"LaunchTemplateId": test_launch_template, "Version": "1"}, + VPCZoneIdentifier=subnet, + ) + cleanup.callback( + autoscaling_client.delete_auto_scaling_group, AutoScalingGroupName=unique_name, ForceDelete=True + ) + before = autoscaling_client.describe_auto_scaling_groups( + AutoScalingGroupNames=[unique_name] + )["AutoScalingGroups"][0] + missing = "subnet-" + uuid.uuid4().hex[:17] + rejected_subnets = [subnet, missing] if include_valid_subnet else [missing] + + with pytest.raises(ClientError) as refused: + autoscaling_client.update_auto_scaling_group( + AutoScalingGroupName=unique_name, + LaunchTemplate={"LaunchTemplateId": test_launch_template, "Version": "$Latest"}, + MaxSize=8, + DefaultCooldown=60, + HealthCheckGracePeriod=120, + VPCZoneIdentifier=",".join(rejected_subnets), + ) + assert refused.value.response["Error"]["Code"] == "ValidationError" + assert refused.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400 + assert missing in refused.value.response["Error"]["Message"] + after = autoscaling_client.describe_auto_scaling_groups( + AutoScalingGroupNames=[unique_name] + )["AutoScalingGroups"][0] + assert after == before + + rejected_name = unique_name + "-rejected" + with pytest.raises(ClientError) as refused: + autoscaling_client.create_auto_scaling_group( + AutoScalingGroupName=rejected_name, + MinSize=0, + MaxSize=0, + DesiredCapacity=0, + LaunchTemplate={"LaunchTemplateId": test_launch_template}, + VPCZoneIdentifier=",".join(rejected_subnets), + ) + cleanup.callback( + autoscaling_client.delete_auto_scaling_group, + AutoScalingGroupName=rejected_name, + ForceDelete=True, + ) + assert refused.value.response["Error"]["Code"] == "ValidationError" + assert missing in refused.value.response["Error"]["Message"] + assert autoscaling_client.describe_auto_scaling_groups( + AutoScalingGroupNames=[rejected_name] + )["AutoScalingGroups"] == [] diff --git a/docs/services/autoscaling.md b/docs/services/autoscaling.md index 0c14db475a..2cefa734f9 100644 --- a/docs/services/autoscaling.md +++ b/docs/services/autoscaling.md @@ -52,6 +52,12 @@ for create, and `eu-west-1` for update, using zero desired capacity. Rejected updates preserve the group's existing configuration. This does not enable preview support for multiple reservation targets. +When `AvailabilityZones` is omitted, group creation and subnet updates derive the +distinct zones from `VPCZoneIdentifier`. Updates without placement fields retain +the group's current subnet and zone selection. Zone derivation rejects missing +subnet IDs with `ValidationError` before changing an existing group or storing a +new one. + Scale-out follows the [AWS placement rules](https://docs.aws.amazon.com/autoscaling/ec2/userguide/auto-scaling-benefits.html): choose the zone with the fewest active instances, then its subnet with the most free IPv4 addresses. Declared subnets and actual EC2 placement take precedence diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java index baf349e1c7..19abfa0523 100644 --- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java +++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java @@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.ec2.Ec2UserDataDecoder; import io.github.hectorvent.floci.services.ec2.model.Instance; 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.Subnet; import io.github.hectorvent.floci.services.ec2.model.Tag; import io.github.hectorvent.floci.services.elb.ElbClassicService; import io.github.hectorvent.floci.services.elbv2.ElbV2Service; @@ -422,7 +423,7 @@ public class AutoScalingService implements PassedRoleLookup { asg.setMaxSize(maxSize); asg.setDesiredCapacity(desiredCapacity); asg.setDefaultCooldown(defaultCooldown > 0 ? defaultCooldown : 300); - asg.setAvailabilityZones(availabilityZones != null ? new ArrayList<>(availabilityZones) : new ArrayList<>()); + asg.setAvailabilityZones(new ArrayList<>(resolveAvailabilityZones(region, availabilityZones, subnetIds))); asg.setSubnetIds(subnetIds != null ? new ArrayList<>(subnetIds) : new ArrayList<>()); asg.setTargetGroupARNs(targetGroupArns != null ? new ArrayList<>(targetGroupArns) : new ArrayList<>()); asg.setLoadBalancerNames(lbNames != null ? new ArrayList<>(lbNames) : new ArrayList<>()); @@ -479,6 +480,10 @@ public class AutoScalingService implements PassedRoleLookup { validateDesiredCapacityType( effectiveDesiredCapacityType(asg, optionalFields), effectiveIdentity.mixedInstancesPolicy()); + List updatedZones = availabilityZones; + if (subnetIds != null && !subnetIds.isEmpty()) { + updatedZones = resolveAvailabilityZones(region, availabilityZones, subnetIds); + } if (launchConfigName != null) { asg.setLaunchConfigurationName(launchConfigName); asg.setLaunchTemplateId(null); @@ -504,7 +509,7 @@ public class AutoScalingService implements PassedRoleLookup { if (maxSize != null) { asg.setMaxSize(maxSize); } if (desiredCapacity != null) { asg.setDesiredCapacity(desiredCapacity); } if (defaultCooldown != null) { asg.setDefaultCooldown(defaultCooldown); } - if (availabilityZones != null) { asg.setAvailabilityZones(new ArrayList<>(availabilityZones)); } + if (updatedZones != null) { asg.setAvailabilityZones(new ArrayList<>(updatedZones)); } if (subnetIds != null) { asg.setSubnetIds(new ArrayList<>(subnetIds)); } if (healthCheckType != null) { asg.setHealthCheckType(healthCheckType); } if (healthCheckGracePeriod != null) { asg.setHealthCheckGracePeriod(healthCheckGracePeriod); } @@ -516,6 +521,20 @@ public class AutoScalingService implements PassedRoleLookup { } } + private List resolveAvailabilityZones(String region, List availabilityZones, List subnetIds) { + if ((availabilityZones == null || availabilityZones.isEmpty()) && subnetIds != null && !subnetIds.isEmpty()) { + List subnets = ec2Service.describeSubnets(region, subnetIds, null); + Set foundIds = subnets.stream().map(Subnet::getSubnetId).collect(Collectors.toSet()); + for (String subnetId : subnetIds) { + if (!foundIds.contains(subnetId)) { + throw new AwsException("ValidationError", "The subnet ID '" + subnetId + "' does not exist", 400); + } + } + return subnets.stream().map(Subnet::getAvailabilityZone).distinct().toList(); + } + return availabilityZones != null ? availabilityZones : List.of(); + } + /** * EnableMetricsCollection: {@code Granularity} is required and 1Minute is its only valid value. * Naming no metrics enables all of them.