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.

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

Python code

26 lines
Python 3.9+
from 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

stdout
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

  1. Use a dataclass to represent target metadata instead of a dict.
  2. 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

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.