diff --git a/moto/ec2/models.py b/moto/ec2/models.py index 901014b4d..e22ccb7d2 100644 --- a/moto/ec2/models.py +++ b/moto/ec2/models.py @@ -602,7 +602,6 @@ class Instance(TaggedEC2Resource, BotoInstance, CloudFormationModel): self.instance_type = kwargs.get("instance_type", "m1.small") self.region_name = kwargs.get("region_name", "us-east-1") placement = kwargs.get("placement", None) - self.vpc_id = None self.subnet_id = kwargs.get("subnet_id") in_ec2_classic = not bool(self.subnet_id) self.key_name = kwargs.get("key_name") @@ -646,7 +645,6 @@ class Instance(TaggedEC2Resource, BotoInstance, CloudFormationModel): if self.subnet_id: subnet = ec2_backend.get_subnet(self.subnet_id) - self.vpc_id = subnet.vpc_id self._placement.zone = subnet.availability_zone if self.associate_public_ip is None: @@ -666,6 +664,15 @@ class Instance(TaggedEC2Resource, BotoInstance, CloudFormationModel): associate_public_ip=self.associate_public_ip, ) + @property + def vpc_id(self): + if self.subnet_id: + subnet = self.ec2_backend.get_subnet(self.subnet_id) + return subnet.vpc_id + if self.nics and 0 in self.nics: + return self.nics[0].subnet.vpc_id + return None + def __del__(self): try: subnet = self.ec2_backend.get_subnet(self.subnet_id) diff --git a/moto/packages/boto/ec2/instance.py b/moto/packages/boto/ec2/instance.py index 38da9b9f6..0bda6691f 100644 --- a/moto/packages/boto/ec2/instance.py +++ b/moto/packages/boto/ec2/instance.py @@ -178,7 +178,6 @@ class Instance(TaggedEC2Object): self.spot_instance_request_id = None self.subnet_id = None self.lifecycle = None - self.vpc_id = None self.private_ip_address = None self.ip_address = None self.requester_id = None diff --git a/tests/test_ec2/test_instances.py b/tests/test_ec2/test_instances.py index 471321193..9e84e389a 100644 --- a/tests/test_ec2/test_instances.py +++ b/tests/test_ec2/test_instances.py @@ -3107,6 +3107,30 @@ def test_describe_instances_dryrun(): ) +@mock_ec2 +def test_describe_instances_filter_vpcid_via_networkinterface(): + vpc_cidr_block = "10.26.0.0/16" + subnet_cidr_block = "10.26.1.0/24" + ec2 = boto3.resource("ec2", region_name="eu-west-1") + vpc = ec2.create_vpc(CidrBlock=vpc_cidr_block) + subnet = ec2.create_subnet( + VpcId=vpc.id, CidrBlock=subnet_cidr_block, AvailabilityZone="eu-west-1a" + ) + my_interface = { + "SubnetId": subnet.id, + "DeviceIndex": 0, + "PrivateIpAddresses": [{"Primary": True, "PrivateIpAddress": "10.26.1.3"},], + } + instance = ec2.create_instances( + ImageId="myami", NetworkInterfaces=[my_interface], MinCount=1, MaxCount=1 + )[0] + + _filter = [{"Name": "vpc-id", "Values": [vpc.id,]}] + found = list(ec2.instances.filter(Filters=_filter)) + found.should.have.length_of(1) + found.should.equal([instance]) + + def retrieve_all_reservations(client, filters=[]): # pylint: disable=W0102 resp = client.describe_instances(Filters=filters) all_reservations = resp["Reservations"]