简体   繁体   中英

How do I test if a bucket exists on AWS S3

How do I test if a bucket exists on AWS S3 using the aws-sdk?


This question is for testing if an object exists within a bucket: How to determine if object exists AWS S3 Node.JS sdk

This question is for Python: How can I check that a AWS S3 bucket exists?

You can use the following code:

// import or require aws-sdk as AWS
// const AWS = require('aws-sdk');

const checkBucketExists = async bucket => { 
  const s3 = new AWS.S3();
  const options = {
    Bucket: bucket,
  };
  try {
    await s3.headBucket(options).promise();
    return true;
  } catch (error) {
    if (error.statusCode === 404) {
      return false;
    }
    throw error;
  }
};

The important thing is to realize that the error statusCode will be 404 if the bucket does not exist.

To test if a bucket exists, you check the statusCode attribute from your createBucket callback method. If it is 409, then it has been created before. I hope this is clear enough?

const ID = ''//Your access key id
const SECRET = ''//Your AWS secret access key

const BUCKET_NAME = ''//Put your bucket name here

const s3 = new AWS.S3({
    accessKeyId: ID,
    secretAccessKey: SECRET
})

const params = {
    Bucket: BUCKET_NAME,
    CreateBucketConfiguration: {
        // Set your region here
        LocationConstraint: "eu-west-1"
    }
}
s3.createBucket(params, function(err, data) {
   if (err && err.statusCode == 409){
    console.log("Bucket has been created already");
   }else{
       console.log('Bucket Created Successfully', data.Location)
   }
})

Looks like after this change from aws-sdk v2 to v3 you can't do it with headBucket().

For those who are using v3 you could give this a shot:

const { S3Client, HeadBucketCommand } = require('@aws-sdk/client-s3');

const checkBucketExists = async (bucket) => {
    const client = new S3Client();
    const options = {
        Bucket: bucket,
    };

try {
    await client.send(new HeadBucketCommand(options));
    return true;
} catch (error) {
    if (error.statusCode === 404) {
        return false;
    }
    throw error;
}

Wanted to present an alternative approach using the Java SDK. LMK if I'm wrong, but it seems like to make a HeadBucketRequest, region needs to be specified, which is a burden. Code below instead relies on the GetBucketLocation API.

public class S3Validation {
    private final static Logger logger = LogManager.getLogger(S3Validation.class);
    enum BucketValidationStatus {
        SUCCESS,
        ACCESS_DENIED,
        NO_SUCH_BUCKET,
        UNKNOWN_ERROR
    }

    
    public static BucketValidationStatus validateBucket(String bucket) {
        String tempKey = "SOME_ACCESS_KEY";
        String tempSecret = "SOME_SECRET_KEY";
        
        AwsBasicCredentials awsCreds = AwsBasicCredentials.create(
                  tempKey,
                  tempSecret);

        
        S3Client s3Client = S3Client.builder()
                .credentialsProvider(StaticCredentialsProvider.create(awsCreds))
                .build();
    
        GetBucketLocationRequest getBucketLocationRequest = GetBucketLocationRequest.builder().bucket(bucket).build();
    try {
        GetBucketLocationResponse response = s3Client.getBucketLocation(getBucketLocationRequest);
        
    } catch(S3Exception f) {
        
        if (f.statusCode()==403) {
            return BucketValidationStatus.ACCESS_DENIED;
        }
        else if (f.statusCode()==404) {
            return BucketValidationStatus.NO_SUCH_BUCKET;
        }
        
        else {
            StringBuilder sb = new StringBuilder(50);
            sb.append("Unknown error for " + bucket + ": ");
            sb.append(f.statusCode() + ", " + f.awsErrorDetails().errorMessage());
            logger.error(sb.toString());
            return BucketValidationStatus.UNKNOWN_ERROR;
        }
    }
        return null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM