NoCredentialsError
botocore.exceptions.NoCredentialsError
Stack trace
botocore.exceptions.NoCredentialsError: Unable to locate credentials
File "/usr/local/lib/python3.9/site-packages/botocore/session.py", line 1234, in get_credentials
raise NoCredentialsError()
Why it happens
boto3 relies on AWS credentials configured via environment variables, config files, or IAM roles. If none are found, botocore raises NoCredentialsError indicating it cannot authenticate requests to AWS Bedrock.
Detection
Catch NoCredentialsError exceptions when creating or calling boto3 clients and log missing credentials errors before retrying or failing.
Causes & fixes
AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables are not set
Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in your environment before running the application.
AWS credentials file (~/.aws/credentials) is missing or misconfigured
Create or fix the ~/.aws/credentials file with valid AWS keys under the correct profile.
Running on an EC2 or container without an attached IAM role or instance profile
Attach a proper IAM role with Bedrock permissions to the EC2 instance or container.
Code: broken vs fixed
import boto3
client = boto3.client('bedrock') # This line raises NoCredentialsError if no credentials
response = client.invoke_model(ModelId='my-model', Body=b'input data')
print(response) import os
import boto3
os.environ['AWS_ACCESS_KEY_ID'] = 'your_access_key_here' # Set your AWS access key
os.environ['AWS_SECRET_ACCESS_KEY'] = 'your_secret_key_here' # Set your AWS secret key
client = boto3.client('bedrock') # Credentials now found
response = client.invoke_model(ModelId='my-model', Body=b'input data')
print(response) Workaround
Wrap boto3 client calls in try/except NoCredentialsError and prompt for credentials or load them dynamically from a secure vault before retrying.
Prevention
Use IAM roles for EC2 or containers, or configure AWS CLI with credentials files and environment variables to ensure boto3 always finds valid credentials.