Abhinav Dhiman
Abhinav Dhiman

Reputation: 755

NoCredentialError when trying to access head_object

I have the following code which runs as expected:

import boto3

session = boto3.Session(profile_name='default')
s3 = session.resource('s3')
bucketName = 'myBucketName'
bucket = s3.Bucket(bucketName)

for object_summary in bucket.objects.filter(Prefix="MainFolder/"):
    s3_cli = boto3.client('s3')
    if(object_summary.key[-1]!='/'):
        print('FileName: '+object_summary.key)
        # print(s3_cli.head_object(Bucket=bucketName,Key=str(object_summary.key)))
    else:
        s3obj='FolderName: '+object_summary.key
        print(s3obj)

And lists the files and folders present in MainFolder on my S3 bucket. However, when I uncomment Line#12, I get this error:

NoCredentialsError: Unable to locate credentials

Any idea what I am doing wrong?

Upvotes: 0

Views: 46

Answers (1)

Marcin
Marcin

Reputation: 238747

Instead of:

s3_cli = boto3.client('s3')

you should be using your session which loads the specific profile:

s3_cli = session.client('s3')

Upvotes: 1

Related Questions