Head Bucket
Determining if a bucket exists or not.
Components
- Credentials
- Bucket Name
- .NET
- PHP
- Python
- Javascript
- GO
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX - License - Identifier: Apache - 2.0
using Amazon;
using Amazon.S3;
using System;
using System.Threading.Tasks;
using Amazon.S3.Util;
namespace HeadBucket
{
class HeadBucket
{
// This example shows how to check a bucket existence.
// The examples uses AWS SDK for .NET 3.5 and .NET 5.0.
private static IAmazonS3 _s3Client;
// Specify the name of the bucket to check.
private const string BUCKET_NAME = "<BUCKET_NAME>";
static async Task Main()
{
var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("<ACCESS-KEY>", "<SECRET-KEY>");
var config = new AmazonS3Config { ServiceURL = "<ENDPOINT>" };
_s3Client = new AmazonS3Client(awsCredentials, config);
await HeadBucketAsync(_s3Client, BUCKET_NAME);
}
/// <summary>
/// HeadBucketAsync calls the DoesS3BucketExist method
/// to check if the S3 bucket bucketName exists.
/// </summary>
/// <param name="client">The Amazon S3 client object.</param>
/// <param name="bucketName">The name of the bucket to check.</param>
static async Task HeadBucketAsync(IAmazonS3 client, string bucketName)
{
bool bucketExists = await AmazonS3Util.DoesS3BucketExistV2Async(client, bucketName);
if(bucketExists)
{
Console.WriteLine("Bucket Exists");
}
else
{
Console.WriteLine("Bucket DOES NOT Exists");
}
Console.WriteLine(bucketExists);
}
}
}
<?php
require('client.php');
function headBucket($s3Client, $bucketName)
{
try {
$result = $s3Client->headBucket([
'Bucket' => $BUCKET_NAME, // REQUIRED
]);
} catch (AwsException $e) {
return 'Error: ' . $e->getAwsErrorMessage();
}
}
echo headBucket($client, 'sample-bucket-4');
import boto3
import logging
from botocore.exceptions import ClientError
logging.basicConfig(level=logging.INFO)
try:
s3_client = boto3.client(
's3',
endpoint_url='endpoint_url',
aws_access_key_id='access_key',
aws_secret_access_key='secret_key'
)
except Exception as exc:
logging.error(exc)
else:
try:
response = s3_client.head_bucket(Bucket="my_bucket_name")
except ClientError as err:
status = err.response["ResponseMetadata"]["HTTPStatusCode"]
errcode = err.response["Error"]["Code"]
if status == 404:
logging.warning("Missing object, %s", errcode)
elif status == 403:
logging.error("Access denied, %s", errcode)
else:
logging.exception("Error in request, %s", errcode)
else:
print(response)
const { S3Client, HeadBucketCommand } = require('@aws-sdk/client-s3');
// Create an S3 client service object
const s3 = new S3Client({
region: 'default',
endpoint: 'endpoint_url',
credentials: {
accessKeyId: 'access_key',
secretAccessKey: 'secret_key',
},
});
const run = async () => {
try {
const data = await s3.send(
new HeadBucketCommand({
Bucket: 'sample-bucket'
})
);
console.log(data);
} catch (err) {
console.log('Error', err);
}
};
run();
package main
import (
"fmt"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)
// GetBucket determines whether we have this bucket
//
// Usage:
// go run s3_head_bucket BUCKET_NAME
func main() {
if len(os.Args) != 2 {
exitErrorf("bucket name required\nUsage: %s bucket_name", os.Args[0])
}
bucket := os.Args[1]
sess, err := session.NewSession(&aws.Config{
Credentials: credentials.NewStaticCredentials("<ACCESS_KEY>", "<SECRET_KEY>", ""),
})
svc := s3.New(sess, &aws.Config{
Region: aws.String("default"),
Endpoint: aws.String("<ENDPOINT_URL>"),
})
// Try to access bucket
_, err = svc.HeadBucket(&s3.HeadBucketInput{
Bucket: aws.String(bucket),
})
if err != nil {
exitErrorf("Unable to check for bucket %q, %v", bucket, err)
}
fmt.Printf("Successfully read bucket %q\n", bucket)
}
func exitErrorf(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg+"\n", args...)
os.Exit(1)
}
The following command can be used to execute the aforementioned code, presuming the code file is called s3_head_bucket.go:
go run s3_head_bucket.go BUCKET_NAME