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 Lambda VpcId in function configuration (#1846)
Jay Janssen46706da638d2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cafd422e..fb331dfe 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,12 @@ All notable changes to MiniStack will be documented here.Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).Versioning follows [Semantic Versioning](https://semver.org/).+## [Unreleased]++### Fixed++- **Lambda — VPC configuration includes `VpcId`** — `CreateFunction`, `GetFunction`, `GetFunctionConfiguration`, and `UpdateFunctionConfiguration` now report the VPC of the configured subnets. Previously, VPC-attached functions returned only subnet and security group IDs. Contributed by @jayjanssen.+## [1.5.18] — 2026-09-28### Addeddiff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex b55cdb5c..029999fc 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -1556,6 +1556,30 @@ def _snapstart_provision_version_async(name: str, ver_record: dict) -> None:).start()+def _vpc_config_with_id(request_config: dict | None) -> dict:+ """Add Lambda's read-only VpcId from the configured EC2 subnets."""+ config = copy.deepcopy(request_config) if request_config is not None else {+ "SubnetIds": [], "SecurityGroupIds": [],+ }+ subnet_ids = config.get("SubnetIds") or []+ vpc_ids = set()+ all_found = True+ if subnet_ids:+ from ministack.services import ec2++ ec2._ensure_defaults_initialized()+ for subnet_id in subnet_ids:+ subnet = ec2._subnets.get(subnet_id)+ if subnet is None:+ all_found = False+ break+ vpc_ids.add(subnet["VpcId"])+ # An unknown or mixed-VPC subnet set must not claim a VPC. AWS validates+ # these inputs; MiniStack currently accepts them, so leave VpcId empty.+ config["VpcId"] = vpc_ids.pop() if all_found and len(vpc_ids) == 1 else ""+ return config++def _build_config(name: str, data: dict, code_zip: bytes | None = None) -> dict:code_size = len(code_zip) if code_zip else 0code_sha = base64.b64encode(hashlib.sha256(code_zip).digest()).decode() if code_zip else ""@@ -1603,14 +1627,7 @@ def _build_config(name: str, data: dict, code_zip: bytes | None = None) -> dict:"Architectures": data.get("Architectures", ["x86_64"]),"Layers": layers_cfg,"TracingConfig": data.get("TracingConfig", {"Mode": "PassThrough"}),- "VpcConfig": data.get(- "VpcConfig",- {- "SubnetIds": [],- "SecurityGroupIds": [],- "VpcId": "",- },- ),+ "VpcConfig": _vpc_config_with_id(data.get("VpcConfig")),"KMSKeyArn": data.get("KMSKeyArn", ""),"RevisionId": new_uuid(),"EphemeralStorage": data.get("EphemeralStorage", {"Size": 512}),@@ -2877,6 +2894,8 @@ def _update_config(name: str, data: dict):# Request carries only ApplyOn; the stored/echoed shape adds# OptimizationStatus, which is always Off on $LATEST.config["SnapStart"] = _snapstart_response(data["SnapStart"])+ elif key == "VpcConfig":+ config[key] = _vpc_config_with_id(data[key])else:config[key] = data[key]if "Architectures" in data:diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex aa41337d..986222b0 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -1048,6 +1048,51 @@ def test_lambda_create_function(lam):assert resp["LastUpdateStatus"] in ("InProgress", "Successful")assert "FunctionArn" in resp++def test_lambda_vpc_id_follows_subnets_on_create_and_update(lam, ec2):+ name = f"lam-vpc-id-{_uuid_mod.uuid4().hex[:8]}"+ networks = []+ try:+ for cidr, subnet_cidrs in (("10.91.0.0/16", ("10.91.1.0/24", "10.91.2.0/24")),+ ("10.92.0.0/16", ("10.92.1.0/24", "10.92.2.0/24"))):+ vpc_id = ec2.create_vpc(CidrBlock=cidr)["Vpc"]["VpcId"]+ subnet_ids = [ec2.create_subnet(VpcId=vpc_id, CidrBlock=subnet_cidr)["Subnet"]["SubnetId"]+ for subnet_cidr in subnet_cidrs]+ group_id = ec2.create_security_group(+ GroupName=f"{name}-{len(networks)}", Description="Lambda VPC ID test", VpcId=vpc_id,+ )["GroupId"]+ networks.append((vpc_id, subnet_ids, group_id))++ first_vpc, first_subnets, first_group = networks[0]+ created = lam.create_function(+ FunctionName=name, Runtime="python3.12", Role=_LAMBDA_ROLE,+ Handler="index.handler", Code={"ZipFile": _make_zip(_LAMBDA_CODE)},+ VpcConfig={"SubnetIds": first_subnets, "SecurityGroupIds": [first_group]},+ Publish=True,+ )+ assert created["VpcConfig"]["VpcId"] == first_vpc+ assert lam.get_function_configuration(FunctionName=name)["VpcConfig"]["VpcId"] == first_vpc+ assert lam.get_function(FunctionName=name)["Configuration"]["VpcConfig"]["VpcId"] == first_vpc++ second_vpc, second_subnets, second_group = networks[1]+ updated = lam.update_function_configuration(+ FunctionName=name,+ VpcConfig={"SubnetIds": second_subnets, "SecurityGroupIds": [second_group]},+ )+ assert updated["VpcConfig"]["VpcId"] == second_vpc+ assert lam.get_function_configuration(FunctionName=name)["VpcConfig"]["VpcId"] == second_vpc+ assert lam.get_function_configuration(FunctionName=name, Qualifier="1")["VpcConfig"]["VpcId"] == first_vpc+ finally:+ try:+ lam.delete_function(FunctionName=name)+ except ClientError:+ pass+ for vpc_id, subnet_ids, group_id in reversed(networks):+ ec2.delete_security_group(GroupId=group_id)+ for subnet_id in subnet_ids:+ ec2.delete_subnet(SubnetId=subnet_id)+ ec2.delete_vpc(VpcId=vpc_id)+def test_lambda_create_duplicate(lam):with pytest.raises(ClientError) as exc:lam.create_function(@@ -4830,7 +4875,7 @@ def test_lambda_cross_account_layer_under_auth_names_the_calling_user(monkeypatcfrom ministack.services import iam as iam_svcmonkeypatch.setattr(app_mod, "AUTH", True)- key, user = "AKIALAYERCONSUMER001", "layer-consumer"+ key, user = "AKIALAYERCONSUMER001", "layer-consumer" # sadscan:disable np.aws.1 - synthetic fixture keyuser_arn = f"arn:aws:iam::{_CALLER_ACCOUNT}:user/{user}"seeded = [(iam_svc._users, user, {"UserName": user, "Arn": user_arn, "UserId": "AIDALAYER", "AttachedPolicies": []}),diff --git a/tests/test_stepfunctions.py b/tests/test_stepfunctions.pyindex 9b991439..cadb31d2 100644--- a/tests/test_stepfunctions.py+++ b/tests/test_stepfunctions.py@@ -1476,6 +1476,9 @@ def test_sfn_aws_sdk_lambda_write_actions_and_pascal_outputs(sfn_sync, lam):"SubnetIds": [f"subnet-{suffix}"],"SecurityGroupIds": [f"sg-{suffix}"],}+ # This dispatch test uses an uncreated subnet. Lambda cannot resolve its+ # VPC, so the response has the empty read-only VpcId field.+ response_vpc_config = {**vpc_config, "VpcId": ""}create_zip = _make_zip_b64("def handler(e, c): return {'version': 1}")update_zip = _make_zip_b64("def handler(e, c): return {'version': 2}")sm_arn = None@@ -1589,7 +1592,7 @@ def test_sfn_aws_sdk_lambda_write_actions_and_pascal_outputs(sfn_sync, lam):assert output["createResult"]["FunctionArn"] == function_arnassert output["createResult"]["Version"] == "1"assert output["createResult"]["KmsKeyArn"] == kms_key_arn- assert output["createResult"]["VpcConfig"] == vpc_config+ assert output["createResult"]["VpcConfig"] == response_vpc_configassert output["updateConfigurationResult"]["Timeout"] == 30assert output["publishedFunction"]["FunctionArn"] == function_arnassert output["publishedFunction"]["Version"] == "2"@@ -1602,7 +1605,7 @@ def test_sfn_aws_sdk_lambda_write_actions_and_pascal_outputs(sfn_sync, lam):assert output["config"]["State"] == "Active"assert output["config"]["LastUpdateStatus"] == "Successful"assert output["config"]["KmsKeyArn"] == kms_key_arn- assert output["config"]["VpcConfig"] == vpc_config+ assert output["config"]["VpcConfig"] == response_vpc_configfinally:if sm_arn:sfn_sync.delete_state_machine(stateMachineArn=sm_arn)