from __future__ import annotations
from typing import Any, Dict, List
import boto3
from botocore.exceptions import ClientError
def collect_elbv2_region(session: boto3.Session, region: str) -> Dict[str, Any]:
elb = session.client("elbv2", region_name=region)
load_balancers: List[Dict[str, Any]] = []
target_groups: List[Dict[str, Any]] = []
target_health: List[Dict[str, Any]] = []
try:
lb_p = elb.get_paginator("describe_load_balancers")
for page in lb_p.paginate():
for lb in page.get("LoadBalancers", []):
load_balancers.append(
{
"load_balancer_arn": lb.get("LoadBalancerArn"),
"name": lb.get("LoadBalancerName"),
"type": lb.get("Type"),
"scheme": lb.get("Scheme"),
"state": (lb.get("State") or {}).get("Code"),
"dns_name": lb.get("DNSName"),
"vpc_id": lb.get("VpcId"),
}
)
tg_p = elb.get_paginator("describe_target_groups")
for page in tg_p.paginate():
for tg in page.get("TargetGroups", []):
tg_arn = tg.get("TargetGroupArn")
target_groups.append(
{
"target_group_arn": tg_arn,
"name": tg.get("TargetGroupName"),
"protocol": tg.get("Protocol"),
"port": tg.get("Port"),
"vpc_id": tg.get("VpcId"),
"target_type": tg.get("TargetType"),
}
)
if tg_arn:
th = elb.describe_target_health(TargetGroupArn=tg_arn)
for desc in th.get("TargetHealthDescriptions", []):
target_health.append(
{
"target_group_arn": tg_arn,
"target": desc.get("Target"),
"health": (desc.get("TargetHealth") or {}).get("State"),
"reason": (desc.get("TargetHealth") or {}).get("Reason"),
}
)
except ClientError as e:
return {"region": region, "error": str(e), "load_balancers": [], "target_groups": [], "target_health": []}
return {"region": region, "load_balancers": load_balancers, "target_groups": target_groups, "target_health": target_health}