Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(ec2): populate AvailabilityZoneId on subnets (#1677)
Alexis Carella870554295b3e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f8829868..4bd50e78 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **IoT Wireless — `GetPositionEstimate`** — the service was absent. `POST /position-estimate` now answers the way the API is shaped: the output structure declares a `payload` blob, so the HTTP body is the raw GeoJSON `Point` and boto3 hands the caller a `StreamingBody`, not a JSON envelope. The estimate is synthetic and deterministic (the canonical `Ip.IpAddress` hashes onto lon [-180, 180) / lat [-60, 60)); `properties` carry the two accuracy fields plus `timestamp`, which is always there: AWS documents the request's `Timestamp` as the time the position is resolved and the receive time as its substitute when the caller sends none, so a request that carries a `Timestamp` answers byte-identical bytes. `WiFiAccessPoints`, `CellTowers` and `Gnss` are accepted and ignored, while `AdvancedConfiguration.WiFiCellular.ConfidencePercent` drives the reported `horizontalConfidenceLevel` over 100, within the 50 to 99 the model allows. Refusals carry the live service's wording: no measurement, an unparseable address, a `Timestamp` that is not a Unix timestamp or a `ConfidencePercent` out of range is `ValidationException`; an address that is not globally routable, or is multicast, is `ResourceNotFoundException` `Cannot find position for the IP address <ip>`, as is a well-formed request whose only measurements are WLAN/cell/GNSS, which AWS documents that class for. Stateless. Contributed by @iot-rocket.### Fixed+- **EC2 — `AvailabilityZoneId` is populated on subnets** — `DescribeSubnets` and `CreateSubnet` always returned `null` for `AvailabilityZoneId`, even though `DescribeAvailabilityZones` reports the correct `ZoneId` mapping for the same account/region. Real AWS always populates this field, and consumers that fall back to computing it themselves when it's missing (e.g. the AWS Load Balancer Controller's subnet resolution) can crash on the fallback path. `CreateSubnet` now derives the id from the given (or default) `AvailabilityZone`; an `AvailabilityZoneId` supplied alongside it is preserved as given. The default-VPC and CloudFormation (`AWS::EC2::Subnet`) subnet-creation paths derive it the same way, and `DescribeSubnets` now always returns a non-null value. Subnets restored from state saved before this fix are backfilled on load. Contributed by @Alexis-DevOps.+- **EC2 — `DescribeAvailabilityZones` reports `ZoneType`** — the field was omitted entirely, so a consumer that branches on it (the AWS Load Balancer Controller's subnet locale resolution) read it as empty and refused to classify the subnet ("unknown zone type"), blocking Service/Ingress reconciliation. Every zone ministack fabricates is a standard Availability Zone, so `DescribeAvailabilityZones` now always reports `"availability-zone"`. Contributed by @Alexis-DevOps.- **CloudFormation — the template and stack quotas are enforced** — a template of any size, with any number of resources, parameters, outputs or mappings, and a stack name of any shape were accepted, so a template that a real account refuses deployed. `CreateStack`, `UpdateStack`, `CreateChangeSet`, `ValidateTemplate` and `GetTemplateSummary` now refuse a `TemplateBody` over 51,200 bytes and a template behind `TemplateURL` over 1,000,000 bytes; the engine refuses more than 500 resources, 200 parameters, 200 outputs, 200 mappings or 200 attributes in a mapping, a name over 255 characters, a description over 1,024 bytes and a parameter default or value over 4,096 bytes; `CreateStack` and a `CREATE` change set refuse a stack name that is not alphanumeric-and-hyphens starting with a letter or longer than 128 characters, joined with an oversized body into the one message the API's parameter validation gives. All of it before a stack record exists, with the messages of the API's parameter validation and the template format errors. `ValidateTemplate` also takes `TemplateURL` now. Contributed by @iot-rocket.### Fixed- **CloudFormation — `Capabilities` are enforced under `AUTH=true`** — `CreateStack`, `UpdateStack` and `CreateChangeSet` accepted a template with IAM resources or a `Transform` whatever the request acknowledged, so a deploy that CloudFormation refuses with `InsufficientCapabilitiesException` went through. With `AUTH=true` they now answer that error (HTTP 400, `Requires capabilities : [CAPABILITY_IAM]`, measured) and create nothing: an IAM resource needs `CAPABILITY_IAM` or `CAPABILITY_NAMED_IAM`, one with a custom name `CAPABILITY_NAMED_IAM`, a template with a `Transform` `CAPABILITY_AUTO_EXPAND` on `CreateStack` and `UpdateStack` (not on a change set, as the API documents). Without `AUTH` nothing changes; `GetTemplateSummary` keeps reporting the same set. Contributed by @iot-rocket.diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex b0e88a2a..ffa02a1c 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -5778,6 +5778,7 @@ def _ec2_subnet_create(logical_id, props, stack_name):"VpcId": vpc_id,"CidrBlock": cidr,"AvailabilityZone": az,+ "AvailabilityZoneId": _ec2._az_id_for_zone_name(az),"State": "available","AvailableIpAddressCount": 251,"DefaultForAz": False,diff --git a/ministack/services/ec2.py b/ministack/services/ec2.pyindex a99dbc3f..efc2a1c4 100644--- a/ministack/services/ec2.py+++ b/ministack/services/ec2.py@@ -134,6 +134,34 @@ _images = AccountRegionScopedDict() # ami_id -> registered image rec_default_initialized_scopes = set()+# ---------------------------------------------------------------------------+# Availability Zones+# ---------------------------------------------------------------------------++_AZ_ID_DIRECTIONS = {+ "north": "n", "south": "s", "east": "e", "west": "w", "central": "c",+ "northeast": "ne", "northwest": "nw", "southeast": "se", "southwest": "sw",+}+++def _az_id_prefix(region):+ """Region -> the AZ-id prefix AWS codes it with: eu-central-1 -> euc1, ap-southeast-2 -> apse2."""++ parts = region.split("-")+ if len(parts) < 3:+ return region.replace("-", "")+ geo, middles, index = parts[0], parts[1:-1], parts[-1]+ coded = "".join(_AZ_ID_DIRECTIONS.get(part, part[:1]) for part in middles)+ return f"{geo}{coded}{index}"+++def _az_id_for_zone_name(zone_name):+ """Zone name -> its AZ id, e.g. eu-west-3a -> euw3-az1 (matches DescribeAvailabilityZones)."""++ region, letter = zone_name[:-1], zone_name[-1]+ n = ord(letter.lower()) - ord("a") + 1+ return f"{_az_id_prefix(region)}-az{n}"+# ── Persistence ────────────────────────────────────────────@@ -296,6 +324,7 @@ def restore_state(data):_restore_regional_store(_placement_groups, data.get("placement_groups", {}))_restore_regional_store(_vpcs, data.get("vpcs", {}))_restore_regional_store(_subnets, data.get("subnets", {}))+ _backfill_subnet_availability_zone_ids()_restore_regional_store(_internet_gateways, data.get("internet_gateways", {}))_restore_regional_store(_addresses, data.get("addresses", {}))_restore_regional_store(_tags, data.get("tags", {}))@@ -356,6 +385,13 @@ def _restore_regional_store(store, restored):store.set_scoped(get_account_id(), region, key, value)+def _backfill_subnet_availability_zone_ids():+ """State saved before AvailabilityZoneId existed on subnets has none: backfill+ it so DescribeSubnets doesn't KeyError on a restored pre-upgrade snapshot."""+ for subnet in _subnets.all_values():+ subnet.setdefault("AvailabilityZoneId", _az_id_for_zone_name(subnet["AvailabilityZone"]))++try:_restored = load_state("ec2")if _restored:@@ -409,6 +445,7 @@ def _init_defaults():"VpcId": _DEFAULT_VPC_ID,"CidrBlock": cidr,"AvailabilityZone": az,+ "AvailabilityZoneId": _az_id_for_zone_name(az),"AvailableIpAddressCount": 4091,"State": "available","DefaultForAz": True,@@ -2855,9 +2892,11 @@ def _create_default_vpc(p):("172.31.0.0/20", "a"), ("172.31.16.0/20", "b"), ("172.31.32.0/20", "c"),]):subnet_id = _new_subnet_id()+ az = f"{get_region()}{az_suffix}"_subnets[subnet_id] = {"SubnetId": subnet_id, "VpcId": vpc_id, "CidrBlock": sub_cidr,- "AvailabilityZone": f"{get_region()}{az_suffix}",+ "AvailabilityZone": az,+ "AvailabilityZoneId": _az_id_for_zone_name(az),"AvailableIpAddressCount": 4091, "State": "available","DefaultForAz": True, "MapPublicIpOnLaunch": True,"OwnerId": get_account_id(),@@ -2913,12 +2952,14 @@ def _create_subnet(p):vpc_id = _p(p, "VpcId") or _DEFAULT_VPC_IDcidr = _p(p, "CidrBlock") or "10.0.1.0/24"az = _p(p, "AvailabilityZone") or f"{get_region()}a"+ az_id = _p(p, "AvailabilityZoneId") or _az_id_for_zone_name(az)subnet_id = _new_subnet_id()_subnets[subnet_id] = {"SubnetId": subnet_id,"VpcId": vpc_id,"CidrBlock": cidr,"AvailabilityZone": az,+ "AvailabilityZoneId": az_id,"AvailableIpAddressCount": 251,"State": "available","DefaultForAz": False,@@ -3418,35 +3459,13 @@ def _describe_vpc_endpoint_services(p):""")-# ----------------------------------------------------------------------------# Availability Zones-# -----------------------------------------------------------------------------_AZ_ID_DIRECTIONS = {- "north": "n", "south": "s", "east": "e", "west": "w", "central": "c",- "northeast": "ne", "northwest": "nw", "southeast": "se", "southwest": "sw",-}---def _az_id_prefix(region):- """Region -> the AZ-id prefix AWS codes it with: eu-central-1 -> euc1, ap-southeast-2 -> apse2."""-- parts = region.split("-")- if len(parts) < 3:- return region.replace("-", "")- geo, middles, index = parts[0], parts[1:-1], parts[-1]- coded = "".join(_AZ_ID_DIRECTIONS.get(part, part[:1]) for part in middles)- return f"{geo}{coded}{index}"--def _describe_availability_zones(p):"""AZ ids are deliberately unlike the zone names: AWS shuffles names per account, so AZa is different,while az1 is the same across accounts. The shuffle on AWS is per-account stable."""region = get_region()- prefix = _az_id_prefix(region)# 3 AZs with a=1, b=2, c=3 for ministack- zones = [(f"{region}{letter}", f"{prefix}-az{n}") for n, letter in enumerate("abc", start=1)]+ zones = [(f"{region}{letter}", _az_id_for_zone_name(f"{region}{letter}")) for letter in "abc"]# groupName / networkBorderGroup / optInStatus are optional members, so an# SDK silently returns a zone with those keys absent rather than erroring —# a consumer that reads them (Terraform's aws_availability_zones exposes@@ -3462,6 +3481,7 @@ def _describe_availability_zones(p):<groupName>{group_name}</groupName><networkBorderGroup>{region}</networkBorderGroup><optInStatus>opt-in-not-required</optInStatus>+ <zoneType>availability-zone</zoneType></item>""" for name, zone_id in zones)return _xml(200, "DescribeAvailabilityZonesResponse",f"<availabilityZoneInfo>{items}</availabilityZoneInfo>")@@ -4257,6 +4277,7 @@ def _subnet_fields_xml(subnet, tag="item"):<cidrBlock>{subnet['CidrBlock']}</cidrBlock><availableIpAddressCount>{subnet['AvailableIpAddressCount']}</availableIpAddressCount><availabilityZone>{subnet['AvailabilityZone']}</availabilityZone>+ <availabilityZoneId>{subnet['AvailabilityZoneId']}</availabilityZoneId><defaultForAz>{'true' if subnet['DefaultForAz'] else 'false'}</defaultForAz><mapPublicIpOnLaunch>{'true' if subnet['MapPublicIpOnLaunch'] else 'false'}</mapPublicIpOnLaunch><ownerId>{subnet['OwnerId']}</ownerId>diff --git a/tests/test_ec2.py b/tests/test_ec2.pyindex 1dbb46a5..8c454924 100644--- a/tests/test_ec2.py+++ b/tests/test_ec2.py@@ -118,6 +118,15 @@ def test_ec2_availability_zones_carry_group_and_opt_in(ec2):assert all(z["OptInStatus"] == "opt-in-not-required" for z in zones)+def test_ec2_availability_zones_carry_zone_type(ec2):+ """ZoneType is another optional member: a consumer that branches on it (the AWS+ Load Balancer Controller's subnet locale resolution) gets an empty string, not+ an error, when it's missing — and fails its own validation on that empty value.+ Every zone ministack fabricates is a standard Availability Zone."""+ zones = ec2.describe_availability_zones()["AvailabilityZones"]+ assert all(z["ZoneType"] == "availability-zone" for z in zones)++def test_ec2_describe_regions_returns_commercial_regions(ec2):"""DescribeRegions must list at least the four legacy us-* regionswith opt-in-not-required, and emit the shape AWS returns."""@@ -2672,6 +2681,62 @@ def test_ec2_default_subnets_three_azs(ec2):assert s["MapPublicIpOnLaunch"] is True+def test_ec2_default_subnets_carry_availability_zone_id(ec2):+ """Default VPC subnets must expose the same ZoneId DescribeAvailabilityZones reports."""+ resp = ec2.describe_subnets(Filters=[{"Name": "vpc-id", "Values": ["vpc-00000001"]}])+ by_az = {s["AvailabilityZone"]: s for s in resp["Subnets"]}+ assert by_az["us-east-1a"]["AvailabilityZoneId"] == "use1-az1"+ assert by_az["us-east-1b"]["AvailabilityZoneId"] == "use1-az2"+ assert by_az["us-east-1c"]["AvailabilityZoneId"] == "use1-az3"+++def test_ec2_create_subnet_availability_zone_id(ec2):+ """AvailabilityZoneId must never be null: it's derived from the AZ, or honored when given."""+ vpc_id = ec2.create_vpc(CidrBlock="10.78.0.0/16")["Vpc"]["VpcId"]++ derived = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.78.1.0/24",+ AvailabilityZone="us-east-1c")["Subnet"]+ assert derived["AvailabilityZoneId"] == "use1-az3"++ desc = ec2.describe_subnets(SubnetIds=[derived["SubnetId"]])["Subnets"][0]+ assert desc["AvailabilityZoneId"] == "use1-az3"++ # AZ says use1-az1, but an explicit AvailabilityZoneId must win.+ explicit = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.78.2.0/24",+ AvailabilityZone="us-east-1a",+ AvailabilityZoneId="use1-az2")["Subnet"]+ assert explicit["AvailabilityZoneId"] == "use1-az2"++ ec2.delete_subnet(SubnetId=derived["SubnetId"])+ ec2.delete_subnet(SubnetId=explicit["SubnetId"])+ ec2.delete_vpc(VpcId=vpc_id)+++def test_ec2_backfill_availability_zone_id_on_restore():+ """A subnet persisted before AvailabilityZoneId existed must not KeyError on restore.++ In-process against ministack.services.ec2 directly (like the AMI/instance tests+ below): this exercises the module's own state, not whatever separate process is+ serving the `ec2` fixture's HTTP requests.+ """+ import ministack.services.ec2 as ec2mod++ legacy_subnet = {+ "SubnetId": "subnet-legacy1", "VpcId": "vpc-legacy1", "CidrBlock": "10.9.0.0/24",+ "AvailabilityZone": "us-east-1b", "AvailableIpAddressCount": 251,+ "State": "available", "DefaultForAz": False, "MapPublicIpOnLaunch": False,+ "OwnerId": "000000000000",+ }+ ec2mod._subnets["subnet-legacy1"] = legacy_subnet+ try:+ ec2mod._backfill_subnet_availability_zone_ids()++ assert legacy_subnet["AvailabilityZoneId"] == "use1-az2"+ assert "<availabilityZoneId>use1-az2</availabilityZoneId>" in ec2mod._subnet_fields_xml(legacy_subnet)+ finally:+ del ec2mod._subnets["subnet-legacy1"]++def test_ec2_describe_subnets_tags_filters(ec2):vpc_id = ec2.create_vpc(CidrBlock="10.77.0.0/16")["Vpc"]["VpcId"]subnet_id = ec2.create_subnet(VpcId=vpc_id, CidrBlock="10.77.1.0/24")["Subnet"]["SubnetId"]