cloud

Build an EKS IP Exhaustion Agent: Find Subnets Running Out of Addresses, Measure VPC CNI Warm-Pool Waste, and Ship WARM_IP_TARGET Fixes as Terraform PRs

Build an EKS IP exhaustion agent: forecast subnet free IPs, measure VPC CNI warm-pool waste per node, and ship WARM_IP_TARGET fixes as reviewed Terraform PRs.

November 29, 2026·11 min read·
#ai#aws#kubernetes#cloud#automation#sre#reliability#terraform#devops

What This Agent Does

An EKS IP exhaustion agent answers three questions for every subnet your cluster uses: how many free addresses are left, who is holding the ones that are gone, and how many of those are attached to nodes but not assigned to any pod. It reads AvailableIpAddressCount from EC2, groups every network interface in the subnet by owner, joins that with the VPC CNI's own Prometheus metrics, and assigns each subnet one finding. For the most common finding, warm-pool hoarding, it opens a Terraform pull request that sets WARM_IP_TARGET and MINIMUM_IP_TARGET on the vpc-cni add-on. It never calls a write API on EC2 or EKS.

The reason to build it: EKS subnet IP exhaustion looks like a capacity problem and is usually a configuration problem. With default settings the VPC CNI keeps one whole spare ENI of addresses on every node. On large instance types that is 30 addresses per node sitting idle, and a cluster can fill a /22 while running a few hundred pods. The first symptom is a pod stuck with failed to assign an IP address to container, which the ContainerCreating troubleshooting guide covers after the fact. This agent exists so you see it three weeks earlier.

Where the Addresses Go: A Worked Example

Take 40 m5.4xlarge nodes averaging 22 pods each, spread over three /22 subnets. AWS reserves 5 addresses per subnet, so you have 3 x 1,019 = 3,057 usable addresses.

An m5.4xlarge supports 8 ENIs with 30 IPv4 addresses each. The CNI default is WARM_ENI_TARGET=1: always keep one fully free ENI attached. So each node holds:

  • ENI 1: 30 addresses (the node's own IP plus 29 pod slots, 22 in use)
  • ENI 2: 30 addresses, all idle, because the warm target demands a spare ENI

That is 60 addresses per node and 2,400 across the cluster, for 880 pods. The subnets are 78% consumed and the cluster is using 37% of what it holds. Add a rolling node upgrade that surges 10 extra nodes and you are at 98%.

With WARM_IP_TARGET=5 and MINIMUM_IP_TARGET=25, the same node holds 22 + 5 = 27 pod addresses plus its own, 28 total. The cluster drops to 1,120 addresses and gets 1,280 back without touching the VPC.

The Five Findings

FindingEvidenceFixAgent action
Warm-pool hoardingIdle CNI addresses above 30% of attachedWARM_IP_TARGET + MINIMUM_IP_TARGETTerraform PR
AZ skewOne subnet under 15% free, siblings above 50%Rebalance node groups, widen subnet selectorsReport, PR for Karpenter EC2NodeClass only
Non-cluster consumersLambda, VPC endpoints, ELBs hold over 25% of used addressesMove them or the nodes to other subnetsReport only
Genuinely fullIdle share low, pods really use the spaceSecondary CIDR with custom networkingReport only
Fragmented for prefixesPrefix delegation on, InsufficientCidrBlocks in ipamd logsSubnet CIDR reservation, fresh subnetsReport only

Only the first row is a config change that is safe to automate as a PR. The rest change the network layout and need a human who knows what is routed where.

Step 1: Snapshot Subnets and Attribute Every ENI

AvailableIpAddressCount tells you how much is left. describe-network-interfaces tells you who took the rest. Start by hand so you know what your account looks like:

aws ec2 describe-subnets \
  --filters "Name=tag:kubernetes.io/cluster/prod,Values=shared,owned" \
  --query 'Subnets[].[SubnetId,AvailabilityZone,CidrBlock,AvailableIpAddressCount]' \
  --output table

aws ec2 describe-network-interfaces \
  --filters "Name=subnet-id,Values=subnet-0abc123" \
  --query 'NetworkInterfaces[].[InterfaceType,RequesterId,Description]' \
  --output text | sort | uniq -c | sort -rn | head

The collector does the same thing and counts addresses per owner. An ENI's cost in addresses is its private IPs plus 16 for every /28 prefix assigned to it.

# ipagent/collect.py
import boto3

ec2 = boto3.client("ec2")

def subnets(cluster: str) -> list[dict]:
    resp = ec2.describe_subnets(Filters=[{
        "Name": f"tag:kubernetes.io/cluster/{cluster}",
        "Values": ["shared", "owned"]}])
    return resp["Subnets"]

def owner(eni: dict, node_instance_ids: set[str]) -> str:
    desc = eni.get("Description", "")
    itype = eni.get("InterfaceType", "")
    instance = eni.get("Attachment", {}).get("InstanceId")
    if instance in node_instance_ids:
        return "eks_node"
    if instance:
        return "other_ec2"
    if itype == "lambda" or desc.startswith("AWS Lambda VPC ENI"):
        return "lambda"
    if itype == "vpc_endpoint":
        return "vpc_endpoint"
    if desc.startswith("ELB ") or itype.endswith("load_balancer"):
        return "load_balancer"
    if itype == "nat_gateway":
        return "nat_gateway"
    if desc.startswith("RDSNetworkInterface"):
        return "rds"
    if desc.startswith("Amazon EKS"):
        return "eks_control_plane"
    return "unknown"

def usage_by_owner(subnet_id: str, node_instance_ids: set[str]) -> dict[str, int]:
    out: dict[str, int] = {}
    pages = ec2.get_paginator("describe_network_interfaces").paginate(
        Filters=[{"Name": "subnet-id", "Values": [subnet_id]}])
    for page in pages:
        for eni in page["NetworkInterfaces"]:
            ips = len(eni.get("PrivateIpAddresses", []))
            ips += 16 * len(eni.get("Ipv4Prefixes", []))
            key = owner(eni, node_instance_ids)
            out[key] = out.get(key, 0) + ips
    return out

node_instance_ids comes from the cluster, by parsing spec.providerID on every Node. Matching on instance ID is more reliable than matching the aws-K8S- description prefix, because the node's primary ENI carries pod addresses too and has no CNI description.

Description strings are not a stable API. Anything that falls through lands in unknown, and the report prints the raw descriptions for that bucket so you can add a rule.

Step 2: Measure Warm-Pool Waste from ipamd

The CNI's aws-node DaemonSet exposes Prometheus metrics on port 61678. If you do not scrape it yet, add a PodMonitor for the aws-node pods in kube-system first. Confirm the metric names against your CNI version:

kubectl -n kube-system port-forward ds/aws-node 61678:61678 &
curl -s localhost:61678/metrics | grep -E '^awscni_(total_ip|assigned_ip|eni_allocated|ip_max)'

Three queries carry the analysis:

# Addresses attached to nodes but not assigned to pods
sum(awscni_total_ip_addresses) - sum(awscni_assigned_ip_addresses)

# Idle share per node, worst first
topk(20, 1 - (awscni_assigned_ip_addresses / awscni_total_ip_addresses))

# EC2 API errors from the CNI, the thing to watch after tightening warm targets
sum(rate(awscni_aws_api_error_count[10m])) by (api, error)

For sizing the fix, the agent also pulls per-node pod counts over 14 days: the p50 for the floor and the largest 5-minute increase for the buffer.

quantile_over_time(0.5, awscni_assigned_ip_addresses[14d])
max_over_time(delta(awscni_assigned_ip_addresses[5m])[14d:5m])

Step 3: Forecast on the Daily Minimum

Averages hide the moment that hurts. Free addresses dip during deploys, node upgrades, and scale-ups, so the collector samples every 5 minutes and the forecast runs on each day's minimum.

# ipagent/forecast.py
def days_to_exhaustion(daily_min_free: list[int], floor: int) -> float | None:
    n = len(daily_min_free)
    if n < 7:
        return None
    xs = range(n)
    mx, my = (n - 1) / 2, sum(daily_min_free) / n
    slope = sum((x - mx) * (y - my) for x, y in zip(xs, daily_min_free)) \
        / sum((x - mx) ** 2 for x in xs)
    if slope >= 0:
        return None
    return max(0.0, (daily_min_free[-1] - floor) / -slope)

floor is not zero. Reserve room for one surge: the largest node group's maxSurge multiplied by the addresses a new node grabs on boot, plus 8 per subnet that hosts an Application Load Balancer, since ALBs need free addresses to scale. The same approach drives the node and PVC forecasts in the capacity planning agent. Subnet space is the fourth resource that agent does not watch.

Step 4: Classify in Code, Not in the Prompt

The finding is deterministic. The model never decides whether a subnet is in trouble.

# ipagent/classify.py
def classify(s: dict) -> str:
    used = s["total"] - s["free"]
    node_ips = s["by_owner"].get("eks_node", 0)
    foreign = used - node_ips - s["by_owner"].get("eks_control_plane", 0)
    idle = s["cni_total"] - s["cni_assigned"]

    if s["free"] / s["total"] > 0.40 and s["days_left"] is None:
        return "healthy"
    if s["prefix_delegation"] and s["insufficient_cidr_blocks"] > 0:
        return "prefix_fragmented"
    if s["cni_total"] and idle / s["cni_total"] > 0.30:
        return "warm_pool_hoarding"
    if used and foreign / used > 0.25:
        return "non_cluster_consumers"
    if s["sibling_max_free_ratio"] > 0.50:
        return "az_skew"
    return "genuinely_full"

Order matters. Hoarding is checked before everything except fragmentation because it is the cheapest fix and it often makes the other findings disappear.

Step 5: The Model Sizes the Fix and Writes the PR

The model gets one finding at a time with its evidence and must answer through a single tool. The schema leaves little room to invent:

{
  "name": "propose_cni_settings",
  "description": "Propose VPC CNI warm-pool settings for one cluster. Only for warm_pool_hoarding findings.",
  "input_schema": {
    "type": "object",
    "properties": {
      "warm_ip_target": {"type": "integer", "minimum": 2, "maximum": 15},
      "minimum_ip_target": {"type": "integer", "minimum": 0, "maximum": 110},
      "expected_ips_released": {"type": "integer"},
      "risk": {"type": "string", "enum": ["low", "medium"]},
      "reasoning": {"type": "string"},
      "evidence_refs": {"type": "array", "items": {"type": "string"}}
    },
    "required": ["warm_ip_target", "minimum_ip_target", "expected_ips_released", "risk", "evidence_refs"]
  }
}

The system prompt carries the sizing rules:

You size VPC CNI warm-pool settings from measured data. Rules:
- minimum_ip_target = p50 pods per node over 14 days, rounded up to the next 5.
- warm_ip_target = largest 5-minute pod increase on any node, minimum 2.
- If pod churn exceeds 50 pod starts per node per hour, set risk=medium and say
  that EC2 API throttling is possible.
- Never propose ENABLE_PREFIX_DELEGATION. It raises pod density, it does not
  save addresses, and a sparse node holds 16 to 32 addresses under it.
- Every number you state must come from the evidence block. Cite the key.

The code then recomputes expected_ips_released from the metrics and rejects the proposal if the model's figure is off by more than 10%. The PR edits the add-on resource:

resource "aws_eks_addon" "vpc_cni" {
  cluster_name = aws_eks_cluster.prod.name
  addon_name   = "vpc-cni"

  configuration_values = jsonencode({
    env = {
      WARM_IP_TARGET    = "5"
      MINIMUM_IP_TARGET = "25"
    }
  })
}

Setting either variable overrides WARM_ENI_TARGET. Do it through the add-on configuration, not kubectl set env daemonset aws-node, because a managed add-on update reverts hand edits. The PR body lists the per-subnet before and after counts, the two PromQL queries a reviewer can run, and the rollback, which is deleting the two lines. The reasons to route this through a PR at all are in GitOps for AI agents.

Guardrails

  • Read-only IAM. The role has ec2:DescribeSubnets, ec2:DescribeNetworkInterfaces, ec2:DescribeVpcs, and eks:DescribeAddon. Nothing else. The Kubernetes side is get and list on nodes.
  • One cluster per PR, one PR open at a time. A second proposal waits until the first is merged or closed.
  • Post-merge watch. For 48 hours after the add-on updates, the agent checks awscni_aws_api_error_count and pod startup latency. If throttling errors rise above the pre-change baseline, it opens a follow-up PR raising MINIMUM_IP_TARGET, since a higher floor means fewer incremental AssignPrivateIpAddresses calls.
  • No network-layout PRs. Secondary CIDRs, new subnets, and custom networking are report-only. They require replacing nodes and they change which source addresses your peers and firewalls see.
  • Bounded values. The schema caps warm_ip_target at 15. Past that you are back to hoarding and the PR has no point.

What the Report Looks Like

EKS subnet IP report: cluster prod (3 subnets, 14d history)

subnet-0a1 us-east-1a /22  free  212 (21%)  min 96   ~19 days to floor  warm_pool_hoarding
subnet-0b2 us-east-1b /22  free  248 (24%)  min 131  ~26 days to floor  warm_pool_hoarding
subnet-0c3 us-east-1c /22  free  197 (19%)  min 74   ~15 days to floor  warm_pool_hoarding

Holders (all subnets): eks_node 2,400 | load_balancer 24 | vpc_endpoint 9 | unknown 3
CNI: 2,400 attached, 880 assigned to pods, 1,520 idle (63%)

Proposal: WARM_IP_TARGET=5, MINIMUM_IP_TARGET=25
  expected release: ~1,280 addresses, risk low (peak churn 11 pod starts/node/h)
  PR: infra#2291

Honest Limits

  • Tight warm targets trade addresses for API calls. With WARM_IP_TARGET set, the CNI calls EC2 every time the buffer drains. On clusters with heavy pod churn, such as batch or CI runners, that can hit EC2 rate limits and slow pod startup. MINIMUM_IP_TARGET absorbs most of it, and some clusters should stay on the default and get more address space instead. API throttling is account-wide, so check headroom with the AWS service quota agent if you run many clusters in one account.
  • Linear forecasts miss step changes. A new node group or a team onboarding 200 pods does not show up in a trend line. The floor calculation covers one surge, not a launch.
  • Released addresses come back gradually. After the change, ipamd frees secondary addresses and detaches empty ENIs over the following minutes, and only when an ENI has no pods left on it. A node with pods scattered across two ENIs keeps both until pods churn. Expect the full number after the next node rotation.
  • Genuinely full needs a network change. The standard answer is a secondary CIDR from 100.64.0.0/10 with CNI custom networking and one ENIConfig per AZ. Pods move to the new range and nodes keep the old one. It costs one ENI of pod capacity per node and requires node replacement, which is why the agent stops at a report.
  • Karpenter hides AZ skew until it does not. Karpenter launches into the subnet with the most free addresses among those the EC2NodeClass selects, which balances things as long as zonal constraints allow it. Workloads pinned to one AZ by volume affinity defeat that, and the Spot with Karpenter guide has the same problem from the capacity side.

Run the collector and report for two weeks before enabling PRs. On most clusters the first report shows more than half of the attached addresses idle, and that one number settles whether you need a bigger VPC or two environment variables.

#ai#aws#kubernetes#cloud#automation#sre#reliability#terraform#devops
D
DevToCashAuthor

Senior DevOps/SRE Engineer · 10+ years · Professional Trader (IDX, Crypto, US Equities)

I write about real infrastructure patterns and trading strategies I use in production and in live markets. No courses, no affiliate hype — just documentation of what actually works.

More about me →