Nov 19, 20266 min read

Fix "Could Not Load Credentials" Errors in the AWS SDK

Why the AWS SDK for JavaScript, Python and Go cannot find credentials, how the default provider chain decides, and the fix for each environment: laptops, Docker, EC2, ECS, EKS and CI.

Illustration for Fix "Could Not Load Credentials" Errors in the AWS SDK

The AWS SDKs search for credentials in a fixed order, and the error appears only after every source in that chain came back empty. JavaScript reports "Could not load credentials from any providers", boto3 says "Unable to locate credentials", and Go ends with "no EC2 IMDS role found".

The fix is in the environment rather than the SDK call, so the first step is finding out which source you expected to win and why it is missing.

AWS credential errors at a glance

Where it failsLikely causeFix
LaptopNo profile, wrong AWS_PROFILE, expired SSO sessionaws configure sso or aws sso login
Docker on a laptopContainer cannot see ~/.aws or env varsMount the config read-only or pass env vars
Container on EC2IMDSv2 hop limit of 1Raise the hop limit to 2
ECS or FargateNo task role on the task definitionSet taskRoleArn
EKSNo Pod Identity association or IRSA annotationAssociate a role with the service account
CI (GitHub Actions)Missing credentials stepUse OIDC to assume a role

How does the default credential chain work?

Every current SDK follows the standardized credential provider chain, with small differences in order. Roughly, the SDK checks:

  1. Environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN).
  2. The shared config and credentials files in ~/.aws, for the profile in AWS_PROFILE or default, including SSO and credential_process entries.
  3. Web identity tokens (AWS_WEB_IDENTITY_TOKEN_FILE with AWS_ROLE_ARN), used by EKS IRSA.
  4. Container credentials (AWS_CONTAINER_CREDENTIALS_RELATIVE_URI or _FULL_URI), set by ECS and EKS Pod Identity.
  5. The EC2 instance metadata service, for an instance profile.

The first source that returns credentials wins, which explains the confusing case where a stale key in an environment variable overrides a correct role. The JavaScript and boto3 docs list each SDK's exact order.

Which provider is the SDK using?

Ask the SDK in the environment that fails: in Go, the retrieved credentials carry a Source, and the error lists what the last provider tried:

package main import ( "context" "fmt" "log" "github.com/aws/aws-sdk-go-v2/config" ) func main() { ctx := context.Background() cfg, err := config.LoadDefaultConfig(ctx) if err != nil { log.Fatal(err) // bad profile name or broken shared config } creds, err := cfg.Credentials.Retrieve(ctx) if err != nil { log.Fatalf("credential chain failed: %v", err) } // Source names the provider that won, e.g. EnvConfigCredentials, // SharedConfigCredentials or EC2RoleProvider. fmt.Printf("region=%s source=%s key=%s...\n", cfg.Region, creds.Source, creds.AccessKeyID[:4]) }

In Python, get_credentials() returns None when the chain is empty, and method names the winner:

import boto3 session = boto3.Session() creds = session.get_credentials() if creds is None: raise SystemExit("credential chain returned nothing") # method names the provider that won: env, shared-credentials-file, # sso, container-role, iam-role, assume-role-with-web-identity, ... print("region:", session.region_name, "method:", creds.method)

In Node.js, resolve the chain once at startup so the failure shows up immediately instead of on the first S3 or SQS call:

import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; try { const creds = await fromNodeProviderChain()(); console.log("resolved access key", creds.accessKeyId.slice(0, 4) + "..."); } catch (err) { // CredentialsProviderError: Could not load credentials from any providers console.error(err.name, err.message); process.exit(1); }

Fix it on a laptop

Check aws configure list, which shows the profile, the source of each value and the Region. With IAM Identity Center, an expired session is the usual cause, and aws sso login --profile dev refreshes it. A typo in AWS_PROFILE produces a profile-not-found error at config load, before the chain runs, which the Go sample above reports from LoadDefaultConfig.

Fix it in Docker

A container starts with neither your shell environment nor your home directory. For local testing, mount the config read-only and pass the profile:

~
$ docker run --rm -v $HOME/.aws:/root/.aws:ro -e AWS_PROFILE=dev my-api

Keys baked into an image leak with every copy of it, so leave them out. On EC2, containers reach the instance role through the metadata service, and with IMDSv2 the default hop limit of 1 drops the response before it reaches the container. AWS recommends a hop limit of 2 in container environments, set with aws ec2 modify-instance-metadata-options --http-put-response-hop-limit 2.

Fix it on ECS, EKS and CI

On ECS, the SDK reads credentials from the container endpoint only when the task definition has a task role. The task execution role is a different role, used by the agent to pull images and read secrets, and it does not give your code credentials.

On EKS, create a Pod Identity association for the namespace and service account, or annotate the service account for IRSA. A pod running under a different service account than the one you associated gets nothing and falls through to the node's instance metadata.

In GitHub Actions, use the aws-actions/configure-aws-credentials action with OIDC to assume a role per workflow, which exports short-lived credentials as environment variables for later steps.

Skip SDK credentials with Encore

Encore

Credential errors happen where code builds its own AWS clients and relies on the environment to supply keys. Encore is a backend framework with built-in infrastructure, where a bucket, database or Pub/Sub topic is declared in code. Encore provisions an IAM role for the service, and your handlers use the declared bucket rather than constructing an SDK client and walking the credential chain.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create exports-app --example=ts/hello-world$ cd exports-app && mkdir exports
// exports/exports.ts import { api, APIError } from "encore.dev/api"; import { Bucket } from "encore.dev/storage/objects"; // Declared in code: no access keys, no SDK client, no credential chain. export const exportsBucket = new Bucket("exports", { versioned: false }); interface SaveRequest { key: string; csv: string; } export const save = api( { expose: false, method: "POST", path: "/exports" }, async ({ key, csv }: SaveRequest): Promise<void> => { await exportsBucket.upload(key, Buffer.from(csv), { contentType: "text/csv" }); }, ); export const link = api( { expose: true, method: "GET", path: "/exports/:key/link" }, async ({ key }: { key: string }): Promise<{ url: string }> => { if (!(await exportsBucket.exists(key))) { throw APIError.notFound("no such export"); } const { url } = await exportsBucket.signedDownloadUrl(key, { ttl: 900 }); return { url }; }, );

encore run serves the bucket from local storage, so the code runs on a laptop with no AWS profile at all. On deploy to AWS, Encore creates the S3 bucket in your own account. Encore provisions an IAM role for the service.

The same property helps with coding agents: an agent can add a bucket and test it under encore run, which serves the bucket from local storage. On deploy, Encore provisions an IAM role for the service.

Best fit: TypeScript and Go teams that want declared resources to work locally and in production without managing credential chains, keys or roles per environment.

Frequently asked questions

What does "Could not load credentials from any providers" mean?

It is the CredentialsProviderError from the AWS SDK for JavaScript v3. The SDK walked its whole default chain, environment variables, shared config files, SSO, web identity, container and instance metadata, and none of them returned credentials. The fix is to make one of those sources available in the environment where the code runs.

Why do AWS credentials work on my laptop but not in Docker?

The container does not see your ~/.aws directory or your shell's environment variables unless you mount or pass them. On EC2, a container also needs the instance metadata hop limit raised to 2 to reach the instance role with IMDSv2.

Should I put access keys in environment variables in production?

No. On AWS compute, attach a role instead: an ECS task role, EKS Pod Identity or IRSA, an EC2 instance profile or a Lambda execution role. The SDK picks these up automatically, the credentials rotate on their own, and there is no long-lived key to leak.

How do I see which credentials the SDK is using?

Run aws sts get-caller-identity in the same environment, or ask the SDK directly. In boto3, Session().get_credentials().method names the provider, and in Go, the Source field on the retrieved credentials does the same. For Encore apps that use only declared resources, Encore provisions an IAM role for the service, so this check applies when your code still builds its own AWS clients.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders