Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

Fix EC2 instance tag filters (#425)

Constantin Gavrilescua11ae0d0b04d
diff --git a/ministack/services/ec2.py b/ministack/services/ec2.py
index d9d0fcef..336224b3 100644
--- a/ministack/services/ec2.py
+++ b/ministack/services/ec2.py
@@ -63,8 +63,8 @@ import time
from urllib.parse import parse_qs
from xml.sax.saxutils import escape as _esc
-from ministack.core.persistence import load_state, PERSIST_STATE
-from ministack.core.responses import AccountScopedDict, get_account_id, new_uuid, get_region
+from ministack.core.persistence import PERSIST_STATE, load_state
+from ministack.core.responses import AccountScopedDict, get_account_id, get_region, new_uuid
logger = logging.getLogger("ec2")
@@ -2279,6 +2279,7 @@ def _parse_filters(params):
def _matches_filters(inst, filters):
+ tag_list = _tags.get(inst["InstanceId"], [])
for name, vals in filters.items():
if name == "instance-state-name":
if inst["State"]["Name"] not in vals:
@@ -2289,6 +2290,14 @@ def _matches_filters(inst, filters):
elif name == "image-id":
if inst["ImageId"] not in vals:
return False
+ elif name.startswith("tag:"):
+ tag_key = name[4:]
+ tag_val = next((t["Value"] for t in tag_list if t["Key"] == tag_key), None)
+ if tag_val not in vals:
+ return False
+ elif name == "tag-key":
+ if not any(t["Key"] in vals for t in tag_list):
+ return False
return True
diff --git a/tests/test_ec2.py b/tests/test_ec2.py
index 84ecc475..afd1a665 100644
--- a/tests/test_ec2.py
+++ b/tests/test_ec2.py
@@ -2,11 +2,13 @@ import io
import json
import os
import time
+import uuid as _uuid_mod
import zipfile
from urllib.parse import urlparse
+
import pytest
from botocore.exceptions import ClientError
-import uuid as _uuid_mod
+
def test_ec2_describe_vpcs_default(ec2):
resp = ec2.describe_vpcs()
@@ -229,6 +231,33 @@ def test_ec2_tags_crud(ec2):
ec2.terminate_instances(InstanceIds=[iid])
+
+def test_ec2_describe_instances_tag_filter_excludes_untagged(ec2):
+ owner = f"devuser-{_uuid_mod.uuid4().hex}"
+ untagged_id = ec2.run_instances(ImageId="ami-untagged", MinCount=1, MaxCount=1)["Instances"][0]["InstanceId"]
+ tagged_id = ec2.run_instances(
+ ImageId="ami-tagged",
+ MinCount=1,
+ MaxCount=1,
+ TagSpecifications=[{
+ "ResourceType": "instance",
+ "Tags": [{"Key": "PopOpsOwner", "Value": owner}],
+ }],
+ )["Instances"][0]["InstanceId"]
+
+ resp = ec2.describe_instances(Filters=[{"Name": "tag:PopOpsOwner", "Values": [owner]}])
+ ids = [
+ inst["InstanceId"]
+ for reservation in resp["Reservations"]
+ for inst in reservation["Instances"]
+ ]
+
+ assert tagged_id in ids
+ assert untagged_id not in ids
+
+ ec2.terminate_instances(InstanceIds=[untagged_id, tagged_id])
+
+
def test_ec2_modify_vpc_attribute(ec2):
vpc_id = ec2.create_vpc(CidrBlock="10.10.0.0/16")["Vpc"]["VpcId"]
ec2.modify_vpc_attribute(VpcId=vpc_id, EnableDnsSupport={"Value": True})