How to mock EC2 describe-instances tag filtering in Python

Simulate AWS EC2 describe-instances with tag-based filtering using a mock dataset and conditional list comprehension.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 15 views 0 copies

Python code

31 lines
Python 3.9+
import json
from datetime import datetime, timezone


def mock_describe_instances(tag_key: str, tag_value: str) -> list[dict]:
    """Simulate EC2 describe-instances with tag filtering."""
    all_instances = [
        {"InstanceId": "i-0abc123", "State": "running", "Tags": [{"Key": "Name", "Value": "web-server"}, {"Key": "Env", "Value": "prod"}]},
        {"InstanceId": "i-0def456", "State": "stopped", "Tags": [{"Key": "Name", "Value": "db-server"}, {"Key": "Env", "Value": "dev"}]},
        {"InstanceId": "i-0ghi789", "State": "running", "Tags": [{"Key": "Name", "Value": "cache-server"}, {"Key": "Env", "Value": "prod"}]},
    ]

    filtered = [
        inst for inst in all_instances
        if any(tag["Key"] == tag_key and tag["Value"] == tag_value for tag in inst["Tags"])
    ]

    return [
        {
            "InstanceId": inst["InstanceId"],
            "State": inst["State"],
            "TagValue": next(tag["Value"] for tag in inst["Tags"] if tag["Key"] == tag_key),
            "FilteredAt": datetime.now(timezone.utc).isoformat(),
        }
        for inst in filtered
    ]


if __name__ == "__main__":
    result = mock_describe_instances("Env", "prod")
    print(json.dumps(result, indent=2))

Output

stdout
[
  {
    "InstanceId": "i-0abc123",
    "State": "running",
    "TagValue": "prod",
    "FilteredAt": "2025-01-01T12:00:00.000000+00:00"
  },
  {
    "InstanceId": "i-0ghi789",
    "State": "running",
    "TagValue": "prod",
    "FilteredAt": "2025-01-01T12:00:00.000000+00:00"
  }
]

How it works

The function accepts a tag key and value, then loops through a mock list of EC2 instances. The any() generator checks if any tag matches both key and value, filtering only matching instances. A second list comprehension extracts only the fields you need, looking up the tag value with next() on the filtered tags. The datetime.now(timezone.utc) call adds a UTC timestamp, keeping the mock realistic. Returning a list of dicts keeps it easy to extend into a real boto3 response.

Common mistakes

  • Assuming every instance has the tag key, causing `next()` to raise StopIteration.
  • Comparing tag Key/Value with case sensitivity when AWS is case-insensitive.
  • Forgetting that `datetime.now(timezone.utc)` is naive if you omit timezone, creating ambiguous timestamps.

Variations

  1. Use a dict comprehension to build a lookup of tag key/value pairs for faster checks.
  2. Implement the same mock with a filter lambda, like `filter(lambda i: any(...), all_instances)`.

Real-world use cases

  • Unit-testing functions that rely on EC2 tag metadata without making live AWS calls.
  • Developing CI/CD scripts that need to target instances by environment tags locally.
  • Building reusable cloud resource inventory tools before deploying to real AWS APIs.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.