Botocore.exceptions.NoCredentialsError: Unable to locate credentials error occurs when your AWS credentials are missing, invalid, or cannot be located by your Python script.
Here are two ways to fix the error:
- Create a .env or config file ~/.aws/credentials.
- Using Amazon CLI
Common reasons for the error
- Credentials are not set up properly.
- Credentials are not located in the correct location.
- Credentials are not associated with the correct IAM user or role.
- Credentials are not valid.
Flow diagram
Reproduce the error
import boto3
s3 = boto3.client('s3')
bucket = s3.create_bucket(Bucket='main-bucket')
try:
bucket.put(Key='file.txt', Body='Budget, 2023!')
except AttributeError as e:
print(e)
Output
botocore.exceptions.NoCredentialsError: Unable to locate credentials
How to fix the error
Solution 1
To fix the error, create a .env or config file ~/.aws/credentials and set the environment variables: AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY like this:
[default]
aws_access_key_id=XXXXXXXXXXXXXX
aws_secret_access_key=YYYYYYYYYYYYYYYYYYYYYYYYYYY
You can specify which profile to use in boto3 using session = boto3.Session(profile_name=<your_profile>).
You can also specify the credentials in your code using boto3.Session
.
import boto3
session = boto3.Session(
aws_access_key_id='ACCESS_KEY',
aws_secret_access_key='SECRET_KEY'
)
s3 = session.client('s3')
Don’t use this approach in production. Instead, consider injecting environment configs into the code, as we already saw in this article.
Using IAM roles
Another way to set up the aws credentials is by using the IAM roles when running code on an EC2 instance or using other AWS services to interact with S3.
You need to make sure to use the correct credentials and that they have the necessary permissions to perform the actions you are trying to perform with S3.
Create an AWS credentials file, typically at ~/.aws/credentials on a Linux or macOS system or at C:\Users\UserName\.aws\credentials on Windows.
The credentials file stores the AWS access key ID and secret access key, which are used to authenticate your requests to AWS services.
[FirstProfile]
aws_access_key_id = yourAccessId
aws_secret_access_key = yourSecretKey
[SecondProfile]
aws_access_key_id = yourAccessId
aws_secret_access_key = yourSecretKey
In the above code, we created two profiles, FirstProfile and SecondProfile, each with its own AWS access key ID and secret access key. This allows you to have multiple credentials for different AWS accounts or purposes within a single AWS account.
Your Python script should look like this code.
import boto3
import os
os.environ['AWS_PROFILE'] = "FirstProfile"
os.environ['AWS_DEFAULT_REGION'] = "us-east-1"
s2 = boto3.client('s2')
Solution 2: Using Amazon CLI
You can try adding your credentials using AmazonCLI using this command.
aws configure
And then, you can fill in your keys and region.
Related posts
ImportError: cannot import name ‘docevents’ from ‘botocore.docs.bcdoc’