Removing static AWS keys from Spark and Trino, and what they were hiding

Moving Spark, Trino and a Hive Metastore off static AWS keys: the SDK check that blocked Pod Identity, a node-role fallback, and a crash with a clock in it.

Published
Updated
Reading time
19 min read
Schematic of one ordered AWS credential chain: Pod Identity blocked by an endpoint-mode check, IRSA resolving, static keys ranked below, and the EC2 instance profile deliberately excluded Schematic of one ordered AWS credential chain: Pod Identity blocked by an endpoint-mode check, IRSA resolving, static keys ranked below, and the EC2 instance profile deliberately excluded
The keys were never the only credential in the pod. Removing them is how you find out which other ones were there.
On this page

Static AWS keys are easy to remove and hard to replace. Delete four lines from a SparkApplication manifest, annotate a service account, and the job assumes a role. That was the whole plan, written up in a research note before any change: Pod Identity rather than IRSA, no functional change to application code, four manifest lines removed per job.

None of it happened that way. The keys had been the first credential every component found, so they had been hiding everything behind them: a provider the SDK refused on an IPv6 cluster, a node-role fallback that made a correct policy look broken, a connector with its own credential chain, an HTTP client that had never been loaded, and a shared object that a short-lived client was quietly allowed to close.

Operating rule. A static key does not just grant access. It decides which code path runs. Remove it and every component falls through to whatever it would have done without it, so the migration is an audit of those fall-through paths. Build one ordered chain, leave out the fallbacks you never want, fail at boot when nothing resolves, and call it finished only when the old identity goes silent in CloudTrail.

The plan, and what it assumed

The research note was careful. It traced every call site, quoted the AWS documentation on chain precedence, and got the hard requirement right: environment keys sit earlier in the default chain than Pod Identity, so creating the association while leaving the secret injected “changes nothing, silently”. It audited IAM actions from the code rather than a template, and warned that the S3 multipart actions are not optional for large ORC writes.

It was still wrong about most of the work, because it reasoned from documentation about components that did not follow it.

The plan said What happened
Use Pod Identity; the cluster has the agent and S3A’s default chain picks it up SDK 2.35.4 rejected the IPv6 credentials endpoint. Every workload in this migration moved to IRSA instead
Application code needs no functional change The default chain ranked keys first and ended at the instance profile. It was replaced with one explicit chain that fails at boot
The Kinesis reader resolves through the same chain The connector carries its own shaded SDK and default chain, where environment keys outrank web identity
The manifest change is four removed lines Plus a pinned HTTP client for the connector, which crash-looped on its first STS call
Not considered A short-lived S3 client closed the shared chain and killed streaming jobs about 6h50m after start
Not considered Trino pods kept pre-cutover keys in memory; any involuntary restart would have left them with no credentials

I would write the note again. It made the decisions reviewable and said what had been verified. A plan is a list of assumptions, though, and the useful thing to do with one is to find out which of them fail.

Pod Identity failed on a host check, and my first diagnosis was wrong

On staging, everything about Pod Identity was correct. The role, the inline policy and the association existed before the driver started. The pod received AWS_CONTAINER_CREDENTIALS_FULL_URI and a readable token, and curl against that endpoint from inside the pod returned HTTP 200 with credentials. The SDK still refused it:

The full URI (http://[fd00:ec2::23]/v1/credentials) contained within environment
variable AWS_CONTAINER_CREDENTIALS_FULL_URI has an invalid host. Host should resolve
to a loopback address or have the full URI be HTTPS.

The cluster is IPv6, so the webhook injects the agent’s IPv6 link-local address. The commit that switched Spark to IRSA explained the rejection like this: the SDK’s allow-list stores the host as [fd00:ec2::23] with brackets, URI.getHost() returns it without them, so the comparison never matches. An experiment against the 2.35.4 bundle seemed to confirm it, because the IPv6 URI was rejected and the IPv4 form, 169.254.170.23, was accepted.

That explanation is wrong, and writing this post is how I found out. java.net.URI.getHost() on Java 17 returns an IPv6 literal with its brackets, so the string comparison would match. The real gate is one method up. In 2.35.4 the host is accepted if it resolves to loopback, or if it is a known metadata endpoint for the current endpoint mode:

public boolean isMetadataServiceEndpoint(String host) {
    String mode = SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.getStringValueOrThrow();
    if ("IPV6".equalsIgnoreCase(mode)) {
        return VALID_LOOP_BACK_IPV6.contains(host);   // contains "[fd00:ec2::23]"
    }
    return VALID_LOOP_BACK_IPV4.contains(host);
}

AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE defaults to IPv4. On an IPv6 cluster nothing sets it, so the IPv6 endpoint is checked against the IPv4 list. Reproduced against the same bundle with no cluster at all:

IPv6 URI, endpoint mode unset    -> SdkClientException: ... has an invalid host ...
IPv6 URI, endpoint mode = IPv6   -> SdkClientException: Failed to load credentials from metadata service.
IPv4 URI, endpoint mode unset    -> SdkClientException: Failed to load credentials from metadata service.

The second and third lines are failures to connect, because a laptop has no agent. Both got past the host check. The bracket experiment had varied the address family and the mode-dependent list together, so it could not tell the two explanations apart.

Upstream agrees. The behaviour is tracked in aws/containers-roadmap#2683 with the workaround of setting the variable to IPV6, and SDK 2.48.1, released on 15 July 2026, fixed ContainerCredentialsProvider rejecting the IPv6 endpoint unless that variable was set. The image here shipped 2.35.4, and the same version is shaded inside the Kinesis connector, so the whole JVM was affected.

The wrong diagnosis did not change the decision. IRSA’s WebIdentityTokenFileCredentialsProvider reads a token file and validates no host, so it sidestepped the check whatever the cause. It did change what “revisit Pod Identity later” means: that needs one environment variable or one SDK upgrade, not a fixed JDK. A month later a Python consumer on another IPv6 cluster hit the same wall from the other side. Its image pinned botocore 1.29.71, from before Pod Identity existed, and refused the same address with Unsupported host 'fd00:ec2::23'. That one also moved to IRSA.

The fallback that made a correct policy look broken

The most expensive hour of the migration was spent on an IAM policy that was correct.

When Pod Identity failed to resolve on staging, nothing failed loudly. S3A is the Hadoop FileSystem connector for Amazon S3 and S3-compatible object stores. Spark and Hive use it to read and write objects through the standard file-system API. Related: The Spark 4 upgrade that succeeded and wrote nothing’s default provider list ends in IAMInstanceCredentialsProvider, which tries the container provider and then the EC2 instance profile. The job fell through to the node role, started, acquired executors, and returned a 403 on its checkpoint upload once per micro-batch for an hour. Every signal pointed at the policy. The role, the policy and the association were all fine. The identity was wrong, and nothing in the error said so.

The fix was to stop letting each client assemble its own chain. One object now owns credential resolution for the SDK clients and S3A, in a fixed order:

Position Provider Mechanism Why it is there, or not
1 ContainerCredentialsProvider Pod Identity First, so it works without a code change once the SDK accepts the endpoint
2 WebIdentityTokenFileCredentialsProvider IRSA The mechanism that actually resolves in-cluster today
3–4 System property and environment providers Static keys Accepted, but below both roles. The SDK default puts them first, which is how a stale exported pair shadows a role
5 ProfileCredentialsProvider Local profile or SSO Laptops
— Instance profile Node role Excluded. Nobody sets it on purpose, and it turns a broken identity into misleading 403s

The first version dropped static keys entirely. A day later they came back at positions three and four, because a chain that blocks a working credential source has no escape hatch while a role path is broken, and staging was in exactly that state. The instance profile stayed out. Nobody configures it on purpose, which is why it is dangerous.

private lazy val chain: AwsCredentialsProviderChain =
  AwsCredentialsProviderChain.builder()
    .reuseLastProviderEnabled(false)   // don't latch whichever provider won first
    .credentialsProviders(
      ContainerCredentialsProvider.create(),            // Pod Identity
      WebIdentityTokenFileCredentialsProvider.create(), // IRSA
      SystemPropertyCredentialsProvider.create(),       // static keys, ranked below roles
      EnvironmentVariableCredentialsProvider.create(),
      ProfileCredentialsProvider.create())              // local only
    .build()                                            // no instance profile, on purpose

// S3A takes class names by reflection, so derive them from the same list.
def configureS3A(conf: Configuration): Unit =
  conf.set("fs.s3a.aws.credentials.provider", s3aProviderList)

reuseLastProviderEnabled(false) matters because the SDK default caches whichever provider first succeeded for the life of the JVM. One transient failure at startup, such as a link-local route not yet programmed, would pin the wrong provider permanently. Each provider still caches its own credentials, so this is not an HTTP call per request.

That flag does not reach S3A. It is a property of AwsCredentialsProviderChain, which only the explicit SDK clients use. S3A builds its own AWSCredentialProviderList, and in hadoop-aws 3.5.0 that class hardcodes reuseLastProvider = true with no configuration key. The path carrying all the ORC traffic caches its first successful provider regardless. The first version of the code comment claimed otherwise; a review caught it.

The last piece is failing at boot. verifyOrFail() resolves the chain at the top of every entry point, before a SparkSession exists. An unresolvable identity is a configuration error. Without the check the job submits, acquires executors and logs a 403 per micro-batch indefinitely under restartPolicy: Always, looking healthy the whole time. The failure message names which mechanisms the environment advertises (presence only, never values), what the chain tried, and that the instance profile is deliberately not a fallback.

One detail cost a day: the success line was invisible in every driver log. The check runs before Spark initialises logging, so SLF4J was still on its no-op binder and the log4j call printed nothing. The failure path was legible only because it throws. The message now goes to stdout as well.

The connector that kept its own chain

The shared chain covers every client that accepts a provider object. The Kinesis connector does not accept one. It takes option strings and resolves credentials through its own shaded copy of the SDK’s DefaultCredentialsProvider:

SystemProperty -> EnvironmentVariable -> WebIdentity -> Profile -> Container -> InstanceProfile

Environment keys rank above web identity there: the opposite of the order enforced everywhere else. After the IRSA cutover on staging, CloudTrail showed the old IAM user still calling ListShards every minute. All 20 of its 20 most recent events came from that call, while every other path had moved to the role. It stopped only when the key variables were removed from the pod environment, after which CloudTrail recorded nothing further for that user. For that path the chain order was advisory. The only control was which credentials were present.

The same switch exposed a defect that static keys had kept dormant for as long as the job had existed. The first batch after cutover aborted on an executor:

java.lang.NoClassDefFoundError: org/apache/hc/client5/http/ConnectionKeepAliveStrategy
  at org.apache.spark.sql.kinesis.shaded.software.amazon.awssdk.core.internal.http...

The shaded SDK’s service loader lists three HTTP client implementations and picks the first, Apache HttpClient 5, which the image did not ship. It throws rather than falling through to the two that would have worked. With static keys the connector read credentials from the environment and never built an HTTP client for them. Under IRSA it has to call The Security Token Service (STS) API issues short-lived, scoped credentials in exchange for an authenticated identity. AWS defines it, and S3-compatible stores such as MinIO implement it.. So the driver started cleanly and the query died a minute later, on executors, because executors perform the reads. The fix pins the JDK client by its shaded property name; the unshaded name does nothing:

javaOptions: >-
  -Dorg.apache.spark.sql.kinesis.shaded.software.amazon.awssdk.http.service.impl=org.apache.spark.sql.kinesis.shaded.software.amazon.awssdk.http.urlconnection.UrlConnectionSdkHttpService

The JDK client is unpooled, and that trade-off is written next to the setting. The real fix is shipping HttpClient 5 in the base image.

A crash with a clock in it

A week after the chain shipped, streaming jobs in both production regions began dying with Connection pool shut down. Four crashes, all between 6h49m and 6h59m after driver start. Jobs restarted together stayed synchronised and crashed together.

  • 6h49m–6h59mafter driver start: four crashes with Connection pool shut down, in both production regions
  • 0 occurrencesof Connection pool shut down in either region in the 16 hours after the fix deployed; every job passed its first predicted crash point at about 6h50m, and most passed a second

Field observations from one migration across a few clusters, in August and September 2026, not a lab benchmark: the four crashes and the 16-hour window come from production logs recorded in commit messages and an incident write-up at the time. That window is short.

A failure that keeps time is a scheduler talking. The process ran a cleanup task every 6 hours that built a throwaway S3Client on the shared chain and closed it in a finally. In SDK v2, closing a client closes every closeable attribute of its configuration, including a credentials provider you passed in. AwsCredentialsProviderChain is closeable. Closing it closed the STS client that the IRSA provider refreshes through, and that pool is never reopened. Cached credentials kept working for the rest of their hour, so the crash landed at the next refresh: six hours plus the remainder of the cache window.

Why the streaming jobs crashed on a clock

S3Clientthrowaway, every 6 hours
Shared chainprocess-wide
STS clientIRSA refreshes through it
Streaming jobfrom driver start

The shared chain is passed to the throwaway client

A cleanup task builds an S3Client on the shared chain and closes it in a finally

  1. The process runs a cleanup task every 6 hours that builds a throwaway S3Client on the shared chain and closes it in a finally. Clock: a cleanup every 6 hours. STS connection pool: open.
  2. AwsCredentialsProviderChain is closeable. Closing the client closed the chain, and closing the chain closed the STS client that the IRSA provider refreshes through. That pool is never reopened. STS connection pool: shut down, never reopened.
  3. Cached credentials kept working for the rest of their hour. Credentials: cached, for the rest of their hour.
  4. The crash landed at the next refresh: six hours plus the remainder of the cache window. Four crashes, all between 6h49m and 6h59m after driver start, each with Connection pool shut down. Clock: 6h49m to 6h59m after driver start. Credentials: the next refresh.

The chain is wrapped in a provider that cannot be closed

The shared object returns nonCloseableChain, which is not SdkAutoCloseable

  1. The fix wraps the chain in a provider that cannot be closed. It delegates resolveCredentials() to the chain and keeps the chain's per-provider error text. STS connection pool: open.
  2. The cleanup still builds a throwaway S3Client every 6 hours and closes it. The provider it was given is not SdkAutoCloseable, so closing the client takes nothing process-wide with it. Clock: a cleanup every 6 hours. STS connection pool: open.
  3. After the fix deployed there were zero occurrences of Connection pool shut down in either region in the following 16 hours. Every job passed its first predicted crash point at about 6h50m, and most passed a second. Clock: past 6h50m, most past a second crash point.
In SDK v2, closing a client closes every closeable attribute of its configuration, including a credentials provider you passed in.

The SDK has a non-managed opt-out for user-supplied HTTP clients and nothing equivalent for credentials providers. This is not new. It is the hazard behind aws-sdk-java-v2#3493, where a shared DefaultCredentialsProvider.create() instance closed by one client broke every other client and create() was eventually deprecated. Iceberg hit it through a finalized S3FileIO (apache/iceberg#8601), Flink’s Kinesis sink through the same singleton (FLINK-32964), and a Pinot user on IRSA saw it at exactly the one-hour refresh. The fix wraps the chain in a provider that cannot be closed:

private lazy val nonCloseableChain: AwsCredentialsProvider = new AwsCredentialsProvider {
  override def resolveCredentials(): AwsCredentials = chain.resolveCredentials()
  override def toString: String = chain.toString // keep the chain's per-provider error text
}

def provider(): AwsCredentialsProvider = nonCloseableChain

It lives in the shared object rather than in the one caller because the trap is invisible at the point of use: nothing about client.close() says it will take a process-wide object with it. The test that guards it asserts the returned provider is not SdkAutoCloseable. It was checked by reverting the wrapper, which fails it. A second test pins that the raw chain is closeable, so the reason for the wrapper cannot quietly disappear. An in-cluster end-to-end test exists too, and is weak on a laptop: it passed with the wrapper reverted, because a local SSO profile serves cached credentials without the STS pool.

After the fix deployed there were zero occurrences of Connection pool shut down in either region in the following 16 hours. That window is short, but it is long enough to matter: every job passed its first predicted crash point at about 6h50m, and most passed a second.

Trino: the keys were gone, the pods just had not noticed

Trino’s catalogs came from a shared secret store, and two Trino deployments read the same keys. Migrating the first one rewrote the catalogs both consume: the static hive.s3.* keys removed, fs.native-s3.enabled and s3.use-web-identity-token-credentials-provider added. The second deployment kept working, which looked like success.

It was working on borrowed time. An init container copies catalog files at pod creation, so the running pods still held the pre-cutover keys. The service account had no IRSA annotation yet, so there was no token, and the web-identity flag is exclusive: no fallback chain. Any involuntary restart, whether consolidation, node replacement, eviction or spot reclaim, would hand a pod keyless catalogs and no token. Every S3 and Glue query on the heavier of the two deployments would have failed, at a time nobody chose.

The fix was one annotation, plus one habit. Render the manifest with kubectl --dry-run=client and resolve the role it names with aws iam get-role before merging. On staging, the infrastructure directory was named after the application while the service account carried a prefix, and the wrong role name shipped before anyone caught it.

Boundary. These are field observations from one migration across a few clusters, in August and September 2026, not a lab benchmark. The failure messages, the 6h49m–6h59m crash window across four crashes, the 16-hour post-fix window, the hour of per-batch 403s and the CloudTrail event counts come from production and staging logs recorded in commit messages and an incident write-up at the time. The SDK mechanism was reproduced on a laptop against the 2.35.4 bundle and read from its source. The bracket explanation was wrong, and this post corrects it. The claim that the 2.48.1 fix makes Pod Identity work for these images is upstream’s and is untested here.

What I would do first next time

The order matters more than any single step:

  • Inventory every component that resolves AWS credentials by itself: shaded SDKs inside connectors, init containers that copy config, sidecars, migration scripts. Each one is its own migration.
  • Read the SDK version in every image, including shaded copies, before choosing between Pod Identity and IRSA. On IPv6, check the endpoint-mode behaviour or use SDK 2.48.1 or later.
  • Build one ordered chain with roles above keys and the instance profile excluded; derive the S3A class list from the same definition.
  • Fail at boot when nothing resolves, and print which mechanism won to stdout, not only to a logger that may not exist yet.
  • Never let a short-lived client close a shared provider. Wrap it once, centrally, and test the property.
  • Restart every consumer after the secret changes. Do not trust running pods as evidence.
  • Watch CloudTrail for the old IAM user. Retire its keys only after it has been silent for a full cycle of every scheduled job.

Frequently asked questions

Why did EKS Pod Identity fail on an IPv6 cluster with the AWS SDK for Java v2?

On an IPv6 cluster the webhook injects AWS_CONTAINER_CREDENTIALS_FULL_URI=http://[fd00:ec2::23]/v1/credentials. SDK 2.35.4 only accepts that host when AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE is IPv6, and the default is IPv4, so it throws an invalid-host error. Set the variable, or use SDK 2.48.1 or later, which fixed it.

Should the EC2 instance profile be in a Spark job’s credential chain on EKS?

No. When the pod’s own identity fails, the instance profile silently hands the job the node role, and the resulting AccessDenied errors point at an IAM policy that is actually correct. Excluding it turns a wrong identity into an immediate, legible failure at boot.

Why does a Spark streaming job on IRSA crash hours after it starts?

An SDK v2 client closes the credentials provider it was given when the client is closed. If a short-lived client shares the process-wide chain, closing it shuts the STS client IRSA refreshes through, and the job dies at the next refresh. Wrap the shared chain in a provider that is not SdkAutoCloseable.

Is deleting the keys from the Kubernetes secret enough to finish an IRSA migration?

No. Anything that resolves credentials independently, like a shaded connector SDK, may rank environment keys above web identity and keep using them. Pods that copied config at creation keep stale keys in memory until they restart. Check CloudTrail for the old IAM user before you retire it.

This migration ran alongside the Spark 4 upgrade that wrote nothing and the Kinesis connector rework, and the Hive Metastore moved to IRSA a few days before its 4.x upgrade. The operating model behind it is on data platform practice; more on stateful workloads in Kubernetes.

Terms in this piece
S3A
S3A is the Hadoop FileSystem connector for Amazon S3 and S3-compatible object stores. Spark and Hive use it to read and write objects through the standard file-system API. Related: The Spark 4 upgrade that succeeded and wrote nothing
STS
The Security Token Service (STS) API issues short-lived, scoped credentials in exchange for an authenticated identity. AWS defines it, and S3-compatible stores such as MinIO implement it.

Basant Bhattarai is a data and AI architect with 9+ years in industry. He leads a team of five engineers and the architecture of data and AI platforms end to end: the data model, the databases underneath, governance and SOC 2 controls, and the AI built into them. He writes up what he measures, with the method beside each figure.

Currently: Senior Data Engineer at UXCam.

Building something similar? I'm open to long-term consulting, contract or full-time roles. Work with me