Amazon EKS Pod Identity: When to Replace IRSA and How to Migrate

On this page

A pod on Amazon EKS that calls AWS needs credentials, and they should belong to that workload rather than to the node it happens to run on. Since 2019 the answer has been IAM roles for service accounts (IRSA): each cluster gets an OpenID Connect provider in IAM, each role trusts that provider, and a service account annotation tells a webhook which role to inject. It works, but every new cluster means another OIDC provider and another edit to every trust policy that cluster’s workloads use.

EKS Pod Identity, launched at re:Invent in November 2023, takes the cluster out of the trust policy. Roles trust a single service principal, and the mapping from service account to role is an object in the EKS API. Two later additions changed what it can replace: target IAM roles for cross-account access in June 2025, and session policies in March 2026. This article covers how it works as of May 2026, where IRSA is still the right choice, and how to move workloads without an outage. The sample scans manifests for IRSA service accounts, flags what will break, and creates the associations.

How Pod Identity delivers credentials

EKS Pod Identity credential flow: a pod with an AWS SDK calls the Pod Identity Agent on its node at 169.254.170.23, the agent calls the EKS Auth API, which uses the Pod Identity association to assume the IAM role, optionally chains to a target role in another account, and returns credentials with session tags
The association lives in the EKS API. The agent on each node serves credentials to the pods on that node.

Three pieces are involved. The Pod Identity Agent is a DaemonSet, installed as the eks-pod-identity-agent add-on or built in on EKS Auto Mode, that listens on the link-local addresses 169.254.170.23 and fd00:ec2::23 and serves only the pods on its own node. A Pod Identity association maps a cluster, namespace and service account to one IAM role. The EKS Auth API, through AssumeRoleForPodIdentity, checks the pod’s service account token and assumes the role.

When a pod uses a service account that has an association, EKS sets environment variables in its containers that point the AWS SDK’s container credential provider at the agent. The SDK asks the agent, the agent asks EKS Auth, and the credentials come back with session tags for the cluster, namespace, service account and pod. The node role needs eks-auth:AssumeRoleForPodIdentity, which the standard worker node policy includes. Application code does not change, but the SDK must be recent enough to know the provider: for Python that means boto3 and botocore 1.34.41 or later.

The role’s trust policy is the same in every cluster and every account:

JSON15 lines
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "pods.eks.amazonaws.com"
      },
      "Action": [
        "sts:AssumeRole",
        "sts:TagSession"
      ]
    }
  ]
}
ℹ️
SESSION TAGS ARE ON BY DEFAULT

Every session carries six tags: eks-cluster-arn, eks-cluster-name, kubernetes-namespace, kubernetes-service-account, kubernetes-pod-name and kubernetes-pod-uid. They are transitive, so they follow the session into chained roles. Use them in policies as ${aws:PrincipalTag/kubernetes-namespace} to share one role between namespaces without letting them read each other’s data.

Pod Identity or IRSA

Comparison of EKS Pod Identity and IRSA on per-cluster setup, trust policy, where the mapping lives, Fargate, Windows and Outposts support, cross-account access and attribute-based access
Pod Identity is simpler to run at scale. IRSA still covers platforms Pod Identity does not.

Pod Identity runs on Linux EC2 worker nodes in EKS clusters. It does not support pods on AWS Fargate, Windows nodes, AWS Outposts, EKS Anywhere or self-managed Kubernetes on EC2, so IRSA stays for those, and the two can run side by side in one cluster. Each cluster supports up to 5,000 associations, and a service account maps to one role. IRSA’s constraint is elsewhere: every cluster needs its own IAM OIDC provider, and every trust policy names the providers it accepts, which is what becomes hard to manage across dozens of clusters and accounts.

The other difference is ownership. With IRSA, whoever can edit a service account’s annotation chooses which role a workload asks for, and the trust policy decides whether it gets it. With Pod Identity, the association is created through the EKS API, so it is governed by IAM permissions on eks:CreatePodIdentityAssociation and recorded in CloudTrail, and Kubernetes RBAC alone cannot change which role a workload receives.

Cross-account access and session policies

Before June 2025, reaching a resource in another account meant role chaining in application code or SDK configuration. An association can now name a target role in the resource account: EKS assumes the Pod Identity role and then the target role, and the pod receives the target role’s credentials. The target role trusts the Pod Identity role, and EKS supplies an external ID that the trust policy can require.

Since March 2026 an association can also carry a session policy, an inline IAM policy of up to 2,048 characters. The session gets the intersection of the role’s permissions and the session policy, so one broad role can serve several workloads with narrower rights each. Session policies cannot be combined with session tags; the association must set disableSessionTags, which also removes any ABAC conditions that depend on those tags.

⚠️
EVENTUAL CONSISTENCY

Associations are eventually consistent and can take several seconds to take effect after the API call returns. Create them in your deployment pipeline before the workload rolls out, not in a code path that needs credentials straight away, and expect pods that started before the association existed to keep the credentials they already have until they restart.

Migrating from IRSA

A migration works one service account at a time and keeps IRSA working until Pod Identity has been proven for that workload. The order matters:

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor': '#FFF3E0', 'primaryTextColor': '#232F3E', 'primaryBorderColor': '#FF9900', 'lineColor': '#232F3E', 'clusterBkg': '#F8FAFC', 'clusterBorder': '#CBD5E1', 'edgeLabelBackground': '#FFFFFF', 'nodeTextColor': '#232F3E'}}}%%
flowchart TD
    A["Scan manifests for<br/>IRSA service accounts"] --> B{"Fargate, Windows or<br/>proxy without NO_PROXY?"}
    B -- "Yes" --> C["Fix the proxy setting,<br/>or keep IRSA"]
    B -- "No" --> D["Add pods.eks.amazonaws.com<br/>to the role trust policy"]
    D --> E["Install the agent add-on<br/>(built in on Auto Mode)"]
    E --> F["Create the association"]
    F --> G["Restart pods and confirm<br/>the role with get-caller-identity"]
    G --> H["Remove the annotation<br/>and the OIDC trust statement"]
    classDef aws fill:#FFF3E0,stroke:#FF9900,stroke-width:2px,color:#232F3E
    classDef warn fill:#FEF2F2,stroke:#D13212,stroke-width:2px,color:#991B1B
    classDef ok fill:#F0FFF4,stroke:#1D8102,stroke-width:2px,color:#145202
    class A,B,D,E,F,G aws
    class C warn
    class H ok

The sample automates the first half. It reads manifests, finds service accounts with the eks.amazonaws.com/role-arn annotation and the workloads that use them, and blocks the ones that cannot move as they stand: Windows node selectors, and proxies whose NO_PROXY does not include the agent’s addresses, which would send credential requests to the proxy. It then adds the Pod Identity statement to each trust policy, keeping the OIDC statement, and creates the associations idempotently:

Python184 lines
"""Plan and apply a move from IRSA to EKS Pod Identity.

1. scan()      reads Kubernetes manifests, finds service accounts annotated for
               IRSA (eks.amazonaws.com/role-arn) and the workloads that use them,
               and flags workloads Pod Identity cannot serve as they stand.
2. trust()     adds the pods.eks.amazonaws.com statement to an IAM role's trust
               policy and keeps the IRSA statements, so both paths work during
               the migration.
3. plan() / apply()  turn the service accounts into CreatePodIdentityAssociation
               requests, optionally with a cross-account target role or a session
               policy, and create them idempotently.

Do not assume which credentials a pod uses while both IRSA and Pod Identity are
configured for its service account. After creating the association, restart the
pods, check that AWS_CONTAINER_CREDENTIALS_FULL_URI is set, confirm the identity
with `aws sts get-caller-identity`, and then remove the eks.amazonaws.com/role-arn
annotation and the OIDC statement from the role's trust policy.
"""

from __future__ import annotations

import argparse
import copy
import json
import re
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

import yaml

IRSA_ANNOTATION = "eks.amazonaws.com/role-arn"
POD_IDENTITY_STATEMENT = {
    "Sid": "EksPodIdentity",
    "Effect": "Allow",
    "Principal": {"Service": "pods.eks.amazonaws.com"},
    "Action": ["sts:AssumeRole", "sts:TagSession"],
}
AGENT_ADDRESSES = ("169.254.170.23", "fd00:ec2::23")
MIN_SDK = {"boto3": (1, 34, 41), "botocore": (1, 34, 41)}
SESSION_POLICY_LIMIT = 2048
WORKLOAD_KINDS = {"Deployment", "StatefulSet", "DaemonSet", "Job", "CronJob", "Pod"}


@dataclass
class ServiceAccount:
    namespace: str
    name: str
    role_arn: str
    workloads: list[str] = field(default_factory=list)
    blockers: list[str] = field(default_factory=list)
    warnings: list[str] = field(default_factory=list)


def _docs(paths: list[Path]):
    for path in paths:
        files = sorted(path.rglob("*.y*ml")) if path.is_dir() else [path]
        for f in files:
            for doc in yaml.safe_load_all(f.read_text(encoding="utf-8")):
                if isinstance(doc, dict) and doc.get("kind"):
                    yield doc


def _pod_spec(doc: dict[str, Any]) -> dict[str, Any]:
    spec = doc.get("spec") or {}
    if doc["kind"] == "Pod":
        return spec
    if doc["kind"] == "CronJob":
        spec = (spec.get("jobTemplate") or {}).get("spec") or {}
    return ((spec.get("template") or {}).get("spec")) or {}


def scan(paths: list[Path]) -> list[ServiceAccount]:
    docs = list(_docs(paths))
    accounts: dict[tuple[str, str], ServiceAccount] = {}
    for d in docs:
        meta = d.get("metadata") or {}
        role = (meta.get("annotations") or {}).get(IRSA_ANNOTATION)
        if d["kind"] == "ServiceAccount" and role:
            key = (meta.get("namespace", "default"), meta["name"])
            accounts[key] = ServiceAccount(key[0], key[1], role)

    for d in docs:
        if d["kind"] not in WORKLOAD_KINDS:
            continue
        meta = d.get("metadata") or {}
        pod = _pod_spec(d)
        sa = accounts.get((meta.get("namespace", "default"), pod.get("serviceAccountName", "default")))
        if not sa:
            continue
        sa.workloads.append(f"{d['kind']}/{meta.get('name')}")
        selector = pod.get("nodeSelector") or {}
        if selector.get("kubernetes.io/os") == "windows":
            sa.blockers.append(f"{d['kind']}/{meta.get('name')}: Windows nodes are not supported by Pod Identity")
        if pod.get("hostNetwork"):
            sa.warnings.append(f"{d['kind']}/{meta.get('name')}: hostNetwork pods can also reach the node's instance metadata")
        for c in pod.get("containers", []) + pod.get("initContainers", []):
            env = {e.get("name", "").upper(): str(e.get("value", "")) for e in c.get("env", []) or []}
            if (env.get("HTTPS_PROXY") or env.get("HTTP_PROXY")) and not all(
                    a in env.get("NO_PROXY", "") for a in AGENT_ADDRESSES):
                sa.blockers.append(f"{d['kind']}/{meta.get('name')}/{c.get('name')}: proxy set; add "
                                   "169.254.170.23 and fd00:ec2::23 to NO_PROXY")
    for sa in accounts.values():
        sa.warnings.append("check the namespace is not served by a Fargate profile; Fargate is not supported")
    return sorted(accounts.values(), key=lambda s: (s.namespace, s.name))


def check_sdk(requirements: str) -> list[str]:
    """Flag pinned Python SDK versions too old for the Pod Identity credential provider."""
    problems = []
    for line in requirements.splitlines():
        m = re.match(r"\s*(boto3|botocore)\s*==\s*(\d+)\.(\d+)\.(\d+)", line)
        if m and tuple(map(int, m.groups()[1:])) < MIN_SDK[m.group(1)]:
            need = ".".join(map(str, MIN_SDK[m.group(1)]))
            problems.append(f"{line.strip()}: Pod Identity needs {m.group(1)}>={need}")
    return problems


def trust(policy: dict[str, Any]) -> dict[str, Any]:
    """Return the trust policy with the Pod Identity statement added once."""
    new = copy.deepcopy(policy)
    statements = new.setdefault("Statement", [])
    if isinstance(statements, dict):
        statements = new["Statement"] = [statements]
    if not any(s.get("Principal", {}).get("Service") == "pods.eks.amazonaws.com" for s in statements):
        statements.append(copy.deepcopy(POD_IDENTITY_STATEMENT))
    return new


def plan(cluster: str, accounts: list[ServiceAccount], *, target_roles: dict[str, str] | None = None,
         session_policies: dict[str, dict[str, Any]] | None = None) -> list[dict[str, Any]]:
    """CreatePodIdentityAssociation arguments, keyed by namespace/name in the optional maps."""
    target_roles, session_policies = target_roles or {}, session_policies or {}
    requests = []
    for sa in accounts:
        if sa.blockers:
            continue
        key = f"{sa.namespace}/{sa.name}"
        req: dict[str, Any] = {"clusterName": cluster, "namespace": sa.namespace,
                               "serviceAccount": sa.name, "roleArn": sa.role_arn}
        if key in target_roles:
            req["targetRoleArn"] = target_roles[key]
        if key in session_policies:
            text = json.dumps(session_policies[key], separators=(",", ":"))
            if len(text) > SESSION_POLICY_LIMIT:
                raise ValueError(f"{key}: session policy is {len(text)} characters; the limit is {SESSION_POLICY_LIMIT}")
            req["policy"] = text
            req["disableSessionTags"] = True     # session policies and session tags cannot be combined
        requests.append(req)
    return requests


def apply(client: Any, requests: list[dict[str, Any]]) -> list[str]:
    """Create associations; an existing association for the same service account is left alone."""
    results = []
    for req in requests:
        try:
            arn = client.create_pod_identity_association(**req)["association"]["associationArn"]
            results.append(f"created {req['namespace']}/{req['serviceAccount']}: {arn}")
        except client.exceptions.ResourceInUseException:
            results.append(f"exists  {req['namespace']}/{req['serviceAccount']}")
    return results


def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser(description="Plan an IRSA to EKS Pod Identity migration")
    ap.add_argument("cluster")
    ap.add_argument("paths", nargs="+", type=Path)
    args = ap.parse_args(argv)
    accounts = scan(args.paths)
    for sa in accounts:
        state = "BLOCKED" if sa.blockers else "READY"
        print(f"{state:<8}{sa.namespace}/{sa.name} -> {sa.role_arn} ({', '.join(sa.workloads) or 'no workloads'})")
        for b in sa.blockers:
            print(f"  blocker: {b}")
        for w in sa.warnings:
            print(f"  check:   {w}")
    print(json.dumps(plan(args.cluster, accounts), indent=2))
    return 1 if any(sa.blockers for sa in accounts) else 0


if __name__ == "__main__":
    sys.exit(main())

Run against the example manifests, it finds one workload ready to move and one blocked by its proxy settings:

Bash6 lines
$ python migrate.py prod-eu examples
READY   billing/invoice-export -> arn:aws:iam::111122223333:role/invoice-export (CronJob/invoice-export)
  check:   check the namespace is not served by a Fargate profile; Fargate is not supported
BLOCKED orders/orders-api -> arn:aws:iam::111122223333:role/orders-api (Deployment/orders-api)
  blocker: Deployment/orders-api/api: proxy set; add 169.254.170.23 and fd00:ec2::23 to NO_PROXY
  check:   check the namespace is not served by a Fargate profile; Fargate is not supported

Do not assume which credentials a pod uses while both mechanisms are configured for its service account. After creating the association, restart the pods, check that AWS_CONTAINER_CREDENTIALS_FULL_URI is set in the container, and confirm the session with aws sts get-caller-identity before removing the annotation and the OIDC statement. Delete the cluster’s OIDC provider only when no role trusts it any more, and keep it while Fargate or Windows workloads still use IRSA.

Attribute-based access with session tags

Session tags let one role serve many workloads safely. This permissions policy gives each namespace its own prefix in a shared bucket and denies everything to sessions from other clusters. Because a missing tag fails StringNotEquals, the deny also applies if session tags are disabled:

JSON20 lines
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "OwnNamespacePrefixOnly",
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:PutObject"],
      "Resource": "arn:aws:s3:::shared-exports/${aws:PrincipalTag/kubernetes-namespace}/*"
    },
    {
      "Sid": "ThisClusterOnly",
      "Effect": "Deny",
      "Action": "s3:*",
      "Resource": "*",
      "Condition": {
        "StringNotEquals": {"aws:PrincipalTag/eks-cluster-name": ["prod-eu", "prod-eu-dr"]}
      }
    }
  ]
}
⚖️
AUDIT AND SEPARATION OF DUTIES

Pod Identity makes the question “which workload can use this role” answerable from the EKS API and CloudTrail instead of from annotations scattered across manifests. Restrict eks:CreatePodIdentityAssociation, eks:UpdatePodIdentityAssociation and iam:PassRole to the platform pipeline, alert on association changes in CloudTrail, and keep instance metadata limited with a hop limit of 1 so pods cannot fall back to the node role. Pods with hostNetwork: true can always reach instance metadata, so treat them as having the node role’s permissions.

📝
HOW THIS WAS CHECKED

migrate.py was tested with Python 3.13, boto3==1.42.95, pyyaml==6.0.3 and pytest==9.0.2: eight tests cover the scanner, the trust policy merge, the session policy limit and the CLI, and the EKS calls go through botocore’s Stubber, which validates them against the EKS API model in that release. The ABAC policy was checked as valid JSON, not with IAM Access Analyzer. Nothing was run against a live cluster. Feature dates are from AWS announcements and the EKS user guide.

Key takeaways

  • Pod Identity replaces per-cluster OIDC trust with one service principal and an association in the EKS API.
  • It covers Linux EC2 nodes only; keep IRSA for Fargate, Windows nodes, Outposts and EKS Anywhere.
  • Target roles (June 2025) handle cross-account access, and session policies (March 2026) narrow a shared role, at the cost of session tags.
  • Migrate one service account at a time: add the trust statement, create the association, restart, verify, then remove the annotation.
  • Use the default session tags for attribute-based access, and govern association changes as IAM changes.

Have you moved clusters off IRSA, and what kept workloads on it? Share it in the comments.

Glossary

EKS Pod Identity
An EKS feature that gives pods IAM credentials through an association between a service account and an IAM role.
IRSA
IAM roles for service accounts: pod credentials through a per-cluster OIDC provider and a service account annotation.
Pod Identity Agent
The DaemonSet on each node that serves credentials to pods at 169.254.170.23.
Pod Identity association
The EKS object that maps a cluster, namespace and service account to an IAM role.
EKS Auth API
The API the agent calls to exchange a pod’s token for role credentials.
Session tags
Key-value tags attached to a role session that IAM policies can test.
Target role
A role in another account that EKS assumes after the Pod Identity role, for cross-account access.
Session policy
An inline policy that limits a role session to the intersection of its permissions.

References & Further Reading


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.