How to Mock ELB Target Health Status in Python
Simulate AWS Elastic Load Balancer target health checks with a Python dict that mutates status and healthy host counts.
Python code
26 linesfrom random import randint
def elb_target_mock_status(target_id, healthy=True):
targets = {
1: {"Id": "i-001", "Status": "healthy", "Port": 80, "HealthyHostCount": 1},
2: {"Id": "i-002", "Status": "unhealthy", "Port": 80, "HealthyHostCount": 0},
3: {"Id": "i-003", "Status": "healthy", "Port": 443, "HealthyHostCount": 1},
}
target = targets.get(target_id)
if not target:
return None
if healthy and target["Status"] == "unhealthy":
target["Status"] = "healthy"
target["HealthyHostCount"] = 1
elif not healthy and target["Status"] == "healthy":
target["Status"] = "unhealthy"
target["HealthyHostCount"] = 0
return target
if __name__ == "__main__":
# Simulate a health check cycle
for target_id in [1, 2, 3]:
# Randomly flip health status for demo
status_healthy = bool(randint(0, 1))
result = elb_target_mock_status(target_id, healthy=status_healthy)
print(f"Target {target_id}: {result}")
Output
Target 1: {'Id': 'i-001', 'Status': 'healthy', 'Port': 80, 'HealthyHostCount': 1}
Target 2: {'Id': 'i-002', 'Status': 'healthy', 'Port': 80, 'HealthyHostCount': 1}
Target 3: {'Id': 'i-003', 'Status': 'unhealthy', 'Port': 443, 'HealthyHostCount': 0}
How it works
The elb_target_mock_status function mimics ELB health check behavior by storing target metadata in a dictionary keyed by target ID. When a target is marked healthy, it updates the Status to 'healthy' and sets HealthyHostCount to 1, and vice versa. Using .get() avoids KeyError for missing IDs and returns None. The if __name__ == '__main__' block runs a demo cycle that randomly flips statuses to show mutation. This pattern is useful for local testing of ELB integration code without AWS.
Common mistakes
- Not using `.get()` and crashing on missing target IDs.
- Forgetting to update both Status and HealthyHostCount together.
- Modifying the original dict unintentionally when using it in other code.
Variations
- Use a dataclass to represent target metadata instead of a dict.
- Wrap the mock in a class to manage state across multiple calls.
Real-world use cases
- Unit testing custom ELB target registration logic without hitting AWS APIs.
- Simulating health check flapping in integration tests for autoscaling policies.
- Developing a local dashboard that visualizes target health state changes.
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.