Mock ECS Task Run Stop Status Dict in Python
Build a mock ECS task status dictionary with RUNNING/STOPPED states using the standard library.
Python code
23 linesfrom datetime import datetime, timezone
def mock_ecs_task_status(task_id: str, state: str = "RUNNING") -> dict:
"""Return a mock ECS task status dictionary."""
return {
"taskArn": f"arn:aws:ecs:us-east-1:123456789012:task/cluster/{task_id}",
"taskDefinition": "arn:aws:ecs:us-east-1:123456789012:task-definition/my-app:42",
"lastStatus": state,
"desiredStatus": "STOPPED" if state == "STOPPED" else "RUNNING",
"clusterArn": "arn:aws:ecs:us-east-1:123456789012:cluster/my-cluster",
"startedAt": "2025-01-15T10:00:00Z",
"stoppedAt": datetime.now(timezone.utc).isoformat() if state == "STOPPED" else None,
"stopCode": "EssentialContainerExited" if state == "STOPPED" else None,
"stoppedReason": "Task stopped" if state == "STOPPED" else None,
}
if __name__ == "__main__":
running = mock_ecs_task_status("task-abc", "RUNNING")
stopped = mock_ecs_task_status("task-def", "STOPPED")
print("Running:", running)
print("Stopped:", stopped)
Output
Running: {'taskArn': 'arn:aws:ecs:us-east-1:123456789012:task/cluster/task-abc', 'taskDefinition': 'arn:aws:ecs:us-east-1:123456789012:task-definition/my-app:42', 'lastStatus': 'RUNNING', 'desiredStatus': 'RUNNING', 'clusterArn': 'arn:aws:ecs:us-east-1:123456789012:cluster/my-cluster', 'startedAt': '2025-01-15T10:00:00Z', 'stoppedAt': None, 'stopCode': None, 'stoppedReason': None}
Stopped: {'taskArn': 'arn:aws:ecs:us-east-1:123456789012:task/cluster/task-def', 'taskDefinition': 'arn:aws:ecs:us-east-1:123456789012:task-definition/my-app:42', 'lastStatus': 'STOPPED', 'desiredStatus': 'STOPPED', 'clusterArn': 'arn:aws:ecs:us-east-1:123456789012:cluster/my-cluster', 'startedAt': '2025-01-15T10:00:00Z', 'stoppedAt': '2025-01-15T10:00:00.123456+00:00', 'stopCode': 'EssentialContainerExited', 'stoppedReason': 'Task stopped'}
How it works
The function builds a dictionary that mirrors the ECS DescribeTasks response shape, with fields like taskArn, lastStatus, and clusterArn. It uses the state parameter to conditionally set status-related fields so the dict is consistent for RUNNING versus STOPPED. datetime.now(timezone.utc).isoformat() produces a UTC timestamp in ISO 8601 format, matching AWS's API style. This makes it easy to unit-test code that consumes ECS task statuses without making real AWS calls.
Common mistakes
- Forgetting timezone-aware datetime objects, causing naive vs aware comparison errors.
- Hard-coding status fields instead of using conditionals, leading to inconsistent test data.
- Not including fields like stopCode or stoppedReason, which real EC2 describe calls return.
- Using `datetime.now()` without `timezone.utc`, giving local time that looks off in AWS logs.
Variations
- Use a dataclass to model the ECS task status and convert to dict with `asdict()`.
- Add states like 'PROVISIONING' or 'DEACTIVATING' by extending the conditionals.
Real-world use cases
- Unit-testing ECS task orchestration logic that checks `lastStatus` before scaling actions.
- Building integration test fixtures for AWS Lambda handlers that process ECS task state changes.
- Simulating ECS task lifecycle events in a local development environment without AWS calls.
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.