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.
Python code
31 linesimport 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
[
{
"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
- Use a dict comprehension to build a lookup of tag key/value pairs for faster checks.
- 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
More from Cloud + Python
- Build a URL Shortener Client with Python medium
- Create a Cloud Storage Helper Class in Python easy
- Create a Data Helper Class for Beginners in Python easy
- Cross Account Role Chaining Mock Credentials in Python medium
- Exponential Backoff with Jitter for Cloud API Calls in Python medium
- Generate Mock CloudFormation Stack Events in Python easy
Keep learning
Related tutorials and quizzes for this topic.