diff --git a/moto/ec2/models.py b/moto/ec2/models.py index 64d9e02f2..89e25ba9c 100644 --- a/moto/ec2/models.py +++ b/moto/ec2/models.py @@ -286,6 +286,7 @@ class Instance(BotoInstance, TaggedEC2Resource): self.user_data = user_data self.security_groups = security_groups self.instance_type = kwargs.get("instance_type", "m1.small") + self.vpc_id = None self.subnet_id = kwargs.get("subnet_id") self.key_name = kwargs.get("key_name") self.source_dest_check = "true" @@ -309,6 +310,10 @@ class Instance(BotoInstance, TaggedEC2Resource): # string will have a "u" prefix -- need to get rid of it self.user_data[0] = self.user_data[0].encode('utf-8') + if self.subnet_id: + subnet = ec2_backend.get_subnet(self.subnet_id) + self.vpc_id = subnet.vpc_id + self.prep_nics(kwargs.get("nics", {}), subnet_id=kwargs.get("subnet_id",None), private_ip=kwargs.get("private_ip",None), diff --git a/moto/ec2/utils.py b/moto/ec2/utils.py index 9a91299b8..d5fba9d5f 100644 --- a/moto/ec2/utils.py +++ b/moto/ec2/utils.py @@ -274,6 +274,7 @@ filter_dict_attribute_mapping = { 'instance-id': 'id', 'state-reason-code': '_state_reason.code', 'source-dest-check': 'source_dest_check', + 'vpc-id': 'vpc_id', } def get_instance_value(instance, instance_attr): diff --git a/tests/test_ec2/test_instances.py b/tests/test_ec2/test_instances.py index f7b0ceaca..ec404b641 100644 --- a/tests/test_ec2/test_instances.py +++ b/tests/test_ec2/test_instances.py @@ -171,6 +171,30 @@ def test_get_instances_filtering_by_source_dest_check(): source_dest_check_true[0].instances[0].id.should.equal(instance2.id) +@mock_ec2 +def test_get_instances_filtering_by_vpc_id(): + conn = boto.connect_vpc('the_key', 'the_secret') + vpc1 = conn.create_vpc("10.0.0.0/16") + subnet1 = conn.create_subnet(vpc1.id, "10.0.0.0/27") + reservation1 = conn.run_instances('ami-1234abcd', min_count=1, subnet_id=subnet1.id) + instance1 = reservation1.instances[0] + + vpc2 = conn.create_vpc("10.1.0.0/16") + subnet2 = conn.create_subnet(vpc2.id, "10.1.0.0/27") + reservation2 = conn.run_instances('ami-1234abcd', min_count=1, subnet_id=subnet2.id) + instance2 = reservation2.instances[0] + + reservations1 = conn.get_all_instances(filters={'vpc-id': vpc1.id}) + reservations1.should.have.length_of(1) + reservations1[0].instances.should.have.length_of(1) + reservations1[0].instances[0].id.should.equal(instance1.id) + + reservations2 = conn.get_all_instances(filters={'vpc-id': vpc2.id}) + reservations2.should.have.length_of(1) + reservations2[0].instances.should.have.length_of(1) + reservations2[0].instances[0].id.should.equal(instance2.id) + + @mock_ec2 def test_get_instances_filtering_by_tag(): conn = boto.connect_ec2()